Grails - sorting g:sortableColumn with hasMany relation in scaffolding - sorting

I have 3 domain classes:
class Material {
String sku
String description
String uom
String category
String type
double standardPrice
static hasMany = [prices: Price]
static constraints = {
sku(blank:false, nullable:false)
description(blank:false, nullable:false)
}
}
class Price {
double price
static belongsTo = [material: Material, priceList: PriceList]
static constraints = {
}
}
class PriceList {
String priceListName
Date validFrom
Date validTo
Boolean isValid
//static belongsTo = [supplier: Supplier]
static hasMany =[prices: Price]
static constraints = {
}
}
my PriceList update gsp is following:
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<meta name="layout" content="main"/>
<title>Update price list</title>
</head>
<body>
<g:form name="priceListlUpdateForm" id="${priceListInstance.id}">
<div class="buttons" role="navigation">
<g:actionSubmit action="save" class="edit" value="Update" />
<g:actionSubmit action="index" class = "cancel" value = "Cancel" />
<g:actionSubmit action="delete" class ="delete" value="Delete" />
</div>
<div class="body">
<h1>Update price list</h1>
</div>
<table>
<tbody>
<td>Price list name</td>
<td>
<g:textField name ="priceListName" value="${priceListInstance.priceListName}" />
</td>
</tr>
<tr>
<td>Valid From</td>
<td>
<g:datePicker name="validFrom" precision = 'day' value = "${priceListInstance.validFrom}" />
</td>
</tr>
<tr>
<td>Valid To</td>
<td>
<g:datePicker name="validTo" precision ='day' value = "${priceListInstance.validTo}" />
</td>
</tr>
</g:form>
</tbody>
</table>
<div class="constent scaffold-list" role=main>
<h1>Materials for price list</h1>
<table>
<thead>
<tr>
<g:sortableColumn property="sku" title="SKU" />
<g:sortableColumn property="description" title="Description" />
</tr>
</thead>
<tbody>
<g:each in="${pricesInPriceList}" status="i" var="pricesRow">
<tr>
<td>${pricesRow.material.sku}</td>
<td>${pricesRow.material.description}</td>
</tr>
</g:each>
</tbody>
</table>
</div>
</body>
</html>
update in PriceList Controller is following:
def update(long id) {
PriceList row=PriceList.get(id)
def pricesInPriceList = row.prices
[priceListInstance: row, pricesInPriceList: pricesInPriceList]
//render "this is update controller"
}
Everything is working fine except sorting.
When I click sortablecolumn on sku or description sorting is not working (rows are sorted randomly).
I stuck with this sorting. Thank you for help.
Regards,

To get the sorting work, you will need to implement a list method in your controller.. The list code will look like this:
def list(Integer max) {
params.max = Math.min(max ?: 10, 100)
[priceListInstanceList: PriceList.list(params), priceListInstanceTotal:
PriceList.count()]
}

Maybe it will be useful for somebody.
I have changed my update method in PriceList controller as follows:
def update(long id) {
PriceList row=PriceList.get(id)
//default sorting
def pricesInPriceList = row.prices.sort{it.material.sku}
if (params.sort && params.order == "asc") {
pricesInPriceList.asList().sort{it.material."${params.sort}"}
}
if (params.sort && params.order == "desc"){
pricesInPriceList.asList().sort{it.material."${params.sort}"}.reverse()
}
[priceListInstance: row, pricesInPriceList: pricesInPriceList]
}
now sorting with child works perfect.

Related

How do I bind table values to a Map and post with Spring MVC and Thymeleaf?

I have an entry form where users select a subset of items which populate a table. I need to bind each row's first and and third column value to a key and value, respectively, enter them into a Map<Integer, Integer> passed in through the controller, and post the data. I've poured through many different solutions online and have yet to find one that works. The map always returns empty.
Wrapper class for Map
#Getter #Setter
public class ItemForm {
private Map<Integer, Integer> items = new HashMap<>();
}
Controllers
#GetMapping(...)
public String showItemPage(Model model) {
...
model.addAttribute("itemForm", new ItemForm());
...
}
#PostMapping(...)
public String processItemUpdate(#ModelAttribute("itemForm") ItemForm itemForm, BindingResult bindingResult) {
...
}
Template
<tr th:each="item : *{items}">
<td>
<input type="text" th:value="${item.key}">
</td>
<td></td>
<td>
<input type="text" th:field="*{items[__${item.key}__]}">
</td>
</tr>
I understand that I will need something like th:field="*{items[__${item.key}__]}" to access the map, but as to extracting and combining the key-value pair I'm a bit lost.
edit:
Is something along these lines possible?
#Getter #Setter
public class ItemFormPair {
private int ID, quantity;
}
#Getter #Setter
public class ItemForm {
private List<ItemFormPair> items = new ArrayList<>();
}
<tr th:each="item, stat : *{items}">
<td>
<input type="text" th:field="*{items[__${stat.index}__].ID}">
</td>
<td></td>
<td>
<input type="text" th:field="*{items[__${stat.index}__].quantity}">
</td>
</tr>
edit:
I don't really want to spend any more time on this problem and there doesn't appear to be an elegant solution available so I'm simply going to use an Ajax POST request.
You bound the single key/values of the map to the form but not the map itself. That won't work that way. I'm quite sure there is no way to get the map as whole piece back from the form. Maybe with a converter.
An alternative could be to assign name/id to the input fields and read all key/values back to map in the processItemUpdate method:
This solution works on my site. I redefined my answer more precisely:
input.html
<!DOCTYPE HTML>
<html lang="de" xmlns:th="http://www.thymeleaf.org">
<head />
<body>
<form th:action="#{/inputPost}" method="post" th:fragment="form">
<table>
<tr th:each="item,iter : ${itemForm.items.entrySet()}">
<td><input type="text" th:id="${iter.index + '.ID'}"
th:name="${iter.index + '.ID'}" th:value="${item.key}"></td>
<td><input type="text" th:id="${iter.index + '.VALUE'}"
th:name="${iter.index + '.VALUE'}" th:value="${item.value}"></td>
</tr>
</table>
<input type="submit" name="Send" value="Send" /> <input type="submit"
name="Add" value="Add new Line" />
</form>
</body>
</html>
success.html
<!DOCTYPE HTML>
<html lang="de" xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
<table border="1">
<tr th:each="item : ${itemForm.items.entrySet()}">
<td th:text="${item.key}"></td>
<td th:text="${item.value}"></td>
</tr>
</table>
</body>
</html>
Controller
#GetMapping("/inputForm")
public String dummy(Model model) {
ItemForm form = new ItemForm();
form.getItems().put(form.getItems().size(), 42);
model.addAttribute("itemForm", form);
return "input";
}
#PostMapping("/inputPost")
public String processItemUpdate(HttpServletRequest request, Model model) {
Map<String, String[]> params = request.getParameterMap();
ItemForm form = new ItemForm();
String operation = null;
for (Entry<String, String[]> entry : params.entrySet()) {
if (entry.getKey().endsWith(".ID")) { // only react on ID values. The values will be directly fetched from
// map
String[] tokens = StringUtils.split(entry.getKey(), ".");
Integer id = Integer.parseInt(tokens[0]);
Integer idValue = Integer.parseInt(entry.getValue()[0]);
String[] value = params.get(id + ".VALUE"); // fetch the value to defined ID
Integer valueValue = Integer.parseInt(value[0]);
form.getItems().put(idValue, valueValue);
} else if (entry.getKey().equalsIgnoreCase("Send")) { // determine operation
operation = "send";
} else if (entry.getKey().equalsIgnoreCase("Add")) { // determine operation
operation = "add";
}
}
model.addAttribute("itemForm", form);
if (operation.equals("add")) { // add a new line and resend form again
form.getItems().put(form.getItems().size(), 42);
return "input";
}
return "success";
}

ModelAttribute Doesn't return any value from front end to back end

I'm using spring boot and thymeleaf to create a form to collect the data from front-end and update the database at back-end. I'm having trouble to pass the object value by using ModelAttribute. I can almost guaranty my repository and my bean work fine because I have written Junit test case against it and I can see the update from DB. I tried to use th:field at the html page, but it doesn't give me any default value in the field, so I have to use th:value. The print out statements in the controller just keep return 0. It feels like (#ModelAttribute("city") CityBean city) just never pass any data into the variable city. I can't really tell where the problem is after hours of the debugging. I will attach my code here. Thank you very much for helping.
My bean:
public class CityBean {
int cityID;
int population;
String cityName;
String state;
My Repository/DAO:
public int updatePopulation(CityBean city) {
String sql = "UPDATE CITY SET population = ? WHERE cityID = ?";
Object[] args = {city.getPopulation(), city.getCityID()};
int[] types = {Types.VARCHAR, Types.INTEGER};
return jdbcTemplate.update(sql, args, types);
}
My controller:
#RequestMapping(value = "/action", method = RequestMethod.POST)
public String updatePopulation(#ModelAttribute("city") CityBean city) {
System.out.println("This is city ID " + city.getCityID());
System.out.println("This is city population " + city.getPopulation());
cityRepository.updatePopulation(city);
return "redirect:/cityInfo";
}
My Front-end HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>CS6400 Fall 2020 Team 017 Project</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
<h1 style="text-align:center">City Population Update Form</h1>
<br>
<form action="#" th:action="#{/action}" th:object="${city}" method="post" modelAttribute="city">
>
<table class="table">
<thead>
<tr>
<th scope="col">City ID</th>
<th scope="col">City Name</th>
<th scope="col">State</th>
<th scope="col">Population</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr >
<td><input type="text=" th:value="*{cityID}" readonly="readonly"></td>
<td><input type="text=" th:value="*{cityName}" readonly="readonly"></td>
<td><input type="text=" th:value="*{state}" readonly="readonly"></td>
<td><input type="text=" th:value="*{population}" ></td>
<td>
<button type="submit" class="btn btn-primary">Update Population</button>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Problem solved, I added name="pramName" in the input tag then everything works fine.

Controller does not recieve data from jsp page

I have sent data from jsp page to controller. It shows error.
The origin server did not find a current representation for the target
resource or is not willing to disclose that one exists.
This is my controller::::
#GetMapping(value = "/createdistrict")
public ModelAndView createdistrict(Locale locale, Model model) {
List<Division> allDivisionList = new ArrayList<Division>();
allDivisionList = this.districtService.listdivisions() ;
Map<Integer,String> allDivision = new LinkedHashMap<Integer,String>();
for( int i=0 ; i < allDivisionList.size() ; i++) {
//System.out.println(" division id ::::::::::" + allDivisionList.get(i).getId() + " division name:::::::::" + allDivisionList.get(i).getName());
allDivision.put(allDivisionList.get(i).getId() , allDivisionList.get(i).getName());
}
return new ModelAndView("createdistrict" , "allDivision" , allDivision);
}
#RequestMapping(value="/adddistrict/{division}")
public String addDistrict(#ModelAttribute("district")District district, ModelMap model ,#RequestParam("division") int division) {
System.out.println("id:::::::::::::::::::" + division);
this.districtService.adddistrict(district, division);
return "redirect:districtlist";
}
This is my jsp page::::
<form method="POST" action="/farmvill/adddistrict" modelAtribute="district">
<table class="create-table table table-hover">
<tr>
<td>
Division
</td>
<td>
<select id="division" name="division">
<c:forEach items="${allDivision}" var="allDivision">
<option class="dropdivision" value="${allDivision.key}">${allDivision.value }</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td>
Name
</td>
<td>
<input type="text" id="name" name="name" path="name"></input>
</td>
</tr>
<!-- End of single tr -->
</table>
<!-- End of table -->
<div class="button-set text-right">
<button type="submit" class="btn site-btn filled-btn" id="savebutton">save</button>
cancel
reset
</div>
<!-- End of button-set -->
</form>
What I should do now?
Remove division from mapping path. it's a regular request parameter
#RequestMapping(value="/adddistrict")
public String addDistrict(#ModelAttribute("district")District district, ModelMap model ,#RequestParam("division") int division) {

is it possible to add buttons dynamically and pass their values accordingly?

I am new to spring technology please help to solve this problem.
I am developing a web application in spring in which I have a leaveRecords.jsp page,and It should load following things,
For each records the page should display records into the table with two buttons like
<button id="Accept"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id()/>
<button id="Reject"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id()/>
After clicking on accept button relevant action will be performed and should redirect to same page but this time the page should contain button like
<button id="Cancel"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id() />
the leaveRecords.jsp is:
<form:form method="POST" action="upcomingLeaves.do" commandName="loginForm" modelAttribute="loginForm">
<% CommonDTOBean dtoBean=(CommonDTOBean)session.getAttribute("dtoBean");
List upcomingLeavesList=(ArrayList)session.getAttribute("upcomingLeavesList");%>
<table ><col><thead ><tr style="background-color:#666633;">
<th>Employee id</th>
<th>Leave Balance</th>
<th>Date</th>
<th>Leave Type</th>
<th>Leave Period</th>
<th>Applied Leaves</th>
<th>Status</th>
<th colspan="4">Action</th>
</tr></thead>
<tbody>
<%if(upcomingLeavesList!=null){
for(int i=0;i<upcomingLeavesList.size();i++){
dtoBean=(CommonDTOBean)upcomingLeavesList.get(i);%>
<tr>
<td ><span><%= dtoBean.getEmployee_id() %></span></td>
<td ><span><%= dtoBean.getNo_of_leave() %></span></td>
<td ><span></span><%= dtoBean.getFromDate() %>-<%= dtoBean.getToDate() %></td>
<td > <span><%= dtoBean.getLeaveType() %></span></td>
<td ><span></span><%= dtoBean.getLeavePeriod() %></td>
<td><span></span><%= dtoBean.getAppliedLeave() %></td>
<td><span></span><%= dtoBean.getLeaveStatus() %></td>
<td><button id="btnAccept" name="action" type="submit" value="Accept<%= dtoBean.getEmployee_id() %>" onclick="">Approve</button></td>
<td><button id="btnReject" name="action" type="submit" value="Reject<%= dtoBean.getEmployee_id() %>">Reject</button></td>
<td><button id="btnCancel" name="action" type="submit" value="Cancel<%= dtoBean.getEmployee_id() %>">Cancel</button></td>
</tr>
<%}}%>
</tbody>
</table>
</form:form>
Controller class is:
public String ApproveLeaves(#RequestParam(required=false , defaultValue="")String aion,#RequestParam(required=false,defaultValue="")String Cancel,HttpServletRequest request, HttpServletResponse response, ModelMap model){
try{
//following strings are used for getting the value of button and spiting it to get employee id
String buttonName=request.getParameter("action");
String buttonValue=buttonName.substring(0,6);// here we are spliting up the string and button name
int buttonValue1=Integer.parseInt(buttonName.substring(6));
if (buttonValue.equalsIgnoreCase("Reject"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
if (buttonValue.equalsIgnoreCase("Cancel"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
if (buttonValue.equalsIgnoreCase("Accept"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
return GlobalConstants.UPCOMING_LEAVES;
}
catch(Exception e)
{
System.out.println(e);
}
return GlobalConstants.ERRORPAGE;
}
service class has a method for db interaction:
public static boolean Approve(int id,String buttonValue,CommonDTOBean dtoBean2)
{
try {
con=DBConnection.getConnection();
String query="select no_of_leave from newemp_register where emp_id=?";//get available leaves from db
pstmt.executeQuery();
if(buttonValue.equalsIgnoreCase("Cancel"))
{
String approve="Update newemp_register set no_of_leave=? where emp_id=?";
pstmt.executeUpdate();
}
if(buttonValue.equalsIgnoreCase("Reject"))
{
return true;
}
if(buttonValue.equalsIgnoreCase("Accept"))
{
String approve="Update newemp_register set no_of_leave=? where emp_id=?";
pstmt.executeUpdate();
return true;
}
}
}//End Of while
} catch (Exception e) {
}
return false;
}//End of Approve
Please go through this example and help me I have tried very hard and searched on Google but could not solve it.
CommonDTOBean class:
public class CommonDTOBean {
private int emp_id;
private String Status;
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
Use JSTL for conditional rendering the DOM in jsp. like:
<form:form method="POST" action="upcomingLeaves.do" commandName="loginForm" modelAttribute="loginForm">
<table>
<thead>
<tr style="background-color:#666633;">
<th>Employee id</th>
<th>Leave Balance</th>
<th>Date</th>
<th>Leave Type</th>
<th>Leave Period</th>
<th>Applied Leaves</th>
<th>Status</th>
<th colspan="4">Action</th>
</tr></thead>
<tbody>
<c:choose>
<c:when test="${not empty upcomingLeavesList}">
<c:forEach items="${upcomingLeavesList}" var="upComLeave">
<tr>
<td><span>${upComLeave.emp_id}</span></td>
<td><span>${upComLeave.status}</span></td>
<td><span>${upComLeave.fromDate} - ${upComLeave.toDate}</span></td>
<td><span>${upComLeave.leaveType}</span></td>
<td><span>${upComLeave.leavePeriod}</span></td>
<td><span>${upComLeave.appliedLeave}</span></td>
<td><span>${upComLeave.leaveStatus}</span></td>
<c:if test="${upComLeave.leaveStatus ne 'accepted' }"> //check status if accepted, don't render Accept button
<td><button id="btnAccept" name="action" type="submit" value="Accept${upComLeave.emp_id}" onclick="">Approve</button></td>
</c:if>
<c:if test="${upComLeave.leaveStatus ne 'rejected' }">//check status if accepted, don't render Reject button
<td><button id="btnReject" name="action" type="submit" value="Reject${upComLeave.emp_id}">Reject</button></td>
</c:if>
<c:if test="${upComLeave.leaveStatus eq 'cancel' }">//check status if cancel, render cancel button
<td><button id="btnCancel" name="action" type="submit" value="Cancel${upComLeave.emp_id}">Cancel</button></td>
</c:if>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
upcomingLeavesList is empty or null..
</c:otherwise>
</c:choose>
</tbody>
</table>
</form:form>
Edit 1(based on comments):
If I click on approve the page should redirect with only Cancel and
Reject button
use one more if condition like:
<c:if test="${upComLeave.leaveStatus eq 'accepted' }">
<td><button id="btnReject" name="action" type="submit" value="Reject${upComLeave.emp_id}">Reject</button></td>
<td><button id="btnCancel" name="action" type="submit" value="Cancel${upComLeave.emp_id}">Cancel</button></td>
</c:if>
Note:
add this on top of jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

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