I create a CRUD application using SpringBoot. I use PostgreSQL as a database. My application also uses SpringSecurity. The methods of displaying and creating objects work perfectly. But for some reason, updating and deleting the same objects gives an error:
2022-11-01 08:51:14.602 WARN 12149 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
I think the problem is in the html code. I use Thymeleaf.
**My Student Controller:
**
package ru.connor.FirstSecurityApp.controllers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.connor.FirstSecurityApp.model.Student;
import ru.connor.FirstSecurityApp.services.StudentService;
import javax.validation.Valid;
import java.util.Optional;
#Controller
#RequestMapping("/students")
#RequiredArgsConstructor
public class StudentController {
private final StudentService studentService;
#GetMapping()
public String showAllClasses(Model model) {
model.addAttribute("students", studentService.showAllStudent());
return "main/AllClasses";
}
#GetMapping("/{id}")
public String showById(#PathVariable("id") int id, Model model){
Optional<Student> student = Optional.ofNullable(studentService.showStudentById(id));
if (student.isEmpty()){
return "main/students/errorPage";
}else model.addAttribute("student", student);
return "main/students/index";
}
#GetMapping("/add")
public String addStudent(#ModelAttribute("student") Student student) {
return "main/students/new";
}
#PostMapping()
public String create(#ModelAttribute("student") #Valid Student student,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return "main/students/new";
studentService.addStudent(student);
return "redirect:/students";
}
#GetMapping("/{id}/edit")
public String edit(Model model, #PathVariable("id") int id) {
model.addAttribute("student", studentService.showStudentById(id));
return "main/students/edit";
}
#PatchMapping("/{id}")
public String update(#ModelAttribute("student") #Valid Student student, BindingResult bindingResult, #PathVariable("id") int id) {
if (bindingResult.hasErrors()){
return "main/students/edit";}
studentService.update(id, student);
return "redirect:/students";
}
#DeleteMapping("/{id}")
public String delete(#PathVariable("id") int id){
Optional<Student> student = Optional.ofNullable(studentService.showStudentById(id));
if (student.isPresent()){
studentService.delete(id);
return "redirect:/students";
}
return "main/students/index";
}
}
Student Service:
package ru.connor.FirstSecurityApp.services;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.connor.FirstSecurityApp.model.Student;
import ru.connor.FirstSecurityApp.repository.StudentsRepository;
import java.util.List;
import java.util.Optional;
#Service
#RequiredArgsConstructor
#SuppressWarnings("unused")
#Transactional(readOnly = true)
public class StudentService {
private final StudentsRepository studentsRepository;
public List<Student> showAllStudent(){
return studentsRepository.findAll();
}
public Student showStudentById(int id){
Optional<Student> foundPerson = studentsRepository.findById(id);
return foundPerson.orElse(null);
}
#Transactional
public void addStudent(Student student){
studentsRepository.save(student);
}
#Transactional
public void update(int id, Student person){
person.setId(id);
studentsRepository.save(person);
}
#Transactional
public boolean delete(int id){
if (studentsRepository.findById(id).isPresent()){
studentsRepository.deleteById(id);
return true;
}
return false;
}
}
**HTML view where the delete form is specified:
**
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Student</title>
</head>
<body>
<h1 th:text="${student.get().getFullStudentName()}"></h1>
<hr>
<form method="post" th:action="#{/students/{id}(id=${student.get().getId()})}">
<input type="submit" value="Delete">
</form>
</body>
</html>
As you have mentioned #PatchMapping for updates then you need the HTTP PATCH method instead of POST. The same goes for delete you have used #DeleteMapping, so you need to use the HTTP DELETE method instead of POST.
Create -> POST
Read -> GET
Update -> PUT/PATCH
Delete -> DELETE
With form submit I don't think PATCH/PUT/DELETE will work so in that case you need to change #PatchMapping/#DeleteMapping to #PostMapping and update the URL so it will be unique for update/delete.
PUT/PATCH/DELETE will work with REST API only.
I have been trying to display a table in JSP for which I am using this while loop code as given below, the problem is that it is difficult for me to convert my scriptlets into JSTL especially the rs.getInt("id") and I am using JSTL so that I can encode the URL together.
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/login";
String username = "root";
String password = "your-password";
String query = "select * from employeesloginaccount";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
%>
<tr>
<td><%=rs.getInt("id")%></td>
<td><%=rs.getString("first_name")%></td>
<td><%=rs.getString("last_name")%></td>
<td>
<c:url value ="${pageContext.request.contextPath}/downloadFileServlet" var = "myURL">
<c:param name = "id" value = "<%=rs.getInt(id)%>"/>
</c:url>
<form method="get"
action="<c:import url = "${myURL}"/>">
<input style="text-align: center" type="submit" value="Save">
</form>
</td>
</tr>
<%
}
I think it might be worth considering this answer from BalusC on the question, "How to avoid Java code in JSP files?"
The use of scriptlets (those <% %> things) in JSP is indeed
highly discouraged since the birth of taglibs (like JSTL) and
EL (Expression Language, those ${} things) over a decade ago.
The major disadvantages of scriptlets are:
Reusability: you can't reuse scriptlets.
Replaceability: you can't make scriptlets abstract.
OO-ability: you can't make use of inheritance/composition.
Debuggability: if scriptlet throws an exception halfway, all you get is a blank page.
Testability: scriptlets are not unit-testable.
Maintainability: per saldo more time is needed to maintain mingled/cluttered/duplicated code logic.
Your specific problem here is Maintainability.
What you should be doing is seperating the logic of your application so that you can have a high level of reusability/testability/debuggability/maintainability etc.. Let's start by creating a java class for your database connection, maybe something like this:
public class DBConnection {
private static String url = null;
private static Connection conn = null;
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://localhost:3306/login";
conn = DriverManager.getConnection(url,"root","your-password");
} catch (Exception e) {
System.out.println(e);
}
return conn;
}
}
Then you can use this class whenever you want to connect to your database and do something from other classes, in the examples below we will create an object to handle your employee data and then use that to get information from your database:
public class EmployeeObject {
int id;
String firstname;
String lastname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
Now that we have this object class, let's say you have another class called Employees, and in this class you have a method which gets employee info from the employeesloginaccount table:
public class Employees {
public List<EmployeeObject> getEmployeeInfo(){
//this class will return a list of EmployeeObjects from the database.
ArrayList<EmployeeObject> employees = new ArrayList<EmployeeObject>();
//get connection from our DBConneciton class we created earlier
try(Connection conn= DBConnection.getConnection()){
PreparedStatement pst = conn.prepareStatement("select * from employeesloginaccount;");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
//for each result in database, create an EmployeeObject
EmployeeObject employee = new EmployeeObject();
int id = rs.getInt("id");
employee.setId(id);
String fname = rs.getString("first_name");
employee.setFirstname(fname);
String lname = rs.getString("last_name");
employee.setLastname(lname);
employees.add(employee); // add each EmployeeObject to the arrayList of EmployeeObject's
}
} catch (SQLException e) {
e.printStackTrace();
}
return employees; //return all the results
}
}
Then you create a Servlet which will get this information, let's make it easy and put our code in the doGet method of the servlet so that whenever we visit the URL for this Servlet we will call this code (in this case i called my Servlet Test, with url mapping /Test:
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Employees e = new Employees(); //instantiate the Employees class
List<EmployeeObject> employees = e.getEmployeeInfo(); //get employee info from database
request.setAttribute("employees", employees); //set this list of employees to the request so we can access it in our jsp
RequestDispatcher rd = request.getRequestDispatcher("example.jsp"); //change to whatever your jsp is that you want to view the information
rd.forward(request, response);
}
}
And finally in our jsp page where we can view this information:
<!DOCTYPE HTML>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<table style="width:100%;">
<thead>
<tr>
<td>id</td>
<td>Firstname</td>
<td>Lastname</td>
</tr>
</thead>
<tbody>
<!-- for each item in our employees list create a variable called "employee" -->
<c:forEach items="${employees}" var="employee">
<tr>
<td>${employee.id}</td>
<td>${employee.firstname}</td>
<td>${employee.lastname}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
Let me know if that helps you or if you have any questions. :)
So .. I have two tables Utilisateur and ReponsesTickets ( there's no trouble inserting selecting updating deleting from each table by itself) to make a join between these two tables i had to create a new Entity here's its code.
package projet.helpdesk.beans;
import java.sql.Timestamp;
//TEXTE - DATE_POST - NOM - PRENOM - AGENCE - POSTE - DEPARTEMENT - ID_EMPLOYE
public class Jointure1 {
private String texte;
private String nom;
private String prenom;
private String Agence;
private String poste;
private String departement;
private int id_employe;
private Timestamp date_post;
public String getTexte() {
return texte;
}
public void setTexte(String texte) {
this.texte = texte;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getAgence() {
return Agence;
}
public void setAgence(String agence) {
Agence = agence;
}
public String getPoste() {
return poste;
}
public void setPoste(String poste) {
this.poste = poste;
}
public String getDepartement() {
return departement;
}
public void setDepartement(String departement) {
this.departement = departement;
}
public int getId_employe() {
return id_employe;
}
public void setId_employe(int id_employe) {
this.id_employe = id_employe;
}
public Timestamp getDate_post() {
return date_post;
}
public void setDate_post(Timestamp date_post) {
this.date_post = date_post;
}
}
That's the SQL instruction i'm trying to translate into JPQL.
SELECT u.nom, u.prenom, r.texte, r.date_post
FROM Utilisateur u, ReponseTicket r
WHERE u.id_emp = r.id_employe
AND r.id_ticket = ? ( parameter here )
This is the method in the DAO pattern.
private static final String PARAM_TICKET = "id_ticket";
private static final String JPQL_SELECT ="SELECT u.nom, u.prenom, r.texte, r.date_post FROM Utilisateur u JOIN ReponseTicket r ON u.id_emp = r.id_employe AND r.id_ticket=:id_ticket";
//^ Above is the JPQL instruction, not sure if it's correct.
#PersistenceContext( unitName = "bdd_helpdesk_PU" )
private EntityManager em;
public List<Jointure1> trouverJointure( int id_ticket ) throws DAOException {
List<Jointure1> liste;
TypedQuery<Jointure1> query = em.createQuery(JPQL_SELECT, Jointure1.class);
query.setParameter(PARAM_TICKET, id_ticket);
try {
liste = (List<Jointure1>) query.getResultList();
} catch ( NoResultException e ) {
return null;
} catch(Exception e) {
throw new DAOException(e);
}
return liste;
}
Then goes the ResponseForm that communicates with the DAO method.
this method collects the ticket id from the request and passes it to the DAOmethod to insert it into the JPQL instruction.
public List<Jointure1> recupererJointure(HttpServletRequest request)
{
List<Jointure1> ljointure;
int id = getId_ticket(request);
if(id!=0){
ljointure = reponseDao.trouverJointure(id);
}else ljointure=null;
return ljointure;
}
Stacktrace:
Caused by: Exception [EclipseLink-6168] (Eclipse Persistence Services - 2.6.1.v20150605-31e8258): org.eclipse.persistence.exceptions.QueryException
Exception Description: Query failed to prepare, unexpected error occurred: [java.lang.NullPointerException].
Internal Exception: java.lang.NullPointerException
Query: ReportQuery(referenceClass=Utilisateur jpql="SELECT u.nom, u.prenom, r.texte, r.date_post FROM Utilisateur u JOIN ReponseTicket r ON u.id_emp = r.id_employe AND r.id_ticket=:id_ticket")
I don't know about the null pointer exception, the parameter id_ticket is visible in the URL.
However i didn't add the new Entity in the persistence.xml
http://localhost:4040/monprojet2/reponsesticket?id_ticket=62
This is the servlet.
package projet.helpdesk.servlets;
#WebServlet(urlPatterns={"/reponsesticket"})
public class Reponsestickets extends HttpServlet {
#EJB
private TicketDao ticketDao;
#EJB
private ReponseTicketDao reponseDao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CreationTicketForm ticketform = new CreationTicketForm(ticketDao);
Ticket ticket = ticketform.recupererTicket(request);
CreationReponseForm reponse = new CreationReponseForm(reponseDao);
List<Jointure1> listereponse = reponse.recupererJointure(request);
if(ticket==null)
{
response.sendRedirect("/connexion");
} else {
request.setAttribute("lreponse", listereponse);
request.setAttribute("ticket", ticket);
this.getServletContext().getRequestDispatcher("/WEB-INF/ReponsesTickets.jsp").forward(request, response);
}
}
}
EDIT:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Réponses ticket</title>
<meta http-equiv="Content-Type" content="text/html">
<link type="text/css" rel="stylesheet" href="inc/style.css" />
</head>
<body>
<p>Test---> <br>votre id:${masession.idemp}<br>
Type:${masession.type}<br>
</p>
<fieldset>
<legend>Réponses pour ticket id: ${ticket.id_ticket}</legend><br>
<p>Sujet:</p> ${ticket.sujet} <br>
<p>Description:</p> ${ticket.description}<br>
</fieldset>
<br>
<c:forEach items="${lreponse}" var="reponse">
<p>Nom: ${reponse.nom}</p>
<p>Prenom: ${reponse.prenom }</p>
<p>Réponse: ${reponse.texte }</p>
<p>Date: ${reponse.date_post }</p>
<br><br>
</c:forEach>
<br><br><br>
<fieldset>
<legend>Répondre:</legend>
<form method="post" action="creerreponse" enctype="application/x-www-form-urlencoded">
<textarea rows="5" cols="36" name="texte"></textarea>${erreurs['texte']}<br/>
<input type="hidden" name="id_employe" value="${masession.idemp}">
<input type="hidden" name="id_ticket" value="${ticket.id_ticket}">
<input type="hidden" name="type" value="${masession.type}">
<input type="submit" value="Valider"><br/>
</form>
<p></p>
</fieldset>
</body>
</html>
Stacktrace:
[2017-05-03T16:47:49.790+0100] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=30 _ThreadName=http-listener-1(4)] [timeMillis: 1493826469790] [levelValue: 900] [[
StandardWrapperValve[projet.helpdesk.servlets.Reponsestickets]: Servlet.service() for servlet projet.helpdesk.servlets.Reponsestickets threw exception
java.lang.NumberFormatException: For input string: "nom"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at javax.el.ArrayELResolver.toInteger(ArrayELResolver.java:378)
at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:198)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:188)
at com.sun.el.parser.AstValue.getValue(AstValue.java:140)
at com.sun.el.parser.AstValue.getValue(AstValue.java:204)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at org.apache.jasper.runtime.PageContextImpl.evaluateExpression(PageContextImpl.java:1016)
at org.apache.jsp.WEB_002dINF.ReponsesTickets_jsp._jspx_meth_c_forEach_0(ReponsesTickets_jsp.java:143)
at org.apache.jsp.WEB_002dINF.ReponsesTickets_jsp._jspService(ReponsesTickets_jsp.java:85)
I´m trying to develop a simple example of new functionality of JSF 2.2, #FlowScope, I develop it with eclipse luna, glassfish 4.0, I guess the code is right cause I caught it on the web, probably the error is with the configuration of the project. Could anyone give me an Idea of what could be? Pleas ask me further information if it´s hard to understand with these few information but actually I don´t know what more I can write to help and this is my first question on stackoverflow.
public class NestedFlowBuilder implements Serializable {
private static final long serialVersionUID = 1L;
#Produces
#FlowDefinition
public Flow defineCallingFlow
(#FlowBuilderParameter FlowBuilder flowBuilder) {
String flowId = "secondJavaFlow";
flowBuilder.id("", flowId);
flowBuilder.viewNode(flowId, "/java-calling-flow/start-page.xhtml")
.markAsStartNode();
flowBuilder.viewNode("results",
"/java-calling-flow/results-page.xhtml");
flowBuilder.returnNode("return").fromOutcome("/return-page-for-java-calling-flow");
flowBuilder.returnNode("home").fromOutcome("/index");
flowBuilder.flowCallNode("go-to-nested")
.flowReference("", "thirdJavaFlow")
.outboundParameter("paramForNestedFlow",
"#{javaCallingFlowBean.param1}");
return(flowBuilder.getFlow());
}
#Produces
#FlowDefinition
public Flow defineNestedFlow
(#FlowBuilderParameter FlowBuilder flowBuilder) {
String flowId = "thirdJavaFlow";
flowBuilder.id("", flowId);
flowBuilder.viewNode(flowId,
"/java-nested-flow/start-page.xhtml")
.markAsStartNode();
flowBuilder.viewNode("results",
"/java-nested-flow/results-page.xhtml");
flowBuilder.returnNode("return-to-previous-start")
.fromOutcome("secondJavaFlow");
flowBuilder.returnNode("return-to-previous-results")
.fromOutcome("results");
flowBuilder.inboundParameter("paramForNestedFlow",
"#{javaNestedFlowBean.param3}");
return(flowBuilder.getFlow());
}
package coreservlets;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.flow.FlowScoped;
import javax.inject.Named;
#Named
#FlowScoped("thirdJavaFlow")
public class JavaNestedFlowBean implements Serializable {
private static final long serialVersionUID = 1L;
private String param3, param4;
public String doFlow() {
if (param3.equalsIgnoreCase(param4)) {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage fMessage =
new FacesMessage("Params must be distinct");
fMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
context.addMessage(null, fMessage);
return(null);
} else {
return("results");
}
}
public String getParam3() {
return param3;
}
public void setParam3(String param3) {
this.param3 = param3;
}
public String getParam4() {
return param4;
}
public void setParam4(String param4) {
this.param4 = param4;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Java Calling Flow Start PAge</title>
</head>
<body>
<h:form>
<h:messages globalOnly="true" styleClass="error"/>
<h:panelGrid columns="3" styleClass="formTable">
Param 1:
<h:inputText value="#{javaCallingFlowBean.param1}" id="param1"
required="true"
requiredMessage="Param 1 is required"/>
<h:message for="param1" styleClass="error"/>
Param 2:
<h:inputText value="#{javaCallingFlowBean.param2}" id="param2"
required="true"
requiredMessage="Param 2 is required"/>
<h:message for="param2" styleClass="error"/>
<f:facet name="footer">
<h:commandButton value="Show Results"
action="#{javaCallingFlowBean.doFlow}"/><br/>
</f:facet>
</h:panelGrid>
</h:form>
</body>
</html>
I get this error:
javax.el.ELException: /java-calling-flow/start-page.xhtml #17,40 value="#{javaCallingFlowBean.param1}": org.jboss.weld.context.ContextNotActiveException: WELD-001303 No active contexts for scope type javax.faces.flow.FlowScoped
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF-2.2-Faces-Flow-2.pdf from pag 33
I'm really in a grave problem with this. All of a sudden my properly working code has stopped working. I have no clue what so ever why!!!! And worst of all I have to deploy my project today :( . Don't know if it will be right to say or not but all of this started 2 days after adding PrimeFaces in build path. Can anyone please direct me to the right direction. Would be great help!
I have following configuration:
Glassfish v3
Mojara 2.1.6-FCS
JPA Eclipselink
Controller Bean
public List<Usergroupdetail> getUsergroupdetail_list() {
List<Usergroupdetail> myUserGroupDetail = new ArrayList<Usergroupdetail>(
lODBN.listUserGroupDetail(loginBean.getUsername()));
System.out.println("username found is:" + loginBean.getUsername());
return myUserGroupDetail;
}
For getting complete list of data from the JPA PoJO UserGroupReport
public List<Usergroupreport> getGroupId_list() {
List<Usergroupreport> myAllgroupIds = new ArrayList<Usergroupreport>(
lODBN.findAllGroupIdByUser(loginBean.getUsername()));
return myAllgroupIds;
}
Stack Trace
WARNING: PWC4011: Unable to set request character encoding to ISO-8859-1 from context /WebApp, because request parameters have already been read, or ServletRequest.getReader() has already been called
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
Login Bean
package bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
//import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import ejb.UserDaoBean;
import ejb.UserGroupDaoBean;
import model.User;
#ManagedBean(name = "loginBean")
#SessionScoped
public class LoginBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
private UserDaoBean uDB;
#EJB
private UserGroupDaoBean uGDB;
private User userId;
public List<User> usernameFirstLastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String firstName;
public String lastName;
public String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<User> getUsernameFirstLastName() {
List<User> myName = new ArrayList<User>(uDB.findFirtLastNames(username));
return myName;
}
public void setUsernameFirstLastName(List<User> usernameFirstLastName) {
this.usernameFirstLastName = usernameFirstLastName;
}
private String username;
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String login() {
FacesContext context = FacesContext.getCurrentInstance();
if (uDB.validateUser(username,password)) {
userId = uDB.findUser(username);
context.getExternalContext().getSessionMap().put("userId", userId);
if (uGDB.validateGroup(userId)) {
return "home.jsf?faces-redirect=true&includeViewParams=true";
}
return "normalHome.jsf?faces-redirect=true&includeViewParams=true";
} else {
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Username doesn't exists! OR User is trying to login from someone else's account");
context.addMessage("", message);
return "newloginerror.jsf?faces-redirect=true";
}
}
public String logout() {
FacesContext.getCurrentInstance().getExternalContext()
.invalidateSession();
return "logout.jsf?faces-redirect=true";
}
}
Login Page
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link href="./css/PageLayout.css" rel="stylesheet" type="text/css" />
<title>Login</title>
</h:head>
<h:body>
<f:view>
<div style="background-color: #205a8c; width: auto; height: 60px">
<h3 style="font-size: large; position: relative;" align="left">Lord
Of Data Web App</h3>
</div>
<div id="wrappers">
<div class="content pls centering">
<h:form>
<table class="form_table" style="background-color: silver;">
<tbody>
<tr>
<td>Username</td>
<td><h:inputText id="inputusername"
value="#{loginBean.username}" required="true"
requiredMessage="Username is required!"></h:inputText> <h:message
for="inputusername"></h:message></td>
</tr>
<tr>
<td>Password</td>
<td><h:inputSecret id="inputpassword"
value="#{loginBean.password}" required="true"
requiredMessage="Password is required!"></h:inputSecret> <h:message
for="inputpassword"></h:message></td>
</tr>
</tbody>
</table>
<div id="buttonsoptions" align="center" style="padding-top: 10px;">
<h:panelGroup>
<tr>
<td><h:commandButton id="login" value="Login"
action="#{loginBean.login}"></h:commandButton></td>
</tr>
</h:panelGroup>
</div>
</h:form>
</div>
</div>
</f:view>
</h:body>
</html>
EJB Code Snippet for Login Authentication
public boolean validateUser(String username, String password) {
try {
Query myQuery = entityManager.createNamedQuery("userverification")
.setParameter("username", username)
.setParameter("password", password);
User result = (User) myQuery.getSingleResult();
if (result != null) {
System.out.println("Loggin sucessful!");
return true;
} else {
System.out.println("User does not exists in the system");
return false;
}
} catch (NoResultException e) {
return false;
}
}
And I tried to use the username to my other session bean which was working perfectly fine until two days back. Here is the code for this bean where I am trying to call the Username picked from login bean
Bean
package bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import ejb.LODReportDaoBean;
import ejb.LordOfDataDaoBeanNormal;
import ejb.UserDaoBean;
import model.Lodreport;
import model.Usergroupdetail;
import model.Usergroupreport;
#ManagedBean(name = "lordOfDataNormalUserBean")
#SessionScoped
public class LordOfDataNormalUserBean implements Serializable {
/**
* #author Sushant Pandey
*/
private static final long serialVersionUID = 1L;
#EJB
private LordOfDataDaoBeanNormal lODBN;
#EJB
private UserDaoBean uDB;
#EJB
private LODReportDaoBean lONRDB;
#ManagedProperty(value = "#{loginBean}")
private LoginBean loginBean;
public LoginBean getLoginBean() {
return loginBean;
}
public void setLoginBean(LoginBean loginBean) {
this.loginBean = loginBean;
}
public List<Lodreport> lodnormal_list;
public List<Usergroupreport> usergroup_list;
public List<Usergroupdetail> usergroupdetail_list;
public List<Lodreport> findDataByRowId;
private Lodreport myreport = new Lodreport();
public Lodreport getMyreport() {
return myreport;
}
public void setMyreport(Lodreport myreport) {
this.myreport = myreport;
}
public void setFindDataByRowId(List<Lodreport> findDataByRowId) {
this.findDataByRowId = findDataByRowId;
}
public int security;
public String username;
public String access;
public String authentifizierteBenutzer;
public String auto;
public String comment;
public String comment1;
public String comment2;
public String comment3;
public String domain1;
public String domain2;
public String emailFeedback;
public String emailSendStatus;
public String lOD1CostCenter;
public String lOD1DisplayName;
public String lOD1Domain;
public String lOD1Mail;
public String lOD1User;
public String lOD2CostCenter;
public String lOD2DisplayName;
public String lOD2Domain;
public String lOD2Mail;
public String lOD2User;
public String rechteGruppeChange;
public String rechteGruppeRead;
public String type;
public int rowId;
public List<Usergroupreport> groupId_list;
public boolean edit;
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public void setGroupId_list(List<Usergroupreport> groupId_list) {
this.groupId_list = groupId_list;
}
public void setLodnormal_list(List<Lodreport> lodnormal_list) {
this.lodnormal_list = lodnormal_list;
}
public int getSecurity() {
return security;
}
public void setSecurity(int security) {
this.security = security;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccess() {
return access;
}
public void setAccess(String access) {
this.access = access;
}
public String getAuthentifizierteBenutzer() {
return authentifizierteBenutzer;
}
public void setAuthentifizierteBenutzer(String authentifizierteBenutzer) {
this.authentifizierteBenutzer = authentifizierteBenutzer;
}
public String getAuto() {
return auto;
}
public void setAuto(String auto) {
this.auto = auto;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getComment1() {
return comment1;
}
public void setComment1(String comment1) {
this.comment1 = comment1;
}
public String getComment2() {
return comment2;
}
public void setComment2(String comment2) {
this.comment2 = comment2;
}
public String getComment3() {
return comment3;
}
public void setComment3(String comment3) {
this.comment3 = comment3;
}
public String getDomain1() {
return domain1;
}
public void setDomain1(String domain1) {
this.domain1 = domain1;
}
public String getDomain2() {
return domain2;
}
public void setDomain2(String domain2) {
this.domain2 = domain2;
}
public String getEmailFeedback() {
return emailFeedback;
}
public void setEmailFeedback(String emailFeedback) {
this.emailFeedback = emailFeedback;
}
public String getEmailSendStatus() {
return emailSendStatus;
}
public void setEmailSendStatus(String emailSendStatus) {
this.emailSendStatus = emailSendStatus;
}
public String getlOD1CostCenter() {
return lOD1CostCenter;
}
public void setlOD1CostCenter(String lOD1CostCenter) {
this.lOD1CostCenter = lOD1CostCenter;
}
public String getlOD1DisplayName() {
return lOD1DisplayName;
}
public void setlOD1DisplayName(String lOD1DisplayName) {
this.lOD1DisplayName = lOD1DisplayName;
}
public String getlOD1Domain() {
return lOD1Domain;
}
public void setlOD1Domain(String lOD1Domain) {
this.lOD1Domain = lOD1Domain;
}
public String getlOD1Mail() {
return lOD1Mail;
}
public void setlOD1Mail(String lOD1Mail) {
this.lOD1Mail = lOD1Mail;
}
public String getlOD1User() {
return lOD1User;
}
public void setlOD1User(String lOD1User) {
this.lOD1User = lOD1User;
}
public String getlOD2CostCenter() {
return lOD2CostCenter;
}
public void setlOD2CostCenter(String lOD2CostCenter) {
this.lOD2CostCenter = lOD2CostCenter;
}
public String getlOD2DisplayName() {
return lOD2DisplayName;
}
public void setlOD2DisplayName(String lOD2DisplayName) {
this.lOD2DisplayName = lOD2DisplayName;
}
public String getlOD2Domain() {
return lOD2Domain;
}
public void setlOD2Domain(String lOD2Domain) {
this.lOD2Domain = lOD2Domain;
}
public String getlOD2Mail() {
return lOD2Mail;
}
public void setlOD2Mail(String lOD2Mail) {
this.lOD2Mail = lOD2Mail;
}
public String getlOD2User() {
return lOD2User;
}
public void setlOD2User(String lOD2User) {
this.lOD2User = lOD2User;
}
public String getRechteGruppeChange() {
return rechteGruppeChange;
}
public void setRechteGruppeChange(String rechteGruppeChange) {
this.rechteGruppeChange = rechteGruppeChange;
}
public String getRechteGruppeRead() {
return rechteGruppeRead;
}
public void setRechteGruppeRead(String rechteGruppeRead) {
this.rechteGruppeRead = rechteGruppeRead;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getRowId() {
return rowId;
}
public void setRowId(int rowId) {
this.rowId = rowId;
}
public void setUsergroup_list(List<Usergroupreport> usergroup_list) {
this.usergroup_list = usergroup_list;
}
public void setUsergroupdetail_list(
List<Usergroupdetail> usergroupdetail_list) {
this.usergroupdetail_list = usergroupdetail_list;
}
#PostConstruct
public void init() {
// getLodnormal_list();
getUsergroupdetail_list();
// getGroupId_list();
getUsername();
}
public String displayReport() {
getLodnormal_list();
return "reportLordOfDataNormal.jsf?faces-redirect=true";
}
public List<Lodreport> getLodnormal_list() {
List<Lodreport> myLodreport = new ArrayList<Lodreport>(
lODBN.reportLODNormal(loginBean.getUsername()));
System.out.println("LOD list for Username :" + loginBean.getUsername() );
return myLodreport;
}
public List<Usergroupreport> getUsergroup_list() {
return usergroup_list;
}
public List<Usergroupdetail> getUsergroupdetail_list() {
List<Usergroupdetail> myUserGroupDetail = new ArrayList<Usergroupdetail>(
lODBN.listUserGroupDetail(loginBean.getUsername()));
System.out.println("username found is:" + loginBean.getUsername());
return myUserGroupDetail;
}
public String editLODDataNormal() {
lODBN.updateExistingLODDataNormal(security, loginBean.getUsername(),
access, authentifizierteBenutzer, auto, comment, comment1,
comment2, comment3, domain1, domain2, emailFeedback,
emailSendStatus, lOD1CostCenter, lOD1DisplayName, lOD1Domain,
lOD1Mail, lOD1User, lOD2CostCenter, lOD2DisplayName,
lOD2Domain, lOD2Mail, lOD2User, rechteGruppeChange,
rechteGruppeRead, type, rowId);
return "reportLordOfDataNormal.jsf?faces-redirect=true";
}
public List<Usergroupreport> getGroupId_list() {
List<Usergroupreport> myAllgroupIds = new ArrayList<Usergroupreport>(
lODBN.findAllGroupIdByUser(loginBean.getUsername()));
return myAllgroupIds;
}
public void edit(Lodreport myreport) {
this.myreport = myreport;
edit = true;
}
public void saveMyReport(){
lONRDB.updateReport(myreport);
}
}