HTTP Status 400 Bad Request - java

I am developing a JAVA Restful Web Application. Earlier all the functions worked correctly. But now I am facing an error saying that
'HTTP Status 400 – Bad Request
Type Status Report
Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
Apache Tomcat/8.5.31'
I cant figure out what is wrong with my code... Looking for some help
Thank You!
//////Here is my module class - (Student.java)
package com.joseph.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Student {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO) //for autonumber
private int studentId;
#Column
private String firstname;
#Column
private String lastname;
#Column
private int yearLevel;
public Student(){}
public Student(int studentId, String firstname, String lastname,
int yearLevel) {
super();
this.studentId = studentId;
this.firstname = firstname;
this.lastname = lastname;
this.yearLevel = yearLevel;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getYearLevel() {
return yearLevel;
}
public void setYearLevel(int yearLevel) {
this.yearLevel = yearLevel;
}
}
////// DAO Class (StudentDao.java)
package com.joseph.dao;
import java.util.List;
import com.joseph.model.Student;
public interface StudentDao {
public void add(Student student);
public void edit(Student student);
public void delete(int studentId);
public Student getStudent(int studentId);
public List getAllStudent();
public List searchStudent(String srch);
}
////DAO Implementation class (StudentDaoImpl.java)
package com.joseph.dao.impl;
import java.util.List;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.joseph.dao.StudentDao;
import com.joseph.model.Student;
#Repository
public class StudentDaoImpl implements StudentDao {
JdbcTemplate template;
#Autowired
private SessionFactory session;
#Autowired
public void setDatsSource(DataSource dataSource) {
template = new JdbcTemplate(dataSource);
}
#Override
public void add(Student student) {
//session.getCurrentSession().save(student);
String sql = "insert into student(firstname, lastname, yearLevel) values ('"+student.getFirstname()+"', '"+student.getLastname()+"', '"+student.getYearLevel()+"')";
template.update(sql);
}
#Override
public void edit(Student student) {
String sql = "update student set firstname = '"+student.getFirstname()+"', lastname = '"+student.getLastname()+"', yearLevel = '"+student.getYearLevel()+"' where studentId = '"+student.getStudentId()+"'";
template.update(sql);
//session.getCurrentSession().update(student);
}
#Override
public void delete(int studentId) {
String sql = "delete from student where studentId = '"+studentId+"'";
String sql2 = "select count(*) from student";
template.update(sql);
int cnt = template.queryForObject(sql2, Integer.class);
System.out.println(cnt);
}
#Override
public Student getStudent(int studentId) {
return (Student)session.getCurrentSession().get(Student.class, studentId);
}
#Override
public List getAllStudent() {
String sql = "select * from student";
return template.queryForList(sql);
}
#Override
public List searchStudent(String stdID) {
String srch = "%" + stdID + "%";
String sql = "select * from student where studentId like '"+srch+"' OR firstname like '"+srch+"'";
return template.queryForList(sql);
}
}
////Student service (StudentService.java)
package com.joseph.service;
import java.util.List;
import com.joseph.model.Student;
public interface StudentService {
public void add(Student student);
public void edit(Student student);
public void delete(int studentId);
public Student getStudent(int studentId);
public List getAllStudent();
public List searchStudent(String srch);
}
////Student service Implementation(StudentServiceImpl.java)
package com.joseph.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.joseph.dao.StudentDao;
import com.joseph.model.Student;
import com.joseph.service.StudentService;
#Service
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentDao studentDao;
#Transactional
public void add(Student student) {
studentDao.add(student);
}
#Transactional
public void edit(Student student) {
studentDao.edit(student);
}
#Transactional
public void delete(int studentId) {
studentDao.delete(studentId);
}
#Transactional
public Student getStudent(int studentId) {
return studentDao.getStudent(studentId);
}
#Transactional
public List getAllStudent() {
return studentDao.getAllStudent();
}
#Transactional
public List searchStudent(String srch) {
return studentDao.searchStudent(srch);
}
}
//Controller Class/////
package com.joseph.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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.bind.annotation.RequestParam;
import com.joseph.model.Student;
import com.joseph.service.StudentService;
#Controller
public class StudentController {
#Autowired
private StudentService studentService;
#RequestMapping("/index")
public String setupForm(Map<String, Object> map){
Student student = new Student();
map.put("student", student);
map.put("studentList", studentService.getAllStudent());
return "student";
}
#RequestMapping(value="/student.do", method=RequestMethod.POST)
public String doActions(#ModelAttribute Student student, BindingResult result, #RequestParam String action, #RequestParam String searchVal, Map<String, Object> map){
Student studentResult = new Student();
String opr = action.toLowerCase();
if(opr.equals("add")) {
studentService.add(student);
studentResult = student;
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
else if(opr.equals("edit")) {
studentService.edit(student);
studentResult = student;
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
else if(opr.equals("delete")) {
studentService.delete(student.getStudentId());
studentResult = new Student();
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
else if(opr.equals("load")) {
Student searchedStudent = studentService.getStudent(student.getStudentId());
studentResult = searchedStudent!=null ? searchedStudent : new Student();
map.put("student", studentResult);
return "studentEdit";
}
else if(opr.equals("search")) {
System.out.println(searchVal);
map.put("student", studentResult);
map.put("studentList", studentService.searchStudent(searchVal));
return "student";
}
else {
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
}
}
//JSP Form - Student.jsp///
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# include file="/WEB-INF/jsp/includes.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Management</title>
</head>
<body>
<h1>Students Data</h1>
<form:form action="student.do" method="POST" commandName="student">
<table>
<tr>
<td><input type="text" name="searchVal" /></td>
<td><input type="submit" name="action" value="Search" /></td>
</tr>
<tr>
<td>First name</td>
<td><form:input type="text" path="firstname" /></td>
</tr>
<tr>
<td>Last name</td>
<td><form:input type="text" path="lastname" /></td>
</tr>
<tr>
<td>Year Level</td>
<td><form:input type="text" path="yearLevel" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="action" value="Add" />
</td>
</tr>
</table>
</form:form>
<br>
<table border="1">
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Year level</th>
<c:forEach items="${studentList}" var="student">
<tr>
<td>${student.studentId}</td>
<td>${student.firstname}</td>
<td>${student.lastname}</td>
<td>${student.yearLevel}</td>
<form:form action="student.do" method="POST" commandName="student">
<form:input path="studentId" value="${student.studentId}" hidden="hidden"/>
<td><input type="submit" name="action" value="Load" /></td>
<td><input type="submit" name="action" value="Delete" /></td>
</form:form>
</tr>
</c:forEach>
</table>
</body>
</html>

#Controller is used to mark classes as Spring MVC Controller, it will response a view
#RestController is used for Restful API. It is a convenience annotation, which includes the #Controller and #ResponseBody annotations
#Controller // please try to update this line.
public class StudentController {
...
}
Change to
#RestController
public class StudentController {
...
}

Related

Spring - sending form gives back null object using Thymeleaf

When I send some data using form it sends null object to controller and I don't know why. I think I have done everything like it was in tutorial but my program does not work properly. Please help :(
I could bet that it is some obvious mistake in code that I don't see because of lack of experience.
Model (I have decided to not use constructor because I don't know how to use it in Spring yet)
import java.math.BigDecimal;
public class Product {
public String name;
public String description;
public BigDecimal price;
public Product(String name, String description, BigDecimal price) {
this.name = name;
this.description = description;
this.price = price;
}
public Product() {
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public BigDecimal getPrice() {
return price;
}
}
DAO
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import com.example.sklepp.service.Product;
import org.springframework.stereotype.Repository;
#Repository
public class ProductDao {
private List<Product> products = Arrays.asList(
new Product("Tea", "green", new BigDecimal("25.00")),
new Product("Coffee", "black", new BigDecimal("30.00")));
public List<Product> all() {
return products;
}
public void addProduct(Product product) {
this.products.add(product);
}
public Product byName(String name) {
for (Product product : products) {
if (name.equals(product.getName())) {
return product;
}
}
return null;
}
}
My controller
import com.example.sklepp.dao.ProductDao;
import com.example.sklepp.service.Product;
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;
#Controller
#RequestMapping("admin")
public class AdminController {
private final ProductDao productDao;
public AdminController(ProductDao productDao) {
this.productDao = productDao;
}
#GetMapping("/")
public String admin(Model model) {
model.addAttribute("newProduct", new Product());
return "admin/admin";
}
#PostMapping("/add-product")
public String addProduct(#ModelAttribute Product product) {
System.out.println(product.getName());
return "redirect:/sklep";
}
}
My template
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<title>Admin service</title>
</head>
<body>
<h1>ADMIN</h1>
<p>+++++++++++++++++++++</p>
<form th:action="#{/admin/add-product}" th:object="${newProduct}" method="post">
<p>Adding new product: </p>
<p>Name: <input type="text" th:field="*{name}"></p>
<p>Price: <input type="text" th:field="*{price}"></p>
<p>Description: <input type="text" th:field="*{description}"></p>
<p><input type="submit" value="Add product"></p>
</form>
</body>
</html>

JSTL Spring Boot - Bean property 'email' is not readable or has an invalid getter method

I am fairly new to using Spring Boot and JSTL. I am currently trying to implement something in my view where I can select multiple checkboxes and send the data over to my controller to operate on. I think I have done everything correctly but can't seem to find the root of the problem here. Can someone please help? Getting the following error:
021-02-09 17:49:45.227 ERROR 16216 --- [nio-8080-exec-6]
o.s.web.servlet.tags.form.CheckboxTag : Invalid property 'email' of
bean class [java.util.ArrayList]: Bean property 'email' is not
readable or has an invalid getter method: Does the return type of the
getter match the parameter type of the setter?
org.springframework.beans.NotReadablePropertyException: Invalid
property 'email' of bean class [java.util.ArrayList]: Bean property
'email' is not readable or has an invalid getter method: Does the
return type of the getter match the parameter type of the setter? at
org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:625)
~[spring-beans-5.3.3.jar:5.3.3] at
org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:615)
~[spring-beans-5.3.3.jar:5.3.3]
My Controller:
package com.bizlinks.mainapp.controller;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import com.bizlinks.mainapp.models.Lead;
import com.bizlinks.mainapp.repository.UserRepository;
#Controller
public class AdminController {
#Autowired // This means to get the bean called userRepository
//Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
#RequestMapping(value = "admin", method = RequestMethod.GET)
public String List(Model model) {
List<Lead> leads = userRepository.findAll();
model.addAttribute("leads", leads);
return "admin";
}
#RequestMapping(value = "admin", method = RequestMethod.POST)
public String deleteLead(#ModelAttribute("leads")List<Lead> leads){
for(int i =0; i< leads.size();i++) {
System.out.println(leads.get(i).getEmail());
}
return "admin";
}
}
My model:
package com.bizlinks.mainapp.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "leads")
public class Lead {
#Id
#Column(name = "email")
private String email;
#Column(name = "firstName")
private String firstName;
#Column(name = "surName")
private String surName;
#Column(name ="phone")
private String phone;
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurName() {
return surName;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
}
My view body:
<body>
<nav class="nav nav-fill">
<a class="nav-link" href="/">Home</a>
</nav>
<div class="container-fluid con">
<table>
<tr>
<th>First Name</th>
<th>Surname</th>
<th>Email</th>
<th>Phone</th>
</tr>
<form:form action="admin" modelAttribute="leads">
<c:forEach items="${leads}" var="item">
<tr>
<td><c:out value="${item.email}"/></td>
<td><c:out value="${item.firstName}"/></td>
<td><c:out value="${item.surName}"/></td>
<td><c:out value="${item.phone}"/></td>
<form:checkbox path="email" value="${item.email}"/>
</tr>
</c:forEach>
<input type="submit" value="Submit" />
</form:form>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js"></script>
</body>

Problem with saving data from Thymeleaf form to database with Spring MVC

I've just started learning Spring MVC. I try to save some data from the Thymeleaf form to repository, which extends CrudRepository. Unfortunately, the data doesn't display.
When I go to the results page I see used IDs but no data typed to form. Where is the mistake?
Here is a Controller
package com.jtm.twiservice.controller;
import com.jtm.twiservice.Main;
import com.jtm.twiservice.model.Customer;
import com.jtm.twiservice.repository.CustomerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
#Controller
public class CustomerClientController {
private static final Logger myLog = LoggerFactory.getLogger(Main.class);
#Autowired
private CustomerRepository customerRepository;
#GetMapping("/customer")
public String customerForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer";
}
#PostMapping("/customer")
public String createCustomer(Customer customer, Model model) {
customerRepository.save(customer);
return "customer";
}
#GetMapping("/customers")
public String getCustomers(Model model) {
model.addAttribute("customers", customerRepository.findAll());
return "customers;
}
}
`Model:
package com.jtm.twiservice.model;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private String schoolForm;
public Customer() {}
public Customer(String firstName, String lastName, String email, String schoolForm) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.schoolForm = schoolForm;
}
#Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s', email='%s', schoolForm='%s']",
id, firstName, lastName, email, schoolForm);
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getSchoolForm() {
return schoolForm;
}
}
repository:
package com.jtm.twiservice.repository;
import com.jtm.twiservice.model.Customer;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Long> { }
form extract:
<form action="#" th:action="#{/customer}" th:object="${customer}" method="post">
<p class="text"><label>first name:</label> <input type="text" th:field="*{firstName}" /></p>
<p class="text"><label>last name:</label> <input type="text" th:field="*{lastName}" /></p
<p class="text"><label>school form:</label> <input type="text" th:field="*{schoolForm}" /></p>
<div class="text">email: <input type="text" th:field="*{email}" /></div>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /> </p>
</form>
And extract from results template:
<td th:text="${customer.id}">customer ID</td>
<td th:text="${customer.firstName}">first name</td>
<td th:text="${customer.lastName}">last name</td>
Try to use
List<Customer> customers = new customerRepository.findAll();
Model.addAttribute("c" , customers);
See my question for more information Store pictures in H2 database spring boot thymleaf
Another way, with this code:
model.addAttribute("customers", customerRepository.findAll());
for result template:
<th:block th:each="customer : ${customers}">
<td th:text="${customer.id}">customer ID</td>
<td th:text="${customer.firstName}">first name</td>
<td th:text="${customer.lastName}">last name</td>
</th:block>
try this :
#PostMapping("/customer")
public String createCustomer(Customer customer,BindingResult result)
{
if (result.hasErrors())
{
return "your error page in here";
}
customerRepository.save(customer);
return "customer";
}
Although this post is already old, I just stumbled upon it when debugging my own code; my answer may still help someone in the future.
I believe I had a similar issue, where the Thymeleaf form didn't actually assign values to the entity's fields. For me the issue was that the entity had no setters for its fields - it looks like you have that problem here as well.

The requested resource is not available in spring mvc

After click on AddEmployee link next page is open given below
when i click on submit the then next page opening like that
addEmployee.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Add Employee Data</h2>
<form:form method="POST" action="/save.html">
<table>
<tr>
<td><form:label path="id">Employee ID:</form:label></td>
<td><form:input path="id" value="${employee.id}" readonly="true"/></td>
</tr>
<tr>
<td><form:label path="name">Employee Name:</form:label></td>
<td><form:input path="name" value="${employee.name}"/></td>
</tr>
<tr>
<td><form:label path="age">Employee Age:</form:label></td>
<td><form:input path="age" value="${employee.age}"/></td>
</tr>
<tr>
<td><form:label path="salary">Employee Salary:</form:label></td>
<td><form:input path="salary" value="${employee.salary}"/></td>
</tr>
<tr>
<td><form:label path="address">Employee Address:</form:label></td>
<td><form:input path="address" value="${employee.address}"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
<c:if test="${!empty employees}">
<h2>List Employees</h2>
<table align="left" border="1">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Employee Address</th>
<th>Actions on Row</th>
</tr>
<c:forEach items="${employees}" var="employee">
<tr>
<td><c:out value="${employee.id}"/></td>
<td><c:out value="${employee.name}"/></td>
<td><c:out value="${employee.age}"/></td>
<td><c:out value="${employee.salary}"/></td>
<td><c:out value="${employee.address}"/></td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
employeeList.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>All Employees</title>
</head>
<body>
<h1>List Employees</h1>
<h3>Add More Employee</h3>
<c:if test="${!empty employees}">
<table align="left" border="1">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Employee Address</th>
</tr>
<c:forEach items="${employees}" var="employee">
<tr>
<td><c:out value="${employee.id}"/></td>
<td><c:out value="${employee.name}"/></td>
<td><c:out value="${employee.age}"/></td>
<td><c:out value="${employee.salary}"/></td>
<td><c:out value="${employee.address}"/></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring3MVC with Hibernate3 CRUD Example using Annotations</title>
</head>
<body>
<h2>Spring3MVC with Hibernate3 CRUD Example using Annotations</h2>
<h2>1. List of Employees</h2>
<h2>2. Add Employee</h2>
</body>
</html>
web.xml file
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
spring-servlet.xml file
<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="com"></context:component-scan>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"></tx:annotation-driven>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="jdbc:postgresql://localhost:5433/databaseDb"></property>
<property name="username" value="postgres"></property>
<property name="password" value="postgres"></property>
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.model.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="hibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
EmployeeController class
package com.controller;
import com.bean.EmployeeBean;
import com.model.Employee;
import com.service.EmployeeService;
import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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 javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.util.*;
/**
* Created by khan on 28/11/16.
*/
#Controller
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Employee employee = prepareModel(employeeBean);
employeeService.addEmployee(employee);
return new ModelAndView("redirect:/add.html");
}
#RequestMapping(value = "/employees", method = RequestMethod.GET)
public ModelAndView listEmployee() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("employeesList", map);
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("index");
}
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView editEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employee", null);
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView deleteEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employee", prepareEmployeebean(employeeService.getEmployee(employeeBean.getId())));
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
private EmployeeBean prepareEmployeebean(Employee employee) {
EmployeeBean employeeBean = new EmployeeBean();
employeeBean.setAddress(employee.getEmpAddress());
employeeBean.setAge(employee.getEmpAge());
employeeBean.setSalary(employee.getEmpSalary());
employeeBean.setName(employee.getEmpName());
employeeBean.setId(employee.getEmpId());
return employeeBean;
}
private Employee prepareModel(EmployeeBean employeeBean) {
Employee employee = new Employee();
employee.setEmpAddress(employeeBean.getAddress());
employee.setEmpAge(employeeBean.getAge());
employee.setEmpName(employeeBean.getName());
employee.setEmpSalary(employeeBean.getSalary());
employee.setEmpId(null);
return employee;
}
private List<EmployeeBean> prepareListofBean(List<Employee> employees) {
List<EmployeeBean> employeeBeen = null;
if (employees != null && !employees.isEmpty()) {
employeeBeen = new ArrayList<EmployeeBean>();
EmployeeBean bean = null;
for (Employee employee : employees) {
bean = new EmployeeBean();
bean.setName(employee.getEmpName());
bean.setAge(employee.getEmpAge());
bean.setSalary(employee.getEmpSalary());
bean.setAddress(employee.getEmpAddress());
bean.setId(employee.getEmpId());
employeeBeen.add(bean);
}
}
return employeeBeen;
}
}
EmployeeService interface
package com.service;
import com.dao.EmployeeDao;
import com.model.Employee;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
public interface EmployeeService {
public void addEmployee(Employee employee);
public List<Employee> listEmployees();
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
EmployeeServiceImpl class
package com.serviceImpl;
import com.dao.EmployeeDao;
import com.model.Employee;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
#Service("EmployeeService")
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addEmployee(Employee employee) {
employeeDao.addEmployee(employee);
}
public List<Employee> listEmployees() {
return (List<Employee>) employeeDao.listEmployees();
}
public Employee getEmployee(int empid) {
return employeeDao.getEmployee(empid);
}
public void deleteEmployee(Employee employee) {
employeeDao.deleteEmployee(employee);
}
}
EmployeeDao interface
package com.dao;
import com.model.Employee;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
public interface EmployeeDao {
public List<Employee> listEmployees();
public void addEmployee(Employee employee);
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
EmployeDaoImpl class
package com.daoImpl;
import com.bean.EmployeeBean;
import com.dao.EmployeeDao;
import com.model.Employee;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
#Repository
public class EmployeeDaoImpl implements EmployeeDao {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<Employee> listEmployees() {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Employee.class);
List<Employee> list = (List<Employee>) criteria.list();
transaction.commit();
return list;
}
public void addEmployee(Employee employee) {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().saveOrUpdate(employee);
transaction.commit();
}
public Employee getEmployee(int empid) {
return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
}
public void deleteEmployee(Employee employee) {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession()
.createQuery("Delete from Employee where id=" + employee.getEmpId()).executeUpdate();
transaction.commit();
}
}
Employee class
package com.model;
import javax.persistence.*;
/**
* Created by khan on 28/11/16.
*/
#Entity
#Table(name = "Employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "empid")
private Integer empId;
#Column(name = "empage")
private Integer empAge;
#Column(name = "empname")
private String empName;
#Column(name = "empaddress")
private String empAddress;
#Column(name = "empsalary")
private Long empSalary;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public Integer getEmpAge() {
return empAge;
}
public void setEmpAge(Integer empAge) {
this.empAge = empAge;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public Long getEmpSalary() {
return empSalary;
}
public void setEmpSalary(Long empSalary) {
this.empSalary = empSalary;
}
}
EmployeeBean class
package com.bean;
import org.omg.CORBA.INTERNAL;
/**
* Created by khan on 28/11/16.
*/
public class EmployeeBean {
private Integer id;
private Integer age;
private String name;
private Long salary;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getSalary() {
return salary;
}
public void setSalary(Long salary) {
this.salary = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Please Help me i try but not getting how to solve this.
Thanks every buddy in advance
change your form action to
<form:form action="${pageContext.request.contextPath}/save.html" method="POST">
..
</form:form>

how to display error message on server side validation in spring mvc

//This is my loginController.java
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class LoginController
{
#RequestMapping(value="/login.htm", method = RequestMethod.POST)
public String login(#RequestParam(value="userid", required=true) String userid,
#RequestParam(value="password", required=true) String password,
#RequestParam(value="confirmpassword", required=true) String confirmpassword,
#RequestParam(value="role", required=true) String role,
Map<String, Object> model)
{
if(userid.matches("^[a-zA-Z0-9]{5,24}$") && password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{5,15}$")
&& confirmpassword.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{6,20}$")
&& (role.equals(new String("OPS(Operational)"))||role.equals(new String("Helpdesk"))))
{
model.put("userid", userid);
model.put("password", password);
model.put("confirmpassword", confirmpassword);
model.put("role", role);
System.out.println("successful!");
return "page2";
}
else
{
return "login";
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
{
String userid = request.getParameter("userid");
String password = request.getParameter("password");
String confirmpassword = request.getParameter("confirmpassword");
String role = request.getParameter("role");
try
{
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
catch (ServletException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String userid = request.getParameter("userid");
String password = request.getParameter("password");
String confirmpassword = request.getParameter("confirmpassword");
String role = request.getParameter("role");
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
}
//This is my login.jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# include file="include.jsp" %>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div align="center" id='formlogin' class="container">
<form method="post" id="loginForm" name="loginForm" action="login.htm">
<table class="tableprop" border="0" width="90%" cellspacing="5" cellpadding="5">
<h3> Add a new user </h3>
<tr>
<td align="center">User ID:</td>
<td><input tabindex="5" size="20" type="text" name="userid" id="userid" value="<%=request.getParameter("userid")!=null?request.getParameter("userid"):""%>"/></td>
</tr>
<tr>
<td align="center">Password:</td>
<td><input tabindex="5" size="20" type="password" name="password" id="password" value="<%=request.getParameter("password")!=null?request.getParameter("password"):""%>"/></td>
</tr>
<tr>
<td align="center">Confirm Password:</td>
<td><input tabindex="5" size="20" type="password" name="confirmpassword" id="confirmpassword" value="<%=request.getParameter("confirmpassword")!=null?request.getParameter("confirmpassword"):""%>"/></td>
</tr>
<tr>
<td align="center">Role:</td>
<td><select name="role" id="role" title="Please select role" tabindex="5" value="<%=request.getParameter("role")!=null?request.getParameter("role"):""%>"/>
<option value="">Select a specific role</option>
<option value="OPS(Operational)">OPS(Operational)</option>
<option value="Helpdesk">Helpdesk</option>
</select></td>
</tr>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<tr>
<td align="center" colspan="4"><input tabindex="7" type="submit" value="Submit" id="submit" class="submit"/></td>
</tr>
<!-- <div id="dialog" title="Dialog Title">I'm in a dialog</div> -->
</table>
</form>
</div>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
</script>
</body>
</html>
I have added here 2 files.
first one is loginController.java
and other one is login.jsp
i have done client side validation in jquery.
now i want to display error message on server side validation in loginController.java file which has code for server side validation. and also i want it to be check once whether loginController.java is written correct or not.
You can use Spring Validator interface to build your own custom validator and use spring form tags.
User.java
package com.expertwebindia.beans;
public class User {
private String name;
private String email;
private String address;
private String country;
private String state;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserValidator.java
package com.expertwebindia.validators;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.expertwebindia.beans.User;
#Component
public class UserValidator implements Validator
{
public boolean supports(Class clazz) {
return User.class.equals(clazz);
}
public void validate(java.lang.Object arg0, Errors arg1) {
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "name", "name.required", "Name is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "email", "Name.required", "Email is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "address", "name.required", "Address is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "country", "country.required", "Country is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "state", "state.required", "State is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "city", "city.required", "City is required.");
}
}
In controller you need to the following code to validate your bean.
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(#ModelAttribute("userForm") User userForm,
BindingResult result, Map<String, Object> model) {
validator.validate(userForm, result);
System.out.println("Email:"+userForm.getEmail());
if (result.hasErrors()) {
return "register";
}else{
return "success";
}
}
Please find more details about this in link below.
http://www.expertwebindia.com/spring-3-mvc-custom-validator-example/

Categories