The object in the Controller is not filled in when calling the POST method, it gives an error - spring

I am making a Spring MVC application, when I fill out a table in jsp and click the "save" button, the data is not saved, an error is generated: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null];
here is the output I have on the console: Pass_in_trip [key=null, trip=Trip [trip_no=0, comp=Company [id_comp=0, name=null], plane=null, town_from=null, town_to=null, time_out=null, time_in=null, passInTrips=[]], passenger=Passenger [name=null, passengerId=0, passInTrips=[]], place=6f, date=null]
and at the input to the insert method, my object is empty, tell me what I'm doing wrong?
Controller
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value = "insert", method = RequestMethod.GET)
public String insertnewform(Pass_in_trip pass_in_trip, Model uiModel) {
uiModel.addAttribute("trip",service.findallTrip());
uiModel.addAttribute("passenger",service.findallPassenger());
return "/pass_in_trip/insert";
}
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value = "insert", method = RequestMethod.POST)
public String insert(Pass_in_trip pass_in_trip, BindingResult bindingResult, Model uiModel,
HttpServletRequest httprervletrequest, RedirectAttributes redirectatributes) {
System.out.println(pass_in_trip);
if (bindingResult.hasErrors()) {
uiModel.addAttribute("pass_in_trip", pass_in_trip);
return "pass_in_trip/edit";
}
service.save(pass_in_trip);
return "redirect:/pass_in_trip/";
}
Insert.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Pass_in_trip</title>
<style>
form fieldset {
width: 40%;
}
form fieldset label {
display: block;
/*width : 50%;
float :left;*/
}
form fieldset input, form fieldset select, form fieldset textarea {
width: 100%;
}
</style>
</head>
<body>
<h1>Pass_in_trip</h1>
<form method="POST">
<fieldset>
<div>
<label>Flight:</label>
<select name="trip">
<c:forEach var="trip" items="${trip}">
<option value="${trip}" label="№ ${trip.trip_no} ${trip.town_from} ${trip.town_to}"/>
</c:forEach>
</select>
</div>
<div>
<label>Passenger:</label>
<select name="passenger">
<c:forEach var="passenger" items="${passenger}">
<option value="${passenger}" label="${passenger.passengerId} ${passenger.name}">
</c:forEach>
</select>
</div>
<div>
<label>Date: </label>
<input type="datetime" name="date" value="${pass_in_trip.date}">
</div>
<div>
<label>Place:</label>
<input type="text" name="place" value="${pass_in_trip.place}">
</div>
<div>
<input type="submit" value="Save">
</div>
</fieldset>
</form>
</body>
</html>
Pass_in_trip
#Entity
#Table (name="pass_in_trip")
public class Pass_in_trip implements Serializable {
#Override
public String toString() {
return "Pass_in_trip [key=" + key + ", trip=" + trip + ", passenger=" + passenger + ", place=" + place
+ ", date=" + date + "]";
}
#EmbeddedId
private KeysPass_in_trip key;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("tripId")
#JoinColumn(name="trip_no")
Trip trip = new Trip();
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("psgId")
#JoinColumn(name="id_psg")
Passenger passenger = new Passenger();
#Column(name="place")
private String place;
#Column(name="date")
private Timestamp date;
//Getters and setters

Related

Not Showing error in field of model object in Thymeleaf page

Thymeleaf method fields.errors() which is to collect all validation,
is not showing errors in html pages, and gives error
i have tried all the methods to capture the error.
also tried the article
Main Error :
"Neither BindingResult nor plain target object for bean name 'user' available as request attribute"
Error >>
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903)
at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227)
at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306)
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253)
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227)
at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174)
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
... 69 more
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "user_login" - line 28, col 21)
at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
... 48 more
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "user_login" - line 28, col 21)
Controller class
#GetMapping("/user_login")
public String getUserLoginPage(Model model){
LoginModel user_model = new LoginModel();
model.addAttribute("title", "User Login Page");
model.addAttribute("user", user_model);
return "user_login";
}
// user login Handler
#PostMapping("/process_user_login")
public String processUserLogin(
#Valid #ModelAttribute LoginModel user,
BindingResult bindingResult,Model model){
if(bindingResult.hasErrors()){
logger.info("user login from has some error");
return "user_login";
}
model.addAttribute("user", user);
return "user_login";
}
Model class
package com.attendance.model;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class LoginModel {
#NotBlank(message = "email cannot be blank")
#Size(min = 3, max = 20, message = " 3 -20 charater" )
private String userEmail;
#NotBlank(message = "password cannot be blank")
private String password;
public LoginModel() {
super();
}
public LoginModel(String userEmail, String password) {
super();
this.userEmail = userEmail;
this.password = password;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "LoginModel [userEmail=" + userEmail + ", password=" + password + "]";
}
}
HTML Page/View
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" th:replace="base::layout(~{::section})">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style rel="stylesheet" th:href="#{/css/userlogin.css}" ></style>
<title>Home Page </title>
</head>
<body>
<section>
<div class="card card-container mb-4 pb-5">
<!-- <img class="profile-img-card" src="//lh3.googleusercontent.com/-6V8xOA6M7BA/AAAAAAAAAAI/AAAAAAAAAAA/rzlHcD0KYwo/photo.jpg?sz=120" alt="" /> -->
<img id="profile-img" class="profile-img-card" src="//ssl.gstatic.com/accounts/ui/avatar_2x.png" />
<p id="profile-name" class="profile-name-card"></p>
<form th:object="${user}" th:action="#{/process_user_login}" method="post" class="form-signin">
<span id="reauth-email" class="reauth-email"></span>
<input
type="email"
name="userEmail"
th:field="*{userEmail}"
id="inputEmail"
class="form-control"
placeholder="Email address"
autofocus />
<p th:if="${#fields.hasErrors('userEmail')}" >Incorrect date</p>
<!-- <p th:each="e : ${#fields.errors('userEmail')}" th:text="${e}" ></p> -->
<input
type="password"
name="password"
th:field="*{password}"
id="inputPassword"
class="form-control"
placeholder="Password" />
<div id="remember" class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block btn-signin" type="submit">Sign in</button>
</form>
<!-- /form -->
<a href="#" class="forgot-password">
Forgot the password?
</a>
</div>
<!-- /card-container -->
</section>
</body>
</html>
In Thymeleaf, you can use the th:field attribute to bind a form field to a field in a model object, and the th:errors attribute to display any validation errors for that field.
For example, if you have a model object called user with a field called email, and you want to display an input field for the email address and any validation errors, you could use the following code:
<form>
<label for="email">Email:</label>
<input type="text" th:field="*{user.email}" id="email" />
<div th:if="${#fields.hasErrors('user.email')}" th:errors="*{user.email}">Email error</div>
</form>
If the email field is not showing any validation errors, it is possible that the field is not being validated or that the validation is not being triggered. To troubleshoot this issue, you can try the following:
Make sure that the model object is being passed to the Thymeleaf template correctly, and that the field is being bound to the correct model object field.
Make sure that the field is being validated on the server side, and that the validation rules are being applied correctly.
Make sure that the form is being submitted correctly, and that the validation is being triggered when the form is submitted.
If you are still having trouble displaying the validation errors for the model object field, it may be helpful to review the documentation for the th:field and th:errors attributes, as well as the Thymeleaf Validation Dialect, to ensure that you are using them correctly. You may also want to consider debugging the validation process on the server side to identify any issues.

Retrieving Information from Userinput SpringMVC dropdown box

Hi I'm having some trouble retrieving information from the user using a spring controller.
the controller looks like this:
#Slf4j
#Controller("indexController")
public class IndexController {
List<String> userInput = new ArrayList<>(Arrays.asList(new String[]{"Apple", "Blackberry", "Strawberry"}));
public List<String> getUserInput() {
return userInput;
}
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(
Model model
){
log.info("home path was hit");
model.addAttribute("options", getUserInput());
model.addAttribute("option", new Object());
return "index";
}
#RequestMapping(value = "createOrder", method = RequestMethod.POST)
public String placeUserOrder(
Model model,
#ModelAttribute("option")String usersInput
){
log.info("createOrder path was hit");
log.info(usersInput);
return "redirect:/home";
}
the index.thml within re main/resource/templates folder looks like this:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>home page</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h2>your orders are:</h2>
<form method="post" action="/createOrder" th:object="${order}">
<th:text alignment-baseline="text-before-edge" aria-atomic="true" > select a copybook</th:text>
<select class="from-control" id="dropDownList">
<option value="0">select copybook</option>
<option th:each="option : ${options}" th:value="${option}" th:text="${option}" >
<input type="hidden" name="${_csrf.usersChoiceFromThymeleaf}" value="${_csrf.token}" />
</option>
<input type="submit" name="createOrder" value="place">
</select>
</p>
</p>
</form>
<th:block th:each="order : ${orders}">
<tr>
<td th:text="${order.value}"></td>
</tr>
</th:block>
</body>
</html>
every time after i set a breakpoint within the post function the option value is empty.
what am i doing wrong?
shouldnt i expect a string from selected dropdown menu?
i tried to fetch an int and it remains empty as well
the model contains also only 2 key value pairs "option"->""
and org.springframework.validation.BindingResult.option -> {BeanPropertyBindingResult#7472} "org.springframework.validation.BeanPropertyBindingResult: 0 errors"

How to send dropdown value from the html form to the controller?

index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Super Spy App</title>
</head>
<body>
<h1>Our Super Cool Spy App</h1>
<h2>Create a Mission</h2>
<form action="/addMission" method="post">
<p><input type="submit" value="Create a Mission"></p>
</form>
<form action="/viewMission" method="get">
<h2>View Missions for</h2>
<select id="agents" name="agents">
<option value="Johnny English">Johnny English</option>
<option value="Natasha Romanova">Natasha Romanova</option>
<option value="Austin Powers">Austin Powers</option>
</select>
<input type="submit" value="Go">
</form>
</body>
</html>
ViewMissions.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>View Missions</title>
</head>
<body>
<h1> Here are the missions for</h1>
<div th:if="${missionList.empty}">
<h2>No Current Missions</h2>
</div>
<div th:unless="${missionList.empty}">
<table border="1">
<tr>
<th>Title</th>
<th>Gadget 1</th>
<th>Gadget 2</th>
<th colspan="2">Operation</th>
</tr>
<tr th:each="mission : ${missionList}">
<td th:text="${mission.title}"></td>
<td th:text="${mission.gadget1}"></td>
<td th:text="${mission.gadget2}"></td>
<td>edit</td>
<td>delete</td>
</tr>
</table>
</div>
<p> Back to home </p>
</body>
</html>
Controller Class
#GetMapping("/")
public String Home() {
return "index";
}
#PostMapping("/addMission")
public String addMission(Model model) {
model.addAttribute("mission", new Mission());
return "create_mission";
}
#GetMapping("/createMission")
public String ViewMission1(Model model) {
List<Mission> mission1 = database.getMissions();
model.addAttribute("missionList", mission1);
return "view_missions";
}
#PostMapping("/createMission")
public String createMission(#ModelAttribute Mission mission) {
int returnValue = database.createMission(mission);
System.out.println(returnValue);
return "view_missions";
}
#GetMapping("/viewMission")
public String viewMission2(Model model) {
List<Mission> mission1 = database.getMissions();
model.addAttribute("missionList", mission1);
return "view_missions";
}
getMissions method
public List<Mission> getMissions() {
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
String query = "SELECT * FROM missions";
BeanPropertyRowMapper<Mission> missionMapper = new BeanPropertyRowMapper<Mission>(Mission.class);
List<Mission> missions = jdbc.query(query, namedParameters, missionMapper);
return missions;
}
Mission.java (the getter setter are already set but I didn't paste them here to prevent hustle and bustle)
public class Mission {
private Long id;
private String agent;
private String title;
private String gadget1;
private String gadget2;
}
So, in the above examples, I want to send the value selected from the dropdown list to my controller.
Im my html, if I select any value from the dropdown and press 'Go' it shows me the whole database for all the 3 agents but not the particular one that I selected.
Any suggestions how to curb this error.
I have tried searching for a solution on internet but they were using JSP which I haven't studied yet.
You can get the value submitted from the view to the controller in many ways. As you have a single value is passed from View to Controller you can use
#RequestParam
Your viewMission may look like this
#GetMapping("/viewMission")
public String viewMission2(#RequestParam#RequestParam(name = "agents", required = true) String agents, Model model) {
List<Mission> mission1 = database.getMissions(String agents);
model.addAttribute("missionList", mission1);
return "view_missions";
}
You have to pass the selected value to your query to filter the list based on the selected agent and your query will be
public List<Mission> getMissions(String agents) {
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
String query = "SELECT * FROM missions WHERE agent ='" + agent +"'";
BeanPropertyRowMapper<Mission> missionMapper = new BeanPropertyRowMapper<Mission>(Mission.class);
List<Mission> missions = jdbc.query(query, namedParameters, missionMapper);
return missions;
}
Which will filter the list.

Simple search in Spring MVC

I'm new to Spring MVC, and I'm trying to do a simple search.
Here's my Controller and View. How do I make the search to actually work?
The findTeamByName is already implemented from a interface and the Teams are already populated in memory.
Thank you in advance guys!
#Controller
public class SearchController {
#Autowired
SuperPlayerService sp;
#RequestMapping(value="/search")
public ModelAndView Search(#RequestParam(value = "searchTerm", required = false)
String pSearchTerm, HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
}
JSP:
<%# page contentType="text/html" pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<t:MasterTag>
<jsp:attribute name="pageTitle"><c:out value="Search"/></jsp:attribute>
<jsp:attribute name="currentMenuName"><c:out value="Search"/></jsp:attribute>
<jsp:body>
<div class="row">
<div class="small-3 columns">
<input type="text" id="txt" name="searchString">
</div>
<div class="small-5 columns end">
<button id="button-id" type="submit">Search Teams</button>
</div>
</div>
<div class="row">
<div>
${searchTerm}
</div>
</div>
you can return your values i.e in a ModelAndView
#RequestMapping(value="/search/{searchTerm}")
public ModelAndView Search(#PathVariable("searchTerm") String pSearchTerm) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
This field can be accessed in your search.jsp by ${searchTerm}
EDIT:
if you want so search like: search?searchTerm=java then you can do it with:
#RequestMapping(value="/search")
public ModelAndView Search(#RequestParam(value = "searchTerm", required = false) String pSearchTerm, HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
Spring MVC Controller method can accept a wide range of arguments and one of them is org.springframework.ui.Model.
You can add values to the Model which will become available in your JSP at requestScope.
In your case, your Java code would look like this
#RequestMapping(value = "/search")
public String Search(#RequestParam("searchString") String searchString, Model model) {
if(searchString != null){
Object searchResult = sp.findTeamByName(searchString);
model.addAttribute("searchResult", searchResult);
}
return "search";
}
In your JSP, you could then access the result as usual object in requestScope like ${searchResult}
Your JSP needs to look like:
<%# page contentType="text/html" pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:MasterTag>
<jsp:attribute name="pageTitle"><c:out value="Search"/></jsp:attribute>
<jsp:attribute name="currentMenuName"><c:out value="Search"/></jsp:attribute>
<jsp:body>
<div></div>
<div class="row">
<form method="get" action="/search">
<div class="small-3 columns">
<input type="text" id ="txt" name="searchString" >
</div>
<div class="small-5 columns end">
<button id="button-id" type="submit">Search Teams</button>
</div>
<div>
${player.superTeam}
</div>
</form>
</div>
And your controller would be:
#Controller
public class SearchController {
#Autowired
SuperPlayerService sp;
#RequestMapping(value = "/search")
public String Search(#RequestParam("searchString") String searchString) {
if(searchString != null){
sp.findTeamByName(searchString);
}
return "search";
}
}

How to reject a field from bean for validation when binding?

I have three fields department_Id,department_Name,department_location in departmentForm act as a model object in this model form.
I have use annotation to validate the fields. Now, I want to only use two fields in different jsp page say create.jsp and one field in different jsp page say getDepartmentById.
When I press submit button of create.jsp, validation is happening but after providing correct information its not submitted cause in this page.
I haven't give one field department_Id which is auto generated by my DAO layer. So, please help me, how to reject this value to execute my create.jsp page for successfully creating department in database.
When I printed the BindingResult object, it shown as follow:
Field error in object 'departmentForm' on field 'departmentId': rejected value [null];
codes [NotEmpty.departmentForm.departmentId,NotEmpty.departmentId,NotEmpty.java.lang.String,NotEmpty];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
codes [departmentForm.departmentId,departmentId]; arguments [];
default message [departmentId],org.hibernate.validator.constraints.NotEmpty.message},
[Ljava.lang.Class;#4fc4a198,[Ljava.lang.Class;#764d2b11];
default message [may not be empty]`
This is how I coded in controller:
#RequestMapping(value = "/createDepartment", method = RequestMethod.POST)
public String createEmployee(#Valid DepartmentForm departmentForm,
BindingResult bindingResult, Map<String, DepartmentForm> model)
throws Exception {
if (bindingResult.hasErrors()) {
System.out.println(bindingResult);
bindingResult.reject(departmentForm.getDepartmentId());
return "departmentForm";
}
System.out.println("mr ankur jadiy");
model.put("departmentForm", departmentForm);
departmentForm.setUpdateStatus('A');
if (departmentForm.getUpdateStatus() == 'A') {
departmentServiceImpl
.actionDecider(convertDeptFormToDeptBO(departmentForm));
}
return "Success";
}
my DepartmentForm code is as follow:
package com.nousinfo.tutorial.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class DepartmentForm {
#NotEmpty
#Size(min = 1, max = 20,message="")
private String departmentId;
#NotEmpty
private String departmentName;
private String departmentLocation;
private Character updateStatus;
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentLocation() {
return departmentLocation;
}
public void setDepartmentLocation(String departmentLocation) {
this.departmentLocation = departmentLocation;
}
public Character getUpdateStatus() {
return updateStatus;
}
public void setUpdateStatus(Character updateStatus) {
this.updateStatus = updateStatus;
}
}
and my create.jsp is
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://jakarta.apache.org/taglibs/input-1.0" prefix="input"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Create Department</title>
<link rel="stylesheet" href="css/style.css" type="text/css"></link>
</head>
<body>
<table width="1254" height="74" border="0" align="center">
<tr>
<td width="300" height="68" align="center" bgcolor="#99CCFF"><h2>
<span class="style1">Employee Details </span>
</h2></td>
<td width="100" height="68" align="center" bgcolor="#FFFFFF"><img
src="./image/emps.jpg" width="190" height="92" /></td>
</tr>
</table>
<p>
<br />
</p>
<hr size="1" width="786">
<form:form id="form" method="post" action="/EmployeeWebSpring/departmentController/createDepartment"
modelAttribute="departmentForm">
<table>
<tr>
<form:hidden path="updateStatus" />
</tr>
<tr>
<td>
Department_Name:
<font color="red"><form:errors path="departmentName" /></font>
</td>
</tr>
<tr>
<td><form:input path="departmentName" /></td>
</tr>
<tr>
<td>
Department_Location:
<font color="red"><form:errors path="departmentLocation" /></font>
</td>
</tr>
<tr>
<td><form:input path="departmentLocation" /></td>
</tr>
</table>
<br>
<br />
<p> </p>
<br>
<tr>
<td><input type="submit" name="method" value="save" /></td>
<td><input type="submit" name="method" value="cancel" /></td>
</tr>
<hr size="1" width="786">
<p> </p>
</form:form>
</body>
</html>
What the error says is that you're missing value for departmentId, which is not surprising since you defined it as
#NotEmpty
#Size(min = 1, max = 20,message="")
You don't really need to validate departmentId if it's autogenerated by your code. You probably should remove it from the DepartmentForm, especially since it's not in the form, or at least make it optional.
You can make it mandatory in your business object, but the form backing object should reflect what's in the form.
update
If departmentId is a database-generated id, you should set it as disallowed in your controller's InitBinder:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields(new String[] { "departmentId" });
}

Resources