hibernate print data from session object arraylist - java

I made wrong HQL trying to access column from another table. Sorry.
This question is solved.
I have ArrayList of type Object. Fetched from session.
It exists. I check. But I cant print it it from jsp or java. even I create methods.
// with type List I cant even fetch information from session. A change it to ArrayList.
My goal is to print result. I select some sql columns and I just wanna output them. Of course it would be object.
I have no error and that is problem. Only existing arraylist object of my type prod.
ArrayList <prod> goodlist = (ArrayList <prod>) session.getAttribute("goodlist_s");
for (prod glst : goodlist) {
%>
<tr>
<td><%//=out.println(u.getname())%></td>
<td><%=glst.getcatid()%></td>}
I try convert it to String ArrayList .
ArrayList<String> jlistTitles = new ArrayList<String>((ArrayList<String>) session.getAttribute("goodlist_s")); //converted fine
for(int i = 0; i < goodlist.size(); i++) {
System.out.println(goodlist.get(i).getprice());
//print object type
}
**Shows nothing**
This is my function
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
Query query = session.createQuery("from prod where catname=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}
BTW i would sent all code
index.jsp
<%#page import="java.util.List"%>
<%#page import="service.IndexService"%>
<%#page import="java.util.Date"%>
<%#page import="goods.prod"%>
<%#page import="goods.cat"%>
<%#page import ="java.util.ArrayList"%>
<%#page import ="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charprods=UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>Result Page</title>
</head>
</head>
<body>
<form action="IndexServlet" method="POST">
<table align="center" cellpadding = "10">
<tr>
<td>Category</td>
<td><input type="text" name="catname" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Category id</td>
<td><input type="number" name="catid" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Naimenovanie</td>
<td><input type="text" name="name" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Price low</td>
<td><input type="number" name="pricel" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td>Price high</td>
<td><input type="number" name="priceh" maxlength="100" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</td>
</tr>
</table>
prodsAttribute
<%
prod prod = (prod) session.getAttribute("prod");
%>
<%
ArrayList <prod> goodlist = (ArrayList <prod>) session.getAttribute("goodlist_s");
%>
<b>You have<% if (null == prod) out.println("No text entered.");%></b>
<b>You have<% if (null == goodlist) out.println("goodlist does NOT exists.");%></b>
<b>You have<% if (null != goodlist) {
ArrayList<String> jlistTitles = new ArrayList<String>((ArrayList<String>) session.getAttribute("goodlist_s"));
if (null == jlistTitles) out.println("convertedStringlist does NOT exists.");
if (null != jlistTitles) out.println("convertedStringlist exists. How can I use it?");
for(int i = 0; i < goodlist.size(); i++) {
System.out.println(goodlist.get(i).getprice());
//print object type
}
out.println("goodlist exists. How can I use it?");}%></b>
<br>
<b><%if (null!=prod) out.println(prod.getid()+ " "+prod.getname()+ " "+prod.getprice());%></b>
<br/>
<%
if (null!=goodlist) {
for (prod glst : goodlist) {
%>
<tr>
<td><%//=out.println(u.getname())%></td>
<td><%=glst.getcatid()%></td>
<td><%=glst.getprice()%></td>
<td><%="hh"%></td>
</tr>
<%}}%>
</form>
</body>
</html>
Indexservlet.java
package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import goods.prod;
import service.IndexService;
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = -8670416133536111566L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charprods=UTF-8");
//Long id = Long.parseLong(request.getParameter("id"));
String name = request.getParameter("name");
String catname = request.getParameter("catname");
Integer pricel = Integer.parseInt(request.getParameter("pricel"));
Integer priceh = Integer.parseInt(request.getParameter("priceh"));
prod dot = IndexService.getprodbyparam(catname,name,pricel,priceh);
List<prod> goodlist = IndexService.getListOfProds(catname,name,pricel,priceh);
request.getSession().setAttribute("goodlist_s", goodlist);
request.getSession().setAttribute("prod", dot);
response.sendRedirect("index.jsp");
}
}
Indexservice with functions
package service;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import HibernateUtil.HibernateUtil;
import goods.prod;
public class IndexService {
public static prod getprodbyparam(String catname,String name,Integer pricel, Integer priceh) {
Session session = HibernateUtil.openSession();
Transaction tx = null;
prod prod = null;
try {
tx = session.getTransaction();
tx.begin();
//Query query = session.createQuery("select prod.id from prod as prod inner join cat.id as id where name=?");
Query query = session.createQuery("from prod where name=? and price between ? and ?");
query.setString(0, name);
query.setInteger(1, pricel);
query.setInteger(2, priceh);
//query.prodsInteger(3, catid);
prod = (prod)query.uniqueResult();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return prod;
}
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
Query query = session.createQuery("from prod where catname=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}
}
prod with getters
package goods;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name = "prod")
public class prod implements Serializable {
#Id #GeneratedValue
#Column(name = "id")
private Long id;
private Integer catid;
private String name;
private Integer price;
public prod() {
}
public prod(Long id, Integer catid, String name, Integer price) {
this.id = id;
this.catid = catid;
this.name = name ;
this.price = price;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
public Integer getcatid() {
return catid;
}
public void setcatid(Integer catid) {
this.catid = catid;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public Integer getprice() {
return price;
}
public void setprice(Integer price) {
this.price = price;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Improve</display-name>
<servlet>
<servlet-name>IndexServlet</servlet-name>
<servlet-class>servlet.IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IndexServlet</servlet-name>
<url-pattern>/IndexServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Can you please try the below code and see if it works
ArrayList<String> goodlist_s= (ArrayList<String>)session.getAttribute("goodlist_s");
<%
for(int i = 0; i < goodlist_s.size(); i++)
{
String myString = (String) goodlist_s.get(i);
}
%>

Related

In Rest CRUD with OneToOne,when i am inserting data with form it working fine.But the problem comes with updating and deleting

--> when i am Updating it was not saving the entered details insted it was saving null. when deleting it throws error.
DataBase : restonetoone
application.properties
/*****************************/
crm.rest.url=http://localhost:8080/restonetoone/api/details
-->when i use to update it was taking null value insted of inserted data.
Details [id=25, city=null, mobileno=0, student=Student [id=25, name=null, clas=0]]
->when i was deleting it throws this error.
Mar 06, 2021 4:09:53 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /restclient/student/delete
the Details.java class Onetoone with student.java class
Details.java
/******************/
package com.rest.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="details")
public class Details {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private long mobileno;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="student_id")
private Student student;
public Details(){
}
public Details(int id, String city, long mobileno, Student student) {
super();
this.id = id;
this.city = city;
this.mobileno = mobileno;
this.student = student;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getMobileno() {
return mobileno;
}
public void setMobileno(long mobileno) {
this.mobileno = mobileno;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#Override
public String toString() {
return "Details [id=" + id + ", city=" + city + ", mobileno=" + mobileno + ", student=" + student + "]";
}
}
student.java class
Student.java
/******************/
package com.rest.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private int clas;
public Student() {
}
public Student(int id, String name, int clas) {
super();
this.id = id;
this.name = name;
this.clas = clas;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getClas() {
return clas;
}
public void setClas(int clas) {
this.clas = clas;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", clas=" + clas + "]";
}
}
DetailsServImpl.java class(service layers)
DetailsServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
#Service
public class DetailsServImpl implements DetailsServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public DetailsServImpl(RestTemplate theRestTemplate,
#Value("${crm.rest.url}") String theUrl) {
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Details> getDetails() {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Details>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Details>>() {});
// get the list of customers from response
List<Details> theDetails = responseEntity.getBody();
logger.info("in getDetails(): details" + theDetails);
return theDetails;
}
#Override
public Details getDetails(int theId) {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
Details theDetails =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Details.class);
logger.info("in saveDetails(): theDetails=" + theDetails);
return theDetails;
}
#Override
public void saveDetails(Details theDetails) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int detailsId = theDetails.getId();
// make REST call
if (detailsId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theDetails, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theDetails);
}
logger.info("in saveDetails(): success");
}
#Override
public void deleteDetails(int theId) {
logger.info("in deleteDetails(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteDetails(): deleted Details theId=" + theId);
}
}
StudentServImpl.java class
StudentServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
import com.rest.entity.Student;
#Service
public class StudentServImpl implements StudentServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public StudentServImpl(RestTemplate theRestTemplate,#Value("${crm.rest.url}") String theUrl){
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Student> getStudent() {
logger.info("in getCustomers(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Student>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Student>>() {});
// get the list of customers from response
List<Student> theStudent = responseEntity.getBody();
logger.info("in getCustomers(): customers" + theStudent);
return theStudent;
}
#Override
public void saveStudent(Student theStudent) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int studentId = theStudent.getId();
// make REST call
if (studentId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theStudent, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theStudent);
}
logger.info("in saveStudent(): success");
}
#Override
public Student getStudent(int theId) {
logger.info("in getCustomer(): Calling REST API " + crmRestUrl);
// make REST call
Student theStudent =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Student.class);
logger.info("in saveCustomer(): theCustomer=" + theStudent);
return theStudent;
}
#Override
public void deleteStudent(int theId) {
logger.info("in deleteStudent(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteStudent(): deleted Student theId=" + theId);
}
}
Now the controller class(here i am using single controller for multiple entites).
ClientController.java
/******************/
package com.rest.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.rest.entity.Details;
import com.rest.entity.Student;
import com.rest.service.DetailsServ;
import com.rest.service.StudentServ;
#Controller
#RequestMapping("/cont")
public class ClientController {
#Autowired
private DetailsServ detailsServ;
#Autowired
private StudentServ studentServ;
#GetMapping("/showForm")
public String showForm(Model theModel){
Details theDetails = new Details();
Student theStudent = new Student();
theDetails.setStudent(theStudent);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#PostMapping("/saveForm")
private String saveForm(#ModelAttribute("for") Details theDetails) {
detailsServ.saveDetails(theDetails);
return "redirect:/cont/list";
}
#GetMapping("/list")
public String showList(Model theModel) {
List<Details> theDetails = detailsServ.getDetails();
theModel.addAttribute("details", theDetails);
return "list-table";
}
#GetMapping("/update")
public String updateDetails(#RequestParam("detailsId") int theId, Model theModel) {
Details theDetails =detailsServ.getDetails(theId);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#GetMapping("/delete")
public String deleteDetails(#RequestParam("detailsId") int theId) {
detailsServ.deleteDetails(theId);
return "redirect:/cont/list";
}
}
I use this form for both saving and updating.
the-for.jsp
/******************/
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Save Customer</title>
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css">
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/add-customer-style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>Form</h2>
</div>
</div>
<div id="container">
<h3>Save StudentDetails</h3>
<form:form action="saveForm" modelAttribute="for" method="POST">
<!-- need to associate this data with customer id -->
<form:hidden path="id" />
<table>
<tbody>
<tr>
<td><label>City name:</label></td>
<td><form:input path="city" /></td>
</tr>
<tr>
<td><label>mobileno:</label></td>
<td><form:input path="mobileno" /></td>
</tr>
<tr>
<td><label>name:</label></td>
<td><form:input path="student.name" /></td>
</tr>
<tr>
<td><label>class:</label></td>
<td><form:input path="student.clas" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear; both;"></div>
<p>
Back to List
</p>
</div>
</body>
</html>
Now the table which shows the CRUD dynamically.
list-table.jsp
/******************/
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>List</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2 class="pt-2">Student Manager</h2>
<!-- put new button: Add Student -->
<input type="button" value="Add Student"
onclick="window.location.href='showForm'; return false;"
class="btn btn-primary btn-sm mb-3" />
<!-- add our html table here -->
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>city</th>
<th>mobileno</th>
<th>name</th>
<th>class</th>
<th>Action</th>
</tr>
</thead>
<!-- loop over and print our students -->
<tbody>
<c:forEach var="tempDetails" items="${details}">
<!-- construct an "update" link with student id -->
<c:url var="updateLink" value="/cont/update">
<c:param name="detailsId" value="${tempDetails.id}" />
</c:url>
<!-- construct an "delete" link with student id -->
<c:url var="deleteLink" value="/student/delete">
<c:param name="studentId" value="${tempStudent.id}" />
</c:url>
<tr>
<td>${tempDetails.city}</td>
<td>${tempDetails.mobileno}</td>
<td>${tempDetails.student.name}</td>
<td>${tempDetails.student.clas}</td>
<td>
<!-- display the update link -->
Update
|
<a href="${deleteLink}"
onclick="if (!(confirm('Are you sure you want to delete this student?'))) return false">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
For more clearity sake i am shering the link of my project which include Both client side and backend code files with database.
LINK( https://drive.google.com/file/d/128pvCd6bYdCNhOiG6ERRXbPRUlnhZlTp/view?usp=sharing )

Java Hibernate application using mySQL- Login page does not work

I am working on a hibernate project using apache.tomcat in netbeans in which I am creating an application with a user login (employee ID and password) that allows baseball field employees (from mysql database) to request passes to use the field. Users should be able to 1) choose an event for reservation (date & time) from a drop down menu, 2) input their group size, group name, and employee department(drop-down) and 3) manage the reservations on file specific to their employee ID.
I can access the login screen, but nothing happens when I enter employee credentials. I am not sent to the memberscreen.jsp upon entering a correct login, and I do not get the errors I set up for invalid logins. I have been at this for hours and I can not seem to find where I went wrong.
Note: The project requires that I use hibernate
I have tried googling ways to fix this but I have come up short, I think my problem may be too specific. I am getting no errors and the build is successful, but not functional.
logonservlet.java
package servlets;
import business.Employee;
import business.EmployeeDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogonServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String msg = "", empid = "";
long pattempt;
String URL = "/Logon.jsp";
Employee e;
try {
empid = request.getParameter("empid").trim();
e = EmployeeDB.getEmployee(empid);
if (e == null) {
msg = "No member record found<br>";
} else {
pattempt = Long.parseLong(request.getParameter("password"));
e.setPassattempt((int) pattempt);
if (!e.isAuthenticated()) {
msg = "Member found but not authenticated<br>";
} else {
msg = "member authenticated<br>";
URL = "/MemberScreen.jsp";
}
request.getSession().setAttribute("e", e);
}
} catch (Exception x) {
msg = "Servlet exception: " + x.getMessage();
}
request.setAttribute("msg", msg);
RequestDispatcher disp =
getServletContext().getRequestDispatcher(URL);
disp.forward(request,response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.
Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Logon.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Field Pass</title>
</head>
<body>
<h1>Welcome</h1>
<p>Please Enter your id and password:</p>
<form action="Logon" method="post">
<table>
<tr>
<td>User ID:</td>
<td><input type="text" name="userid" id="userid"
value="${empty user.userID ? cookie.memid.value : user.userID }" />
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password">
</td>
</tr>
</table>
<br>
<input type="submit" value="Log in">
</form>
<br>
</body>
</html>
employee.java
package business;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.Transient;
import org.hibernate.annotations.NamedQuery;
#Entity
#Table(name="Employee")
#NamedQuery(name="dbget_Employee", query="from EMPLOYEE where EMP_ID = :EMP_ID")
public class Employee {
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
#Id
#Column(name="EMP_ID")
private int emp_id;
#Column(name="LAST_NAME")
private String last_name;
#Column(name="FIRST_NAME")
private String first_name;
#Column(name="MIDDLE_INITIAL")
private String middle_initial;
#Column(name="HIRE_DATE")
#Temporal(javax.persistence.TemporalType.DATE)
private Date hire_date;
#Column(name="DEPT_ID")
private int dept_id;
#Column(name="PASSWORD")
private int password;
#Column(name="ADMIN")
private String admin;
#Transient
private int passattempt;
#Transient
private String msg;
public Employee() {
emp_id = 0;
last_name= "";
first_name = "";
middle_initial = "";
hire_date = null;
dept_id = 0;
password = 0;
admin = "";
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getMiddle_initial() {
return middle_initial;
}
public void setMiddle_initial(String middle_initial) {
this.middle_initial = middle_initial;
}
public Date getHire_date() {
return hire_date;
}
public void setHire_date(Date hire_date) {
this.hire_date = hire_date;
}
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public int getPassattempt() {
return passattempt;
}
public void setPassattempt(int passattempt) {
this.passattempt = passattempt;
}
public boolean isAuthenticated() {
if (this.password > 0) {
if (this.password == this.getPassattempt()) {
return true;
} else {
setMsg("Member not authenticated");
}
}
return false;
}
}
employeeDB.java
package business;
import javax.persistence.NoResultException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
*
* #author noah
*/
public class EmployeeDB {
public static Employee getEmployee(int emp_id) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
Employee e = null;
try {
String qS ="from Employee e where e.emp_id = :emp_id";
session = sessionFactory.openSession();
Query q = session.createQuery(qS);
q.setParameter("emp_id", emp_id);
e = (Employee)q.uniqueResult();
} catch (NoResultException ex) {
return null;
} finally {
session.close();
}
return e;
}
public static Employee getEmployee(String empid) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
}
memberScreen.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Member Welcome</title>
<style>
table.member-details{
border-collapse: collapse;
}
table.member-details td, table.member-details th{
padding: 6px;
border: 1px solid #999;
}
</style>
</head>
<c:if test="${!e.authenticated}">
<script type="text/javascript">
window.location = "/ClubDB";
</script>
</c:if>
<c:if test="${e.authenticated}">
<body>
<h1>Club member Data</h1>
<form id="memupdate" action="MemberUpdate" method="post">
<table class="member-details">
<tr>uu
<td>Member ID:</td>
<td><input type="text" id="memid" name="memid"
value="${e.empid}" readonly="true"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="lastname" name="lastname"
value="${e.lastname}" ></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" id="firstname" name="firstname"
value="${e.firstname}" ></td>
</tr>
<tr>
<td>Middle Nm:</td>
<td><input type="text" id="middlename" name="middlename"
value="${e.middlename}" ></td>
</tr>
<tr>
<td>Status:</td>
<td><input type="text" id="status" name="status"
value="${m.status}" readonly="true" ></td>
<tr>
<tr>
<td>Member Date:</td>
<td><input type="text" id="memdt" name="memdt"
value="${m.memdtS}" readonly="true" ></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="psswd" name="psswd"
value="${m.password}" size="22"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update Member data"></td>
</tr>
</table>
</form>
<br>
${msg}
<hr>
<br>View Transaction History From:<br>
<form action="ShowPurchases" method="post" >
<table>
<tr>
<td>Month:</td><td><input type="text" name="month"
id="month" value=""></td>
<td>Day:</td><td><input type="text" name="day"
id="day" value=""></td>
<td>Year:</td><td><input type="text" name="year"
id="year" value=""></td>
</tr>
</table><br>
<input type="submit" value="View Transactions">
</form> <br>
<br><br>
Back to the Login Screen
</body>
</c:if>
</html>
hibernate xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-
iiapp_3_1.xsd">
<servlet>
<servlet-name>LogonServlet</servlet-name>
<servlet-class>servlets.LogonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogonServlet</servlet-name>
<url-pattern>/Logon</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>Logon.jsp</welcome-file>
</welcome-file-list>

Problems with Glassfish5 and servlet

I'm relatively new to Java. Tried my first web application with server Tomcat, which went rather well. However, with another server Glassfish, problems arouse. After application deployment jsp doesn't connect to servlet, therefore error 404 appears. I added project structure and several classes. Any help appreciated.
empBean:
package app.bean;
import app.entity.Emp;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
#Stateless
public class EmpBean {
#PersistenceContext(unitName = "DEVMODE")
private EntityManager em;
public Emp add(Emp emp) {
return em.merge(emp);
}
public Emp get(Integer empno) {
return em.find(Emp.class, empno);
}
public void update(Emp emp) {
add(emp);
}
public void delete(long empno){
em.remove(get((int) empno));
}
public List<Emp> getAll(){
TypedQuery<Emp> namedQuery = em.createNamedQuery("Emp.getAll", Emp.class);
return namedQuery.getResultList();
}
}
Emp:
package app.entity;
import javax.persistence.*;
import java.sql.Date;
#Entity(name="emp")
#NamedQuery(name = "Emp.getAll", query = "SELECT e from emp e")
public class Emp {
#Id
#Column(name="empno")
private Integer empno ;
#Column(name="ename")
private String ename;
#Column(name="job")
private String job;
#Column(name="mgr")
private Integer mgr;
#Column(name="hiredate")
private Date hiredate;
#Column(name="sal")
private Integer sal;
#Column(name="comm")
private Integer comm;
#Column(name="deptno")
private Integer deptno;
public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Integer sal, Integer comm, Integer deptno, String id) {
this.empno = empno;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
}
public Emp() {
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public Integer getSal() {
return sal;
}
public void setSal(Integer sal) {
this.sal = sal;
}
public Integer getComm() {
return comm;
}
public void setComm(Integer comm) {
this.comm = comm;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
}
Select1Servlet:
package app.servlets;
import app.bean.DeptBean;
import app.bean.EmpBean;
import app.bean.SalgradeBean;
import app.entity.Dept;
import app.entity.Emp;
import app.entity.Salgrade;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
#WebServlet("/search")
public class Select1Servlet extends HttpServlet {
#EJB
private EmpBean empBean;
private DeptBean deptBean;
private SalgradeBean salgradeBean;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
req.setCharacterEncoding("UTF-8");
req.getRequestDispatcher("/searchview.jsp").forward(req, resp);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/users";
String userName = "root";
String password = "7777";
Statement st;
try {
// Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(url , userName, password);
System.out.println("Connected!");
String numb = request.getParameter("numb");
ArrayList al = null;
ArrayList pid_list = new ArrayList();
// String query = "SELECT emp.ename, emp.job, emp.sal, dept.dname, salgrade.grade FROM dept,emp,salgrade WHERE (emp.empno = '" + numb + "' ) AND (emp.deptno = dept.deptno) and (emp.sal BETWEEN losal and hisal) ";
// System.out.println("query " + query);
st = conn.createStatement();
// ResultSet rs = st.executeQuery(query);
Emp emp = empBean.get(Integer.valueOf(numb));
String ename= emp.getEname();
String job = emp.getJob();
Integer sal = emp.getSal();
Integer deptnoEmp= emp.getDeptno();
Dept dept = deptBean.get(Integer.valueOf(deptnoEmp));
String dname = dept.getDname();
Salgrade salgrade = salgradeBean.get(sal);
Integer grade = salgrade.getGrade();
// while (rs.next()) {
al = new ArrayList();
// out.println(rs.getString(1));
// out.println(rs.getString(2));
// out.println(rs.getString(3));
// out.println(rs.getString(4));
al.add(ename);
al.add(job);
al.add(sal);
al.add(dname);
al.add(grade);
System.out.println("al :: " + al);
pid_list.add(al);
// }
request.setAttribute("piList", pid_list);
RequestDispatcher view = request.getRequestDispatcher("/searchview.jsp");
view.forward(request, response);
conn.close();
System.out.println("Disconnected!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
select1.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Enter the number </title>
<link rel="stylesheet" href="design/w3.css">
</head>
<body>
<br/><br/>
<form method="post" name="frm" action="search">
<table border="0" width="375" align="center" class = "w3-pink w3-text-white" >
<tr><td colspan=2 style="font-size:12pt;" align="center">
<h3>Search User</h3></td></tr>
<br/>
<tr><td ><b>User Number</b></td>
<td>: <input type="number" name="numb" id="numb">
</td></tr>
<tr><td colspan=2 align="center">
<br/>
<input type="submit" name="submit" value="Search" onclick="form.action='/search';"></td></tr>
</table>
</form>
</body>
</html>
searchview.jsp:
<%# page import="java.util.*" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%--<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>--%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title> List of emp </title>
<link rel="stylesheet" href="design/w3.css">
</head>
<body>
<form method="get" name="frm" action="searchview">
<table width="700px"
class = "w3-text-pink">
<tr>
<td colspan=5 align="center"
class = "w3-black w3-text-pink">
<b>User Record</b></td>
</tr>
<tr class = "w3-black ">
<td><b>User Name</b></td>
<td><b>Job</b></td>
<td><b>Sal</b></td>
<td><b>Dname</b></td>
<td><b>Grade</b></td>
</tr>
<%
int count = 0;
String color = "#ffffff";
if (request.getAttribute("piList") != null) {
ArrayList al = (ArrayList) request.getAttribute("piList");
System.out.println(al);
Iterator itr = al.iterator();
while (itr.hasNext()) {
if ((count % 2) == 0) {
color = "#ffffff";
}
count++;
ArrayList pList = (ArrayList) itr.next();
%>
<tr style="background-color:<%=color%>;">
<td><%=pList.get(0)%></td>
<td><%=pList.get(1)%></td>
<td><%=pList.get(2)%></td>
<td><%=pList.get(3)%></td>
<td><%=pList.get(4)%></td>
</tr>
<%
}
}
if (count == 0) {
%>
<tr>
<td colspan=5 align="center"
style="background-color:#ffffff"><b>No Record Found..</b></td>
</tr>
<% }
%>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Select1</servlet-name>
<servlet-class>app.servlets.Select1Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Select1</servlet-name>
<url-pattern>/search</url-pattern>
</servlet-mapping>

Spring MVC wrong entity id after an attempt to update it

I try to write simple Spring MVC CRUD webapp and I got a problem updating my rows. I have a table with some users and I can edit any of them clicking "Edit" button in the table (look at the picture). Then I can change its fields in a form, but when I click "Edit" under the form, the id of user entity, that is conveyed to the addUser() method, is 0, though, when I got the entity from db, it wasn't. Also "createdDate" field becomes null. I can't find out the reason of it, so I need some help... This is my code and the picture with my app:
The picture
user.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#page isELIgnored="false" %>
<%# page session="false" %>
<html>
<head>
<title>Users</title>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-4eph{background-color:#f9f9f9}
</style>
</head>
<body>
<h1>
Add a user
</h1>
<c:url var="addAction" value="/user/add" />
<form:form action="${addAction}" commandName="user">
<table>
<c:if test="${!empty user.name}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="name">
<spring:message text="Name"/>
</form:label>
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>
<form:label path="age">
<spring:message text="Age"/>
</form:label>
</td>
<td>
<form:input path="age" />
</td>
</tr>
<tr>
<td>
<form:label path="isAdmin">
<spring:message text="Is admin"/>
</form:label>
</td>
<td>
<form:input path="isAdmin"/>
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty user.name}">
<input type="submit"
value="<spring:message text="Edit"/>" />
</c:if>
<c:if test="${empty user.name}">
<input type="submit"
value="<spring:message text="Add"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
<br>
<h3>Users list</h3>
<table class="tg">
<tr>
<th width="80">ID</th>
<th width="120">Name</th>
<th width="120">Age</th>
<th width="60">IsAdmin</th>
<th width="120">Created date</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.isAdmin}</td>
<td>${user.createdDate}</td>
<td><a href="<c:url value='/edit/${user.id}' />" >Edit</a></td>
<td><a href="<c:url value='/remove/${user.id}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
UserController
package com.mihusle;
import com.mihusle.model.User;
import com.mihusle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by MHSL on 16.06.2017.
*/
#Controller
public class UserController {
private UserService userService;
#Autowired
#Qualifier("userService")
public void setUserService(UserService userService) {
this.userService = userService;
}
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String showUsersList(Model model) {
model.addAttribute("user", new User());
model.addAttribute("users", userService.getUsers());
return "user";
}
#RequestMapping(value = "/user/add", method = RequestMethod.POST)
public String addUser(#ModelAttribute("user") User user) {
if (user.getId() == 0) {
userService.addUser(user);
} else {
userService.updateUser(user);
}
return "redirect:/users";
}
#RequestMapping("/remove/{id}")
public String removeUser(#PathVariable("id") int id) {
userService.removeUser(id);
return "redirect:/users";
}
#RequestMapping("/edit/{id}")
public String editUser(#PathVariable("id") int id, Model model) {
model.addAttribute("user", userService.getUserById(id));
model.addAttribute("users", userService.getUsers());
return "user";
}
}
UserDAOImpl
package com.mihusle.dao;
import com.mihusle.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
/**
* Created by MHSL on 16.06.2017.
*/
#Repository
public class UserDAOImpl implements UserDAO {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addUser(User user) {
Session session = sessionFactory.getCurrentSession();
Calendar calendar = Calendar.getInstance();
Timestamp currentTime = new Timestamp(calendar.getTimeInMillis());
user.setCreatedDate(currentTime);
session.persist(user);
LOGGER.info(user + " was added successfully");
}
#Override
public void updateUser(User user) {
Session session = sessionFactory.getCurrentSession();
session.update(user);
LOGGER.info(user + " was updated successfully");
}
#SuppressWarnings("unchecked")
#Override
public List<User> getUsers() {
Session session = sessionFactory.getCurrentSession();
List<User> users = session.createQuery("FROM User").list();
users.forEach(user -> LOGGER.info(user + " is in the list"));
return users;
}
#Override
public User getUserById(int id) {
Session session = sessionFactory.getCurrentSession();
User user = session.load(User.class, id);
LOGGER.info(user + " was loaded successfully");
return user;
}
#Override
public void removeUser(int id) {
Session session = sessionFactory.getCurrentSession();
User user = session.load(User.class, id);
if (user != null)
session.delete(user);
LOGGER.info(user + " was deleted successfully");
}
}
User
package com.mihusle.model;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Objects;
/**
* Created by MHSL on 16.06.2017.
*/
#Entity
#Table(name = "user", schema = "test")
public class User {
private int id;
private String name;
private Integer age;
private Boolean isAdmin;
private Timestamp createdDate;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = true, length = 25)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "age", nullable = true)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Basic
#Column(name = "isAdmin", nullable = true, columnDefinition = "BIT", length = 1)
public Boolean getIsAdmin() {
return isAdmin;
}
#Column(name = "isAdmin", columnDefinition = "BIT", length = 1)
public void setIsAdmin(Boolean admin) {
isAdmin = admin;
}
#Basic
#Column(name = "createdDate", nullable = true)
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User that = (User) o;
return id == that.id &&
Objects.equals(name, that.name) &&
Objects.equals(age, that.age) &&
Objects.equals(createdDate, that.createdDate);
}
#Override
public int hashCode() {
return Objects.hash(id, name, age, createdDate);
}
#Override
public String toString() {
return "User{" +
"id = " + id +
", name = '" + name + '\'' +
", age = " + age +
", isAdmin = " + isAdmin +
", createdDate = " + createdDate +
'}';
}
}
I have no idea where the problem may be, so if you need more code, I'm ready to write it. Thanks
I solved this. I had to add <form:hidden path="id" /> to the id input field. I suppose I need to do the same with createdDate field.

value map is not a member of models

Hi I'm trying to fetch a object from a class and displaying it and I'm getting error "value map is not a member of models.TimeSheetDataStore"
Here is my model class files
TimeSheetDataStore.java
package models;
public class TimeSheetDataStore {
String ID;
String EmployeeID;
String RoleID;
String Task;
String TimeSheetDate;
String CreateDate;
String UpdateDate;
String TaskHour;
String IsBilled;
String ClientID;
String ProjectID;
String atHome;
String atClientSite;
}
TimeSheet.java
package models;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import models.TimeSheetDataStore;
public class Timesheet {
public static List<TimeSheetDataStore> PopulateProject() {
List<TimeSheetDataStore> TimeSheetList = new ArrayList<TimeSheetDataStore>();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433","SUMEET","sumeet");
Statement sta = conn.createStatement();
String Sql = "select * from Project";
ResultSet rs = sta.executeQuery(Sql);
while (rs.next()) {
TimeSheetDataStore TSDS= new TimeSheetDataStore();
TSDS.ID=rs.getString("ID");
TSDS.EmployeeID=rs.getString("EmployeeID");
TSDS.RoleID=rs.getString("RoleID");
TSDS.Task=rs.getString("Task");
TSDS.TimeSheetDate=rs.getString("TimeSheetDate");
TSDS.CreateDate=rs.getString("CreateDate");
TSDS.UpdateDate=rs.getString("UpdateDate");
TSDS.TaskHour=rs.getString("TaskHour");
TSDS.IsBilled=rs.getString("IsBilled");
TSDS.ProjectID=rs.getString("ProjectID");
TSDS.ClientID=rs.getString("ClientID");
TSDS.atHome=rs.getString("atHome");
TSDS.atClientSite=rs.getString("atClientSite");
TimeSheetList.add(TSDS);
}
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException |SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return(TimeSheetList);
}
}
Controller file
Application.java
public static Result myAction(String ClientFilter,String ConsultantFilter) {
DynamicForm requestData = Form.form().bindFromRequest();
if (requestData.get("Submit")!=null) {
return ok(index.render(Client.PopulateClient(),Consultant.PopulateConsultant(),Project.PopulateProject(ClientFilter)));
} else if (requestData.get("Generate Timesheet")!=null) {
//return ok(list.render(Client.PopulateClient(),Consultant.PopulateConsultant(),Project.PopulateProject()));
return ok(DisplayTimeSheet.render(Timesheet.PopulateProject()));
} else {
return badRequest("This action is not allowed");
}
}
View file DisplayTimeSheet.scala.html
#(currentPage:List[TimeSheetDataStore])
<html>
<head></head>
<body>
<form>
<table>
<thead>
<tr>
<td>ID</td>
<td>EmployeeID</td>
<td>RoleID</td>
<td>Task</td>
<td>TimeSheetDate</td>
<td>CreateDate</td>
<td>UpdateDate</td>
<td>TaskHour</td>
<td>IsBilled</td>
<td>ProjectID</td>
<td>ClientID</td>
<td>atHome</td>
<td>atClientSite</td>
</tr>
</thead>
<tbody>
#for(i <- currentPage.indices) {
#for(element <- currentPage.get(i)) {
<tr>
<td>#element.ID</td>
<td>#element.EmployeeID</td>
<td>#element.RoleID</td>
<td>#element.Task</td>
<td>#element.TimeSheetDate</td>
<td>#element.CreateDate</td>
<td>#element.UpdateDate</td>
<td>#element.TaskHour</td>
<td>#element.IsBilled</td>
<td>#element.ProjectID</td>
<td>#element.ClientID</td>
<td>#element.atHome</td>
<td>#element.atClientSite</td>
</tr>
}
}
</tbody>
</table>
</form>
</body>
</html>
Can some one tell me what I'm doing wrong?
try instead of
#for(i <- currentPage.indices) {
#for(element <- currentPage.get(i)) {
<tr>
<td>#element.ID</td>
<td>#element.EmployeeID</td>
<td>#element.RoleID</td>
.
.
.
</tr>
}
}
use only one for loop because you have list of currentPage: List[TimeSheetDataStore] so when you do #for(element <- currentPage) it will return you one object assigned to the element variable so now you have TimeSheetDataStore object in element variable so you can directly access it's fields
Do it like this:
<tbody>
#for(element <- currentPage) {
<tr>
<td>#element.ID</td>
<td>#element.EmployeeID</td>
<td>#element.RoleID</td>
<td>#element.Task</td>
<td>#element.TimeSheetDate</td>
<td>#element.CreateDate</td>
<td>#element.UpdateDate</td>
<td>#element.TaskHour</td>
<td>#element.IsBilled</td>
<td>#element.ProjectID</td>
<td>#element.ClientID</td>
<td>#element.atHome</td>
<td>#element.atClientSite</td>
</tr>
}
</tbody>

Categories

Resources