so I am working in a Spring MVC project where I have this class with a few Date fields and I am creating a CRUD for it. Problem is, I read an instance of the class from the database and then send it to the view for editing, and although I am not manipulating any of the Date fields, only the strings, when I collect the object using a post form, the Date fields come as null even though they came from the database with a value and I sent them to the view with that value.
The class:
package com.sophos.mat.beans;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Length;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="IN_PROYECTO")
#GeneratedValue(strategy=GenerationType.AUTO, generator="SECUENCIA_IN_PROYECTO")
#SequenceGenerator(name="SECUENCIA_IN_PROYECTO", sequenceName="SECUENCIA_IN_PROYECTO", allocationSize=1, initialValue= 1)
private long id;
#Column(name="VC_NOMBRE")
#Length(max = 50, message = "El campo no puede exceder los 50 caracteres")
private String nombre;
#Column(name="VC_DESCRIPCION")
#Length(max = 200, message = "El campo no puede exceder los 200 caracteres")
private String descripcion;
#Column(name="VC_CODIGO_SOPHOS")
#Length(max = 20, message = "El campo no puede exceder los 20 caracteres")
private String codigoSophos;
#Column(name="DT_FECHACREACION")
private Date fechaCreacion;
#Column(name="VC_USUARIOACTUALIZACION")
private String usuarioActualizacion;
#Column(name="DT_FECHAACTUALIZACION")
private Date fechaActualizacion;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getCodigoSophos() {
return codigoSophos;
}
public void setCodigoSophos(String codigoSophos) {
this.codigoSophos = codigoSophos;
}
public Date getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public String getUsuarioActualizacion() {
return usuarioActualizacion;
}
public void setUsuarioActualizacion(String usuarioActualizacion) {
this.usuarioActualizacion = usuarioActualizacion;
}
public Date getFechaActualizacion() {
return fechaActualizacion;
}
public void setFechaActualizacion(Date fechaActualizacion) {
this.fechaActualizacion = fechaActualizacion;
}
}
The controller:
package com.sophos.mat.controller;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
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;
import org.springframework.web.servlet.ModelAndView;
import com.sophos.mat.beans.Proyecto;
import com.sophos.mat.services.IProyectoService;
#Controller
public class ProyectoController {
#Autowired
private IProyectoService proyectoService;
#RequestMapping(value = "/editarproyecto/{id}", method = RequestMethod.GET)
public String editarProyectoGet(ModelMap model, #PathVariable long id){
try {
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
model.put("proyectoData", proyectoData);
return "editarproyecto";
} catch (Exception e) {
e.printStackTrace();
return "redirect:/proyectos";
}
}
#RequestMapping(value="/editarproyecto/{id}", method = RequestMethod.POST)
public String editarProyectoPost(ModelMap model, #PathVariable long id, #ModelAttribute("proyectoData")#Valid Proyecto proyectoData, BindingResult result){
if(result.hasErrors()){
return "editarproyecto";
}
try{
proyectoData.setFechaActualizacion(new Date());
proyectoService.actualizarProyecto(proyectoData);
return "redirect:/proyectos";
}catch(Exception e){
e.printStackTrace();
return "redirect:/proyectos";
}
}
public IProyectoService getProyectoService() {
return proyectoService;
}
public void setProyectoService(IProyectoService proyectoService) {
this.proyectoService = proyectoService;
}
}
And the view: editarproyecto.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib uri= "http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>>Nuevo Proyecto</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h1>Nuevo Proyecto</h1>
<form:form method="post" modelAttribute="proyectoData">
<table >
<tr>
<td align="right">
Nombre proyecto:
</td>
<td>
<form:input path="nombre"/>
</td>
<td>
<form:errors path="nombre" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Descripción
</td>
<td>
<form:input path="descripcion"/>
</td>
<td>
<form:errors path="descripcion" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Cód. Sophos
</td>
<td>
<form:input path="codigoSophos"/>
</td>
<td>
<form:errors path="codigoSophos" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Usuario que actualiza
</td>
<td>
<form:input path="usuarioActualizacion"/>
</td>
<td>
<form:errors path="usuarioActualizacion" cssClass="error"/>
</td>
</tr>
</table>
<br>
<input type="submit" value="Guardar">
</form:form>
Proyectos
</body>
</html>
When processing POST, I get an exception from hibernate telling me that I'm trying to update to NULL the column 'DT_FECHACREACION' corresponding to the class field 'fechaCreacion'. As a temporary fix, I had to add in the POST method a query to the database to reset 'fechaCreacion' back to its previous value which I don't want to change and then update the entity with the rest of the captured values. That works but is ugly af and adds extra and unwanted overhead. My database is Oracle 11g. Thanks in advance folks!
PD: Very newbie spring developer, am in my internship and trying my best to get a full contract when the internship is over :D so any help will be much appreciated.
When you call the service you have to control which fields you return to the view.
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
You can omit fields your DAO is returning with #JsonIgnore annotation.
....
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
...
#JsonIgnore
public Date getFechaCreacion() {
return fechaCreacion;
}
....
}
Related
I keep getting SQLGrammarException error, I could not find any syntax error from my code. Here is my controller, entity, DAO and JSP file code. Maybe my form tag in addProduct.jsp is wrong, but I could not find the solution.
HomeController.java
package com.soccershop.springdemo.controller;
import java.io.IOException;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.soccershop.springdemo.entity.Top;
import com.soccershop.springdemo.service.ProductService;
#Controller
public class HomeController {
#Autowired
private ProductService productService;
#RequestMapping("/home")
public String home(Model model) {
List<Top> topProductList = productService.getTopProducts();
model.addAttribute("topProducts", topProductList);
return "home" ;
}
#RequestMapping("/productDetail/{id}")
public String productDetail(#PathVariable int id, Model model) throws IOException {
Top top = productService.getTopById(id);
model.addAttribute(top);
return "productDetail";
}
#RequestMapping("/admin")
public String adminPage() {
return "admin";
}
#RequestMapping("/admin/productInventory")
public String productInventory(Model model) {
List<Top> topProductList = productService.getTopProducts();
model.addAttribute("topProducts", topProductList);
return "productInventory";
}
#GetMapping("/admin/addProduct")
public String addProduct(Model model) {
Top top= new Top();
model.addAttribute("newProduct", top);
return "addProduct";
}
#PostMapping("/admin/saveTop")
public String saveTop(#ModelAttribute("newProduct") Top theTop) {
productService.saveTop(theTop);
return "redirect:/admin/productInventory";
}
}
ProductDAOImpl.java
package com.soccershop.springdemo.dao;
import java.io.IOException;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.soccershop.springdemo.entity.Bottom;
import com.soccershop.springdemo.entity.Top;
#Repository
public class ProductDAOImpl implements ProductDAO {
// need to inject the session factory
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Top> getTopProducts() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query<Top> theQuery =
currentSession.createQuery("from Top", Top.class);
// execute query and get result list
List<Top> topProducts = theQuery.getResultList();
// return the results
return topProducts;
}
#Override
#Transactional
public List<Bottom> getBottomProducts() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query<Bottom> theQuery =
currentSession.createQuery("from Bottom", Bottom.class);
// execute query and get result list
List<Bottom> topProducts = theQuery.getResultList();
// return the results
return topProducts;
}
#Override
public Top getTopById(int topId) throws IOException {
for(Top theTop : getTopProducts()) {
if(theTop.getId() == topId) {
return theTop;
}
}
throw new IOException("No product found.");
}
#Override
public void saveTop(Top theTop) {
Session currentSession = sessionFactory.getCurrentSession();
currentSession.save(theTop);
}
}
Top.java
package com.soccershop.springdemo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Top")
public class Top {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="category")
private String productCategory;
#Column(name="product_name")
private String productName;
#Column(name="price")
private int price;
#Column(name="img")
private String img;
#Column(name="desc")
private String desc;
#Column(name="quantity")
private int quantity;
public Top() {
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getId() {
return id;
}
public String getProductName() {
return productName;
}
public int getPrice() {
return price;
}
public String getImg() {
return img;
}
public void setId(int id) {
this.id = id;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setPrice(int price) {
this.price = price;
}
public void setImg(String img) {
this.img = img;
}
#Override
public String toString() {
return "Top [id=" + id + ", productCategory=" + productCategory + ", productName=" + productName + ", price="
+ price + ", img=" + img + ", desc=" + desc + ", quantity=" + quantity + "]";
}
}
addProduct.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#include file="/WEB-INF/view/template/header.jsp"%>
<div class="container-fluid bg-secondary mb-5">
<div id="p-header"
class="d-flex flex-column align-items-center justify-content-center"
style="min-height: 300px">
<h1 class="font-weight-semi-bold text-uppercase mb-3">Add Product
Page</h1>
<div class="d-inline-flex">
<p class="m-0">
Home
</p>
<p class="m-0 px-2">-</p>
<p class="m-0">Add-Page</p>
</div>
</div>
</div>
<section id="services">
<div class="container-fluid">
<div class="col-lg-8 col-lg-offset-2 text-center">
<p>Please fill out the below information to add a product.</p>
<hr class="primary">
</div>
</div>
<div class="container col-md-6 col-md-offset-3">
<form:form action="saveTop" modelAttribute="newProduct" method="POST" >
<div class="form-group">
<label for="category">Category</label>
<label class="checkbox-inline">
<form:radiobutton path="productCategory" id="category" value="top" />Top
</label>
<label class="checkbox-inline">
<form:radiobutton path="productCategory" id="category" value="bottom" />Bottom
</label>
<label class="checkbox-inline">
<form:radiobutton path="productCategory" id="category" value="shoes" />Shoes
</label>
</div>
<div class="form-group">
<label for="name">Product Name</label>
<form:input path="productName" id="name" Class="form-control" />
</div>
<div class="form-group">
<label for="unitInStock">Unit in Stock</label>
<form:textarea path="quantity" id="unitInStock" Class="form-control" />
</div>
<div class="form-group">
<label for="price">Price</label>
<form:textarea path="price" id="price" Class="form-control" />
</div>
<div class="form-group">
<label for="img">Image URL</label>
<form:textarea path="img" id="img" Class="form-control" />
</div>
<div class="form-group">
<label for="description">Description</label>
<form:textarea path="desc" id="description" Class="form-control" />
</div><br>
<div class="col-lg-8 col-lg-offset-2 text-center">
<input type="submit" value="submit" class="btn btn-primary">
Cancel
</div>
</form:form>
</div>
</section>
<%#include file="/WEB-INF/view/template/footer.jsp"%>
Analysis
It looks like some names used in the database context (a table name, a column name, etc.) collide with the reserved words of the database server that you currently use.
Here is a related question: java - org.hibernate.exception.SQLGrammarException: could not execute statement - Stack Overflow.
Solution
Please, check the documentation for the reserved words of the database server.
Please, change the names that collide with the reserved words of the database server.
Draft examples
Microsoft SQL server
Reserved Keywords (Transact-SQL) - SQL Server | Microsoft Docs:
DESC.
TOP.
Therefore, it is required to rename the Top table and the desc column. For example:
#Entity
#Table(name="TopProduct")
public class Top {
// <…>
#Column(name="description")
private String desc;
// <…>
}
MySQL 8.0
MySQL :: MySQL 8.0 Reference Manual :: 9.3 Keywords and Reserved Words:
DESC.
Therefore, it is required to rename the desc column. For example:
// <…>
public class Top {
// <…>
#Column(name="description")
private String desc;
// <…>
}
--> 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 )
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>
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.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<div align="center" style="margin-top:100px;">
<font face="verdana" size="2">
${welcomeMessage} <BR><BR>
${result}
<form:form action="${pageContext.request.contextPath}/login.html" method="POST" modelAttribute="loginForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Login</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /> <form:errors path="username"></form:errors></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /> <form:errors path="password"></form:errors></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" style="background-color:white;" /></td>
</tr>
</table>
</form:form>
Register if not already registered
</font>
</div>
</body>
</html>
HelloController.java
package java4s;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java4s.model.Login;
#Controller
public class LoginSuccessController {
#Autowired
EmployeeService emp_service;
#RequestMapping(value = "/login", method=RequestMethod.POST)
public ModelAndView loginvalidateForm(ModelMap model, #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
if(result.hasErrors()){
model.addAttribute("result", "All Fields are neccessary");
return new ModelAndView("index",model);
}
if(emp_service.validateLogin(login.getUsername(), login.getPassword()))
{
List<Employee> user_info = emp_service.getUserinfo(login.getUsername());
session.setAttribute("session_username", login.getUsername()); //Add value to session variable
model.addAttribute("result", "Login Success");
model.addAttribute("user_info", user_info);
return new ModelAndView("LoginSuccess",model);
}
else
{
model.addAttribute("result", "Login Failure");
return new ModelAndView("index",model);
}
}
}
Login.java
package java4s.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Login {
#NotNull
#Size(min = 3, max = 20)
private String username;
#NotNull
#Size(min = 3, max = 20)
private String password;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
I am trying to put validation on the login fields when they are empty, but errors are not showing on the index page the the login fields are empty. What is the problem in the code?
You have to add the annotation #Valid ( see the spring doc for more details) :
public ModelAndView loginvalidateForm(ModelMap model, #Valid #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
....
}
Don't forget to enable “mvc:annotation-driven” to make Spring MVC supports #Valid annotation.
Add the following tag to your application context XML file.
<mvc:annotation-driven />