Avoiding entity update directly on form submit - jpa

I have an entity which is showed on the screen as text in input boxes which can be modified. When i submit the form hitting save, i would like my ejb3 component to handle the data and persist or merge it using the entity manager. But for some reason, when i modify the data and hit save the data directly gets updated in the database by-pasing my ejb3, which is certainly undesirable. My code looks like the following
#Entity
#Table(name = "EMP")
public class Emp implements java.io.Serializable {
private short empno;
private Dept dept;
private String ename;
private String job;
private Short mgr;
private Date hiredate;
private BigDecimal sal;
private BigDecimal comm;
public Emp() {
}
public Emp(short empno) {
this.empno = empno;
}
public Emp(short empno, Dept dept, String ename, String job, Short mgr,
Date hiredate, BigDecimal sal, BigDecimal comm) {
this.empno = empno;
this.dept = dept;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
}
#Id
#Column(name = "EMPNO", unique = true, nullable = false, precision = 4, scale = 0)
public short getEmpno() {
return this.empno;
}
public void setEmpno(short empno) {
this.empno = empno;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "DEPTNO")
public Dept getDept() {
return this.dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
#Column(name = "ENAME", length = 10)
#Length(max = 10)
public String getEname() {
return this.ename;
}
public void setEname(String ename) {
this.ename = ename;
}
#Column(name = "JOB", length = 9)
#Length(max = 9)
public String getJob() {
return this.job;
}
public void setJob(String job) {
this.job = job;
}
#Column(name = "MGR", precision = 4, scale = 0)
public Short getMgr() {
return this.mgr;
}
public void setMgr(Short mgr) {
this.mgr = mgr;
}
#Temporal(TemporalType.DATE)
#Column(name = "HIREDATE", length = 7)
public Date getHiredate() {
return this.hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
#Column(name = "SAL", precision = 7)
public BigDecimal getSal() {
return this.sal;
}
public void setSal(BigDecimal sal) {
this.sal = sal;
}
#Column(name = "COMM", precision = 7)
public BigDecimal getComm() {
return this.comm;
}
public void setComm(BigDecimal comm) {
this.comm = comm;
}
}
#Stateful
#Name("workflow")
#Scope(ScopeType.CONVERSATION)
public class WorkflowBean implements Workflow
{
#Logger private Log log;
#In StatusMessages statusMessages;
#PersistenceContext(type=PersistenceContextType.EXTENDED)
EntityManager entityManager;
#Out(required=false)
Emp employee = new Emp();
#RequestParameter("empEmpno")
String empNo;
public void workflow()
{
log.info("workflow.workflow() action called");
statusMessages.add("workflow");
}
#End
public boolean save(){
entityManager.merge(emp);
entityManger.flush();
}
#Begin(join=true)
public boolean populateEmp(){
entityManager.setFlushMode(FlushModeType.COMMIT);
System.out.println("The Emp No. is---"+empNo);
int no = Integer.parseInt(empNo);
short emp =(short)no;
employee = entityManager.find(Emp.class, emp);
entityManager.flush();
return true;
}
public Emp getEmployee() {
return employee;
}
public void setEmployee(Emp employee) {
this.employee = employee;
}
// add additional action methods
public String getEmpNo() {
return empNo;
}
public void setEmpNo(String empNo) {
this.empNo = empNo;
}
#Remove
#Destroy
public void destroy() {
}
}
My view looks like
<h:form id="emp" styleClass="edit">
<rich:panel>
<f:facet name="header">Edit Emp</f:facet>
<s:decorate id="empnoField" template="layout/edit.xhtml">
<ui:define name="label">Empno</ui:define>
<h:inputText id="empno"
required="true"
value="#{workflow.employee.empno}">
</h:inputText>
</s:decorate>
<s:decorate id="commField" template="layout/edit.xhtml">
<ui:define name="label">Comm</ui:define>
<h:inputText id="comm"
value="#{workflow.employee.comm}"
size="14">
</h:inputText>
</s:decorate>
<s:decorate id="enameField" template="layout/edit.xhtml">
<ui:define name="label">Ename</ui:define>
<h:inputText id="ename"
size="10"
maxlength="10"
value="#{workflow.employee.ename}">
</h:inputText>
</s:decorate>
<s:decorate id="hiredateField" template="layout/edit.xhtml">
<ui:define name="label">Hiredate</ui:define>
<rich:calendar id="hiredate"
value="#{workflow.employee.hiredate}" datePattern="MM/dd/yyyy" />
</s:decorate>
<s:decorate id="jobField" template="layout/edit.xhtml">
<ui:define name="label">Job</ui:define>
<h:inputText id="job"
size="9"
maxlength="9"
value="#{workflow.employee.job}">
</h:inputText>
</s:decorate>
<s:decorate id="mgrField" template="layout/edit.xhtml">
<ui:define name="label">Mgr</ui:define>
<h:inputText id="mgr"
value="#{workflow.employee.mgr}">
</h:inputText>
</s:decorate>
<s:decorate id="salField" template="layout/edit.xhtml">
<ui:define name="label">Sal</ui:define>
<h:inputText id="sal"
value="#{workflow.employee.sal}"
size="14">
</h:inputText>
</s:decorate>
<s:decorate id="deptField" template="layout/edit.xhtml">
<ui:define name="label">Department</ui:define>
<h:inputText id="dname"
value="#{workflow.deptName}">
</h:inputText>
</s:decorate>
<div style="clear:both">
<span class="required">*</span>
required fields
</div>
</rich:panel>
<div class="actionButtons">
<h:commandButton id="save"
value="Save"
action="#{workflow.save}"
rendered="true"/>
</div>
</h:form>

[It was difficult to address issue in comments for your response.]
There are few things which I haven't understand & why it's done that way.
Using transient fields, it will add overhead of adding those to entity object while persisting.
Why is auto-commit causes issue & can't be implemented.
Regardless of these things, you can try
Making the entity detached with entityManager.detach(entity) or clearing the persistence context with entityManager.clear(), detaching all the underlying entities. But prior one is more favourible.
Can manage transaction manually instead of container. Use BMT where you can have control over the operations.

Related

JPQL joining two tables and adding parameter generates eclipseLink error

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)

Spring form submit validation for foreign key

My project is a spring mvc project.In my project i have a domain Technology which has foreign key reference.When i validating on form submit it threw error....For view part(jsp),i using form:select for viewing department in technology.
How can i validate a foreign reference?????
i tried below code
domain
#Entity
#Table(name = "technology")
public class Technology {
private int id;
#NotEmpty
private String name;
#NotEmpty
private Department department;
private Date createdDate;
private boolean isDelete;
}
message.properties
NotEmpty.technology.department=Required!
Technology.jsp
<form:form method="post" action="add-technology"
commandName="technology" id="technologyForm">
<label>Technology Name</label>
<form:input path="name" /><form:errors path="name" class="error"></form:errors>
<br />
<label>Department</label>
<form:select path="department.id">
<form:option value="0" label="Select" />
<form:options items="${departments}" itemValue="id" itemLabel="name" />
</form:select><form:errors path="department" class="error"></form:errors>
<%-- <form:select path="department.id" items="${departments}" /> --%>
<input type="submit" class="btn btn-primary"/>
</form:form>
controller
#RequestMapping(value = "/add-technology")
public String addTechnology(
#ModelAttribute(value = "technology")#Valid Technology technology,
BindingResult result) {
if(result.hasErrors()){
return "/secure/admin/technology";
}
java.util.Date utilDate = new java.util.Date();
Date sqlDate = new Date(utilDate.getTime());
technology.setCreatedDate(sqlDate);
technologyService.saveTechnology(technology);
return "redirect:/technologies";
}
ERROR
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.UnexpectedTypeException: No validator could be found for type: com.company.product.domain.Department
How can i resolve this problem???
Here you have to implement validator for Technology object
class TechnologyValidator extends Validator {
public boolean supports(Class<?> cls) {
return Technology .class.equals(cls);
}
public void validate(Object target, Errors errors) {
super.validate(target, errors);
Technology tecObj= (Technology ) target;
//here i am assuming Technology name is REQUIRED and
//NotEmpty.technology.name is in message.properties
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name",
"NotEmpty.technology.name");
Department dept = tecObj.getDepartment();
//as from from your are binding department ID
if (dept==null || dept.getId()==null || dept.getId()==0L ) {
errors.rejectValue("department.id", "NotEmpty.technology.department");
}
}
}
And create bean of this class in Spring-context
#Autowired
TechnologyValidator techValid;
And call this validator in your controller like
#RequestMapping(value = "/add-technology")
public String addTechnology(
#ModelAttribute(value = "technology") Technology technology,
BindingResult result) {
//call validator
techValid.validate(technology, result);
if(result.hasErrors()){
return "/secure/admin/technology";
}
java.util.Date utilDate = new java.util.Date();
Date sqlDate = new Date(utilDate.getTime());
technology.setCreatedDate(sqlDate);
technologyService.saveTechnology(technology);
return "redirect:/technologies";
}

Getter gets called as many times as there are values in ArrayList for h:dataTable and Eclipse says "Method must have signature "String method ..." [duplicate]

This question already has answers here:
Why JSF calls getters multiple times
(9 answers)
How and when should I load the model from database for JSF dataTable
(1 answer)
Method must have signature "String method() ...[etc]..." but has signature "void method()"
(1 answer)
Closed 3 years ago.
I'm really new to JSF, I've been learning it exactly 2 days now. Besides the initial confusion about the concepts, I have issues with eclipse too.
I'm using JSF 2.0 with obviously Eclipse and Tomcat 7.
Firstly, let me describe what I'd want to do: in scope of learning the JSF I want to have a User class, with name, surname, age and Id. Then, I'd like to list pre-defined users and add a submit form. Besides that, there's also a "user detail" option.
Here's my code:
User class:
package com.tutorial;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class User {
private String name;
private String surname;
private int age;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User(String name, String surname, int age, int id) {
super();
this.name = name;
this.surname = surname;
this.age = age;
this.id = id;
}
public User(){}
}
Users "bean":
package com.tutorial;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#SessionScoped
public class UsersBean {
private List<User> listOfUsers = new ArrayList<User>();
private String passedParameter;
public UsersBean()
{
listOfUsers.add(new User("Tywin", "Lannister", 60, 1));
listOfUsers.add(new User("Tyrion", "Lannister", 30, 2));
listOfUsers.add(new User("Jaime", "Lannister", 31, 3));
}
public List<User> getAll()
{
System.out.println("Called!");
return listOfUsers;
}
public User getDetails()
{
passedParameter = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("userID");
int id = Integer.parseInt(passedParameter);
User selected = null;
for (User u : listOfUsers)
{
if (u.getId() == id)
{
selected = u;
}
}
return selected;
}
public void addUser(User u)
{
u.setId(listOfUsers.size()+1);
listOfUsers.add(u);
}
}
users.xml (partial code):
<f:view>
<!-- http://stackoverflow.com/questions/8083469/method-must-have-signature-string-method-etc-but-has-signature-void -->
<h:dataTable value="#{usersBean.all}" var="u">
<h:column>
<f:facet name="header">
User ID
</f:facet>
#{u.id}
</h:column>
<h:column>
<f:facet name="header">
Name
</f:facet>
#{u.name}
</h:column>
<h:column>
<f:facet name="header">
Details
</f:facet>
<h:link outcome="usersDetails" value="get details">
<f:param name="userID" value="#{u.id}"></f:param>
</h:link>
</h:column>
</h:dataTable>
<h:form>
<h:outputText value="Name"></h:outputText>
<h:inputText value="#{user.name}"></h:inputText>
<h:outputText value="Surname"></h:outputText>
<h:inputText value="#{user.surname}"></h:inputText>
<h:outputText value="Age"></h:outputText>
<h:inputText value="#{user.age}"></h:inputText>
<h:commandButton action="#{usersBean.addUser(user)}" value="Add" type="submit"></h:commandButton>
</h:form>
</f:view>
And finally, usersDetails.xhtml (partial code as well):
<ui:define name="content">
<ui:param name="user" value="#{usersBean.details}" />
<h:outputText value="#{user.name}"></h:outputText>
<h:outputText value="#{user.surname}"></h:outputText>
<h:outputText value="#{user.id}"></h:outputText>
</ui:define>
OK, now the questions:
(1) in users.xhtml (see code above - usersBean.all in datatable), it appears as if this function gets called as many times as there are values in arraylist. The "System.out.println("Called!")" is written as many times as there are values in arraylist. Have I done something wrong? I don't believe it's suppose to be called for each object in arraylist.
(2) in users.xhtml, this part of the code
<h:commandButton action="#{usersBean.addUser(user)}" value="Add" type="submit"></h:commandButton>
is highlighted by eclipse and it reads: "Method must have signature "String method(),..."
Did I call the method the wrong way? Is there an alternative to send object to the UsersBean's addUser function? What would be correct way if Eclipse defines this as wrong?
Thank you very much for your time and answers!
1) In JSF, method (used for bulding view) can be called more than once. For proper testing you can create user list with 20 or more users and check again how many times getAll method will be called. I think it still be the same number (3 in your case).
2) Action method in JSF should return redirection outcome (with type String). It is reason why you have message about "signature String method". Change signature of addUser method from public void addUser(User u) to public String addUser(User u) and return outcome for navigation to new page or null for stay on the same page.

JSF forms strange behavior

I have no idea why my forms behave in such way.
This is my JSF page:
<h:body>
<h:form>
<h:form>
<h:selectOneMenu value="#{productBean.product}" converter="#{productConverter}" validator="com.jsf.ProductAvailableValidator">
<f:selectItems value="#{productBean.pizza}" var="pizza" itemValue="#{pizza}" itemLabel="#{pizza.name}" />
<h:commandButton value="Dodaj" action="#{productBean.addToOrder(productBean.product.name)}" /></h:selectOneMenu>
</h:form>
<h:form>
<h:selectOneMenu value="#{productBean.product}" converter="#{productConverter}" validator="com.jsf.ProductAvailableValidator">
<f:selectItems value="#{productBean.drink}" var="drink" itemValue="#{drink}" itemLabel="#{drink.name}" />
<h:commandButton value="Dodaj" action="#{productBean.addToOrder(productBean.product.name)}" /></h:selectOneMenu>
</h:form>
<h:form>
<h:selectOneMenu value="#{productBean.product}" converter="#{productConverter}" validator="com.jsf.ProductAvailableValidator">
<f:selectItems value="#{productBean.other}" var="other" itemValue="#{other}" itemLabel="#{other.name}" />
<h:commandButton value="Dodaj" action="#{productBean.addToOrder(productBean.product.name)}" /></h:selectOneMenu>
</h:form>
<messages />
<h:outputText value="#{productBean.order}" />
<h:commandButton value="Wyczyść" action="#{ProductBean.clearOrder()}" /></h:form>
</h:body>
And this is my ProductBean:
#ManagedBean
#SessionScoped
public class ProductBean extends Connector
{
private List<Product> products;
private List<Product> pizza;
private List<Product> drink;
private List<Product> other;
boolean first = true;
private StringBuilder order = new StringBuilder();
public String getOrder() {
return order.toString();
}
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public void addToOrder(String prod)
{
System.out.println("dodaje");
if(first)
{
first = false;
this.order.append(prod);
}
else
this.order.append(" + ").append(prod);
}
public void clearOrder()
{
this.order = null;
first = true;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public ProductBean() throws SQLException
{
resultSet = statement.executeQuery("SELECT * FROM dbo.products");
products = new ArrayList<Product>();
while(resultSet.next())
{
product = new Product();
product.setId_product(resultSet.getInt("id_product"));
product.setName(resultSet.getString("name"));
product.setCategory(resultSet.getInt("category_id"));
product.setIs_available(resultSet.getInt("is_available"));
products.add(product);
}
}
public Product getProductById(int id)
{
Iterator<Product> it = products.iterator();
while(it.hasNext())
{
Product prod = it.next();
if(prod.getId_product() == id)
return prod;
}
return null;
}
public List<Product> getPizza() throws SQLException
{
Iterator<Product> it = products.iterator();
pizza = new ArrayList<Product>();
while(it.hasNext())
{
Product prod = it.next();
if(prod.getCategory() == 1)
pizza.add(prod);
}
return pizza;
}
public List<Product> getDrink() throws SQLException
{
Iterator<Product> it = products.iterator();
drink = new ArrayList<Product>();
while(it.hasNext())
{
Product prod = it.next();
if(prod.getCategory() == 2)
drink.add(prod);
}
return drink;
}
public List<Product> getOther() throws SQLException
{
Iterator<Product> it = products.iterator();
other = new ArrayList<Product>();
while(it.hasNext())
{
Product prod = it.next();
if(prod.getCategory() == 3)
other.add(prod);
}
return other;
}
public List<Product> getProducts() {
return products;
}
}
I also send a screenshot here to make code easier and faster to analize:
What happens here is that only the first button "Dodaj" (which means "add") works and add the String in outputlabel correctly. The rest of them do nothing. When I change the order, again only the first one works. Why?
You have multiple nested/cascaded <h:form>'s, that is not allowed in HTML! Either make one <h:form> and put all elements in that form, or make multiple <h:form>'s, but don't nest/cascade them!

Controller Bean not picking up the username

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);
}
}