Spring MVC #ModelAttribute in method parameter not binding data with java object - spring-mvc

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).
I am new in Spring MVC and learning about #modelattribute annotation and getting above error.Everything else works fine without modelattribute annotaion. I even tried using #RequestParam instead of #modelattribute and everthing worked fine. But I am not able to understand what is wrong with the code below. Please can anyone help?
AdmissionController.java
package Demo.SpringAnnotation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
#Controller
public class AdmissionController {
#RequestMapping(value="/welcome",method=RequestMethod.GET)
public ModelAndView formLoad() {
ModelAndView mav = new ModelAndView("AdmssionForm");
return mav;
}
#ModelAttribute
public void commonHeaders(Model model1) {
model1.addAttribute("headers", "New College of Engineering");
}
#RequestMapping(value="/admissionsucess",method=RequestMethod.POST)
public ModelAndView submitForm(#ModelAttribute("student1") Student student1) {
ModelAndView mav=new ModelAndView("AmissionSucess");
return mav;
}
}
AdmissionForm.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>Admission Form</title>
</head>
<body>
<h2>${headers }</h2>
<form action="/SpringAnnotation/admissionsucess" method="post">
<table>
<tr>
<td>Name :</td>
<td><input type="text" name="studentName"></td>
</tr>
<tr>
<td>Hobbies:</td>
<td><input type="text" name="studentHobby"></td>
</tr>
<tr>
<td>Mobile:</td>
<td><input type="text" name="studentMobile"></td>
</tr>
<tr>
<td>Date Of birth:</td>
<td><input type="text" name="studentHobby"></td>
</tr>
<tr>
<td>Student Skills:</td>
<td><select name="studentSkills" multiple >
<option value="Java Core">Java Core</option>
<option value="Spring Core">Spring Core</option>
<option value="Spring MVC">Spring MVC</option>
</select></td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
</body>
</html>
AdmissionSuccess.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>Admission Sucess</title>
</head>
<body>
<h2>${headers }</h1>
<h4>Congratulation ${student1.studentName }, Your details are below</h4>
<table>
<tr>
<td>Name:</td>
<td>${student1.studentName}</td>
</tr>
<tr>
<td>Hobbies:</td>
<td>${student1.studentHobby}</td>
</tr>
<tr>
<td>Mobile:</td>
<td>${student1.studentMobile}</td>
</tr>
<tr>
<td>Date Of Birth:</td>
<td>${student1.studentDOB}</td>
</tr>
<tr>
<td>Name:</td>
<td>${student1.studentSkills}</td>
</tr>
</table>
</body>
</html>

You may need to annotate your class not as #Controller but as #ControllerAdvice. A useful page providing an example of the use of #ModelAttribute-- http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation --comments:
It is also important that you annotate the respective class as
#ControllerAdvice. Thus, you can add values in Model which will be
identified as global. This actually means that for every request a
default value exists, for every method in the response part.
Perhaps you are not adding all attributes in your Student class? In any event, perhaps a default object for Student is not available since #ControllerAdvice is not being used. I hope this helps. But regardless, more useful documentation on the subject can be found on that page I referenced above.

Related

Spring MVC exception when i try to read object

i'm new with spring MVC and i'm trying to perform my first application. my objective is to have one web form used to take a string as input and another web form where i write the string on a web page.
i created the following files:
the controller:
package com.gipeto.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 com.prova.form.Prova;
import com.prova.form.User;
#Controller
public class NewController {
#RequestMapping(value="/secondaPagina", method=RequestMethod.GET)
public ModelAndView goToPage(ModelMap model) {
Prova funziona = new Prova();
funziona.setTest("pippo");
model.addAttribute("prova", funziona);
return new ModelAndView("secondPage","model",model);
}
}
my homepage:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
<button onclick="window.location.href='secondaPagina'"> entra </button>
</body>
</html>
The second page.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page session="false" %>
<html>
<head>
<title>Test2</title>
</head>
<body>
<table>
<tr>
<td>nome</td>
<td>sesso</td>
<td>età</td>
</tr>
<tr>
<form:input path="test"/>
</tr>
</table>
<input type=submit value="salva">
</body>
</html>
when i try to run this code i obtain the following error:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message An exception occurred processing JSP page [/WEB-INF/views/secondPage.jsp] at line [17]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: An exception occurred processing JSP page [/WEB-INF/views/secondPage.jsp] at line [17]
14: </tr>
15: <tr>
16:
17: <form:input path="test"/>
18:
19: </tr>
20: </table>
Can you help me to understand where is the issue?
thanks for your help
I think that happens because you don't actually have the form:form tag. Try it like this.
<form:form method="POST">
<table>
<tr>
<td>nome</td>
<td>sesso</td>
<td>età</td>
</tr>
<tr>
<form:input path="test"/>
</tr>
</table>
<input type=submit value="salva">
</form:form>

HTTP Status 400 – Bad Request

Hi i am trying to select category while adding new category.Category details get from DB and I am trying to fetch it's PK to product command by using <form:select> tag.
But it shows following error.
error
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).
My Controller
#RequestMapping(value="productlist/addproduct" , method=RequestMethod.POST)
public String addProdt( #ModelAttribute ("prdt") Product p)
{
pd.addProduct(p);
MultipartFile prodImage=p.getImage();
if(!prodImage.isEmpty()){
Path paths=Paths.get("C:/Users/Dont open/Documents/Eclipse/ClickBuy/src/main/webapp/resources/Images/"+ p.getId()+".png");
try
{
prodImage.transferTo(new File(paths.toString()));
} catch (IllegalStateException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
return "redirect:/allProduct";
}
Jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# include file="header.jsp"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page isELIgnored="false" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#mfg" ).datepicker();
} );
</script>
</head>
<body>
<br>
<h2 align="center">PRODUCT FORM</h2><hr>
<div class="col-md-2 "></div>
<div align="center"><div class="container"><div class="col-md-8 ">
<form:form method="POST" action="productlist/addproduct" commandName="prdt" enctype="multipart/form-data">
<table class="table table-hover">
<tr>
<td> <form:label path="product_Name"> Enter Product Name</form:label></td>
<td><form:input type="text" path="product_Name" class="form-control"/></td>
</tr>
<tr>
<td> <form:label path="descripction"> Enter Product Descripction</form:label></td>
<td><form:input type="text" path="descripction" class="form-control"/></td>
</tr>
<tr>
<td> <form:label path="category"> Enter Product Category</form:label></td>
<td>
<form:select path="category">
<c:forEach var="x" items="${catg}">
<form:option value="${x.category_id}" label="${x.category_name}" /></c:forEach>
</form:select>
</td>
</tr>
<tr>
<td> <form:label path="price"> Enter Product Price</form:label></td>
<td><form:input type="text" path="price" placeholder=" Enter Product Price" class="form-control"/>
</td></tr>
<tr>
<td> <form:label path="mfg_Date"> Enter Manufacture Date</form:label></td>
<td><form:input type="text" id="mfg" path="mfg_Date" class="form-control"/></td>
</tr>
<tr>
<td> <label> Choose Image</label></td>
<td><form:input type="file" path="image" class="form-control"/></td>
</tr>
</table>
<input type="submit" class="btn btn-primary btn-block" value="Add" class="form-control"/>
</form:form>
</div></div></div></body>
</html>
Thanks in advance!!
This error has nothing to do with <form:select> tag
Still There are few things missing in your code which is resulting this error.
In JSP you are trying to upload file along with form data so you need to have multipartResolver bean defined in spring context from common-fileupload.jar
MultipartResolver Spring
Controller method should be changed like this
#RequestMapping(value="/productlist/addproduct" , method= RequestMethod.POST,consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public ModelAndView addProdt(#ModelAttribute("prdt") Product p,BindingResult bindingResult)
This is an old question but In case anyone else experiences the same issue then look how I solved it.
The problem has nothing to do with the post method that was provide. It is thrown by the next page that you are redirecting to ("redirect:/allProduct"). Your ORM could not successfully map the database result to individual objects, this could be caused by not specifying a primary key or having keys that evaluate to null. So visit your database and fix it, make sure you have everything correct in the end.
Error
HTTP Status 400 – Bad Request depctive, malfunction
Type Status Report
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested in logs
I have got the same error while redirecting from one handler to another, my handler was handling request but it couldn't redirected to another Page.
return"redirect:/employeeReport";
I tried all methods but that couldn't solve my issue.
Then I just found that there was sequence mismatch in Entity property and form Property. Just matched all my Entity property and cleaned my project issue resolved.
Advice: Map all fields of your Entity class properly with your form, clean project and run again. Even if there is no issue in mapping of Entity's field this error comes then simply clean project and rerun might work.

Spring form validation: unable to print errors in jsp

I am working on spring mvc application, there I have a form where a user can change his password. I am validating this form by using default spring form validation (see validator code below).
JSP Page:
<%# taglib uri="http://www.springframework.strong textorg/tags/form" prefix="spring"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# 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> Change password </title>
</head>
<body>
<%#include file="index.jsp" %>
<div class="row">
<div class="container" style=" background-color: #F9FFED; ">
<div>
<h4><label>Change password:</label></h4>
</div>
<div class="col-md-12" >
<spring:form commandName="ChangePassword" action="ChangePassword.do" method="post">
<table>
<tr>
<td><label for="current_pwd" >Current Password</label></td>
<td><spring:input path="current_pwd" type="text" class="form-control" placeholder="Name"/></td>
<td><spring:errors path="current_pwd" type="text" cssStyle="color: red;"></spring:errors></td>
</tr>
<tr>
<td>&nbsp</td>
</tr>
<tr>
<td><label for="newpassword" >New Password</label></td>
<td><spring:input path="newpassword" type="text" class="form-control" placeholder="Password"/></td>
<td><spring:errors path="newpassword" type="text" cssStyle="color: red;"></spring:errors></td>
</tr>
<tr>
<td>&nbsp</td>
</tr>
<tr>
<td><label for="confirmPassword" >Confirm Password</label></td>
<td><spring:input path="confirmPassword" type="text" class="form-control" placeholder="Password"/></td>
<td><spring:errors path="confirmPassword" type="text" cssStyle="color: red;"></spring:errors></td>
</tr>
<tr>
<td>&nbsp</td>
</tr>
<tr>
<td>
<button type="submit" class="btn btn-success"> SAVE </button>
Cancel
</td>
</tr>
</table>
</spring:form>
</div>
</div>
</div>
</body>
</html>
Controller get and post methods:
#RequestMapping(value="/ChangePassword",method=RequestMethod.GET)
public String changePassword(ChangePassword chPaswd,BindingResult result,ModelMap model){
chPaswd=new ChangePassword();
model.addAttribute("ChangePassword",chPaswd);
return "ChangePassword";
}
#RequestMapping(value="/ChangePassword",method=RequestMethod.POST)
public String changePasswordPost(ChangePassword chpwd,BindingResult result,ModelMap model,HttpSession session){
String message="";
changepwdValidator.validate(chpwd, result);
chpwd=new ChangePassword();
if(result.hasFieldErrors()){
System.out.println("Has errors");
model.addAttribute("ChangePassword",chpwd);
return "ChangePassword";
}else{
System.out.println("chnage pwd values :"+chpwd.getNewpassword()+","+"current pwd:"+chpwd.getCurrent_pwd());
try{
// some other operations
model.addAttribute("ChangePassword",chpwd);
}catch(Exception e){
message="Failed to process the request, please re-verify the values!";
model.addAttribute("message", message);
}
return "ChangePassword";
}
}
Validator class:
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.knot.pirautomation.models.ChangePassword;
public class ChangePasswordValidator implements Validator{
ChangePassword chngepwd;
public boolean supports(Class clazz) {
return ChangePassword.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
if(target instanceof ChangePassword){
chngepwd=(ChangePassword) target;
System.out.println("----------");
System.out.println("Old pwd:"+chngepwd.getCurrent_pwd());
System.out.println("new pwd:"+chngepwd.getNewpassword());
System.out.println("confirm pwd:"+chngepwd.getConfirmPassword());
System.out.println("----------");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "newpassword", "NewPassword.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "ConfirmPassword.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "current_pwd", "Oldpassword.required");
if( !(chngepwd.getNewpassword().equals(chngepwd.getConfirmPassword()))){
errors.rejectValue("newpassword", "NewPassword.match");
}
if((chngepwd.getNewpassword().length()<8)){
errors.rejectValue("newpassword", "NewPasswordlength.match" );
}
if((chngepwd.getConfirmPassword().length()<8)){
errors.rejectValue("confirmPassword", "ConfirmPasswordlength.match" );
}
String blackListChars = "!'=();<> \"";
char blackListArr[] = blackListChars.toCharArray();
for(int i=0;i<blackListArr.length;i++) {
if(chngepwd.getNewpassword().contains("" + blackListArr[i])) {
errors.rejectValue("newpassword","NewPassword.invalidChars");
break;
}
}
for(int i=0;i<blackListArr.length;i++) {
if(chngepwd.getConfirmPassword().contains("" + blackListArr[i])) {
errors.rejectValue("confirmPassword","ConfirmPassword.invalidChars");
break;
}
}
}
}
}
error.properties file:
Oldpassword.required= Old password is required
NewPassword.required= New password is required
ConfirmPassword.required= Confirm password should be required
NewPassword.match= Confirmation passwords should match
NewPasswordlength.match= New Password should be at least 8 characters
ConfirmPasswordlength.match= Confirm Password should be at least 8 characters
NewPassword.invalidChars=New Password has special characters which are not allowed
ConfirmPassword.invalidChars= Confirm Password has special characters which are not allowed
You can see that when the form has errors, I am returning control back to the same JSP.
My problem is that I am unable to trace the bug/error where my spring form validation is working fine, but when I am trying to display the errors which are defined in my properties file.
You should not explicitly invoke validator. Use this validation method instead:
#Valid #ModelAttribute("forName") FormName formName,
BindingResult bindingResult, Model model,
RedirectAttributes redirectAttributes, HttpSession session

Open A pop window in spring

i have controller through which it navigate to home.jsp in home .jsp there is two button FindEmployeeByid FindEmployeeByName now as i click on FindEmployeeByid new popup window is opened but in pop window i got this message The requested resource (/EmployeeWebSpring/search/Search.jsp) is not available. ,because in Search.jsp i have use form tag of spring so it does not able to get model object so plz tell how i can perform this to open a pop window with input fields active so that i can submit the data a perform some operation on that data
this is my controller
package com.nousinfo.tutorial.controllers;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
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 com.nousinfo.tutorial.model.EmployeeForm;
import com.nousinfo.tutorial.service.impl.EmployeeServiceImpl;
import com.nousinfo.tutorial.service.model.EmployeeBO;
#Controller
#RequestMapping("/search")
public class SearchEmployeeController {
private EmployeeServiceImpl employeeServiceImpl;
public void setEmployeeServiceImpl(EmployeeServiceImpl employeeServiceImpl) {
this.employeeServiceImpl = employeeServiceImpl;
}
#RequestMapping(value = "/searchspring", method = RequestMethod.GET)
public String view(#Validated EmployeeForm employeeForm)
throws Exception {
return "home";
}
#RequestMapping(value = "/employeeNo", method = RequestMethod.POST)
public ModelAndView searchByEmpNo(
#ModelAttribute("employeeForm") EmployeeForm employeeForm)
throws Exception {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
Long i = Long.parseLong(employeeForm.getEmployeeNumber());
EmployeeBO employeeBO = employeeServiceImpl.getEmployee(i);
System.out.println(employeeBO);
model.addObject("employeeBO", employeeBO);
model.setViewName("EmployeeDetail");
return model;
}
#RequestMapping(value = "/empByName", method = RequestMethod.POST)
public ModelAndView searchByEmployeeName(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
List<EmployeeBO> employeeBOs = employeeServiceImpl
.findEmployees(employeeForm.getFirstName());
model.addObject("listEmployeeBO", employeeBOs);
model.setViewName("EmployeeList");
return model;
}
#RequestMapping(value = "/empByDeptId", method = RequestMethod.POST)
public ModelAndView searchByDeptId(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
List<EmployeeBO> employeeBOs = employeeServiceImpl
.getAllEmployeeByDeptid(employeeForm.getDepartmentId());
model.addObject("listEmployeeBO", employeeBOs);
model.setViewName("EmployeeList");
return model;
}
}
this is my home.jsp
<%#page import="java.util.List"%>
<%# 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"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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">
<link rel="stylesheet" href="css/style.css" type="text/css"></link>
<link rel="stylesheet" href="css/styles.css" type="text/css"></link>
<title>Home</title>
<script type="text/javascript">
function LoadByName(windowHeight, windowWidth) {
var centerWidth = (window.screen.width - windowWidth) / 2;
var centerHeight = (window.screen.height - windowHeight) / 2;
newWindow = window.open('Search.jsp', 'mywindow',
'resizable=0,width=' + windowWidth + ',height=' + windowHeight
+ ',left=' + centerWidth + ',top=' + centerHeight);
newWindow.divHiding(1);
newWindow.focus();
}
function LoadById(windowHeight, windowWidth) {
var centerWidth = (window.screen.width - windowWidth) / 2;
var centerHeight = (window.screen.height - windowHeight) / 2;
newWindow = window.open('Search.jsp', 'mywindow',
'resizable=0,width=' + windowWidth + ',height=' + windowHeight
+ ',left=' + centerWidth + ',top=' + centerHeight);
newWindow.divHiding(2);
newWindow.focus();
return newWindow.name;
}
function loadName(name) {
this.firstName = name;
window.location = 'http://localhost:8080/EmployeeWebApp/GetEmployeeServlet?key1='
+ encodeURIComponent(firstName);
}
function loadId(id) {
this.id = id;
window.location = 'http://localhost:8080/EmployeeWebApp/GetEmployeeServlet?key2='
+ encodeURIComponent(id);
}
</script>
</head>
<table width="951" height="116" border="0" align="center">
<tr>
<td width="961" height="112" align="center" bgcolor="#99CCFF"><h2>NOUS
INFOSYSTEMS</h2></td>
<td width="266" height="112" align="center" bgcolor="#FFFFFF"><img
src="image/emps.jpg" alt="1" width="266" height="84" /></td>
</tr>
</table>
<p> </p>
<table width="949" height="183" border="0" align="center">
<tr>
<td width="943" height="43"><input id="findid" name="button"
type="submit" value="Find Employee By Number or ID"
onClick="LoadById(250,500)" /></td>
</tr>
<tr>
<td height="43"><input id="findname" name="submit2" type="button"
value="Find Employee By Name" onClick="LoadByName(250,500)" /></td>
</tr>
<tr>
<td><form id="form2" action="get.spring" method="get">
<input type="submit" name="submit3" value="Get All Employees" />
</form></td>
</tr>
<tr>
<td><form id="form3" action="CreateEmployee.jsp">
<input type="submit" name="submit3" value="Create An Employee" />
</form></td>
</tr>
</table>
<p> </p>
<br>
<br>
<body>
<form>
<table width="725" border="1" align="center" cellpadding="5"
cellspacing="5">
<tr>
<th width="118">EmployeeNumber</th>
<th width="118">First Name</th>
<th width="118">Last Name</th>
<th width="118">Title</th>
<th width="118">Address1</th>
<th width="118">Address2</th>
<th width="118">City</th>
<th width="118">Details</th>
</tr>
<c:forEach var="employeeBO" items="${model.listEmployeeBO}">
<tr>
<td>${employeeBO.employeeNumber}</td>
<td>${employeeBO.firstName}</td>
<td>${employeeBO.lastName}</td>
<td>${employeeBO.title}</td>
<td>${employeeBO.address1}</td>
<td>${employeeBO.address2}</td>
<td>${employeeBO.city}</td>
</tr>
</c:forEach>
</table>
<table>
<tr>
<td></td>
</tr>
</table>
</form>
</body>
</html>
and this is my search.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"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<fmt:setBundle basename="ApplicationResources" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Search Page</title>
</head>
<body>
<form:form action="/EmployeeWebSpring/search/empByName" commandName="employeeForm" method="post">
<table border="0">
<tr>
<td>Employee_ID</td>
<td><form:input path="employeeNumber" /></td>
<td><input type="submit" name="method" value="FindById" /></td>
</tr>
<tr>
<td>Employee_Name</td>
<td><form:input path="firstName" /></td>
<td><input type="submit" name="method" value="FindByName" /></td>
</tr>
<tr>
<td>Employee_Name</td>
<td><form:input path="departmentId" /></td>
<td><input type="submit" name="method" value="FindByDeptNO" /></td>
</tr>
<tr>
<td colspan="2" align="center"><font size=3>For
Searching the employees by<b>Employee Name</b><br />you can use %
match all the records with the given pattern
</font><br /> <font size="2"> <i>e.g <b> for search by</b>EmployeeName<br />
matches alL the employees whose name starts with character <b>S</b></i></font></td>
</tr>
</table>
</form:form>
</body>
</html>
You can do the following in java script and run your java script function as your function run it takes control to controller ,their you can provide the jsp view or any view
<script>
function popup() {
window.open("../popup/searchspring", 'window', 'width=200,height=100');
}
</script>
and in controller you have to do something like this which will navigate your request to desired page cause in spring controller decide the navigation of view pages
#RequestMapping(value = "/searchspring", method = RequestMethod.GET)
public String view(Model model) throws Exception {
EmployeeBO employeeBO = new EmployeeBO();
model.addAttribute("employeeBO", employeeBO);
return "EmployeeForm";
}
I have solved it in my Spring MVC Project by the following way:
The Controller class is like this:
#RequestMapping(value = "viewPicture.dispatch", method = RequestMethod.GET)
public String viewPicture(HttpServletRequest request, RequestParam(value="fileName")String fileName, #RequestParam(value="filePath")String filePath) {
//some code..
return "viewDCPicture"; //the View where it will go.
}
The JSP page on which I have written JS and Html code also, is like this:
<script>
function viewDCPicture(fileName){
var filePath = $("#filePath").val();
//Setting the left and right size of the pop-up window
var left = (screen.width/2)-(1100/2);
var top = (screen.height/2)-(170/2);
$.ajax({
method: "GET",
url : "viewPicture.dispatch?fileName=" + fileName + "&filePath=" + filePath,
success : function(response) {
var strURL = "viewPicture.dispatch?fileName=" + fileName + "&filePath=" + filePath + "";
window.open(strURL, 'viewDCPicture', 'width=1100, height=600, resizable=1, scrollbars=yes, location=0, status=0, titlebar=no, toolbar=0, addressbar=0, top='+top+', left='+left+'');
},
error : function(e) {
}
});
}
</script>
<table>
<tr>
<td align="right"><label>SUPPORTING DOCS.</label></td>
<c:forEach items="${attachmentDtlList}" var="data">
<td>
${data.key}
<input type="hidden" id="filePath" value="${data.value}">
</td>
</c:forEach>
</tr>
</table>
In my template.xml where the JSP files are mapped with the perticular name = "viewDCPicture", I have made changes like this:
I have created a template inside the template.xml file as:
<definition name = "viewDocTemplate" template = "/viewDoc.jsp">
<put-attribute name = "body" value = "" />
</definition>
And used it inside the temlate.xml file as:
<definition extends = "viewDocTemplate" name = "viewDCPicture">
<put-attribute name = "body" value = "/enquiry_management/viewDCPicture.jsp" />
</definition>
The viewDoc.jsp file which will help the Pop-up window file viewDCPicture.jsp to bind it inside body of viewDoc.jsp is as follows:
<%# 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://tiles.apache.org/tags-tiles" prefix = "tiles"%>
<%# taglib uri = "http://www.springframework.org/tags" prefix = "spring"%>
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Insert title here</title>
</head>
<body>
<%-- Adding spring attribute for adding body, header, footer etc tag. --%>
<spring:htmlEscape defaultHtmlEscape = "true" />
<tiles:insertAttribute name = "body" />
</body>
</html>
The viewDCPicture.jsp file is like this:
<html>
<head>
</head>
<table align="center" class="headingSpas">
<tr>
<td class="headingSpas">
<table width="100%" align="center" bgcolor="#CCCCCC">
<tr>
<td colspan="2" align="center" class="headingSpas" >
<img alt="" src="<%=path%>" border="0" align="top" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</html>

calling different method of one spring controller

In my controller there are different method i want to call them with one form action. i dont know how to map map the request to particular method with different value of submit button , as i run my index page it directly go to controller from their it can render the view from view() of my controller and as the Search .jsp is open i get the by default 0 value on my EmployeeId input field i dont know why its happening plz help me out i m new on spring
here is my controller
package com.nousinfo.tutorial.controllers;
import java.util.List;
import org.springframework.stereotype.Controller;
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 com.nousinfo.tutorial.model.EmployeeForm;
import com.nousinfo.tutorial.service.impl.EmployeeServiceImpl;
import com.nousinfo.tutorial.service.model.EmployeeBO;
#Controller
#RequestMapping("/search")
public class SearchEmployeeController {
private EmployeeServiceImpl employeeServiceImpl;
public void setEmployeeServiceImpl(EmployeeServiceImpl employeeServiceImpl) {
this.employeeServiceImpl = employeeServiceImpl;
}
#RequestMapping(value = "/searchspring", method = RequestMethod.GET)
public ModelAndView view(
#ModelAttribute("employeeForm") EmployeeForm employeeForm)
throws Exception {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
model.setViewName("Search");
return model;
}
#RequestMapping(value = "/employeeNo", method = RequestMethod.POST)
public ModelAndView searchByEmpNo(
#ModelAttribute("employeeForm") EmployeeForm employeeForm)
throws Exception {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
Long i = employeeForm.getEmployeeNumber();
EmployeeBO employeeBO = employeeServiceImpl.getEmployee(i);
System.out.println(employeeBO);
model.addObject("employeeBO", employeeBO);
model.setViewName("EmployeeDetail");
return model;
}
#RequestMapping(value = "/empByName", method = RequestMethod.POST)
public ModelAndView searchByEmployeeName(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
List<EmployeeBO> employeeBOs = employeeServiceImpl
.findEmployees(employeeForm.getFirstName());
model.addObject("listEmployeeBO", employeeBOs);
model.setViewName("EmployeeList");
return model;
}
#RequestMapping(value = "/empByDeptId", method = RequestMethod.POST)
public ModelAndView searchByDeptId(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
List<EmployeeBO> employeeBOs = employeeServiceImpl
.getAllEmployeeByDeptid(employeeForm.getDepartmentId());
model.addObject("listEmployeeBO", employeeBOs);
model.setViewName("EmployeeList");
return model;
}
}
and this is my index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
response.sendRedirect("/EmployeeWebSpring/search/searchspring");
%>
this is my search.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"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<fmt:setBundle basename="ApplicationResources" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Search Page</title>
</head>
<body>
<form:form action="/EmployeeWebSpring/search/empByName" commandName="employeeForm" method="post">
<table border="0">
<tr>
<td>Employee_ID</td>
<td><form:input path="employeeNumber" /></td>
<td><input type="submit" name="method" value="FindById" /></td>
</tr>
<tr>
<td>Employee_Name</td>
<td><form:input path="firstName" /></td>
<td><input type="submit" name="method" value="FindByName" /></td>
</tr>
<tr>
<td>Employee_Name</td>
<td><form:input path="departmentId" /></td>
<td><input type="submit" name="method" value="FindByDeptNO" /></td>
</tr>
<tr>
<td colspan="2" align="center"><font size=3>For
Searching the employees by<b>Employee Name</b><br />you can use %
match all the records with the given pattern
</font><br /> <font size="2"> <i>e.g <b> for search by</b>EmployeeName<br />
matches alL the employees whose name starts with character <b>S</b></i></font></td>
</tr>
</table>
</form:form>
</body>
</html>
As an alternative to configuring different endpoints for the same form based on the button clicked (using either separate forms in the HTML or changing the form action via JS), you could use the params attribute of the RequestMapping annotation to further narrow the form submission to a specific controller method based on the value of the button (or any other form submitted field). See the Spring documentation on this for more detail.
Using this strategy, your request mappings would look something like this:
#RequestMapping(value = "/employeeSearch", method = RequestMethod.POST, params="method=FindByName")
public ModelAndView searchByEmployeeName(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
...
#RequestMapping(value = "/employeeSearch", method = RequestMethod.POST, params="method=FindByDeptNO")
public ModelAndView searchByDeptId(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
...
#RequestMapping(value = "/employeeSearch", method = RequestMethod.POST, params="method=FindById")
public ModelAndView searchByEmpNo(
#ModelAttribute("employeeForm") EmployeeForm employeeForm)
throws Exception {
...
i dont know how to map map the request to particular method with different value of submit button
Have each search in a separate form. Each form mapped to different controller methods. Like this:
<form:form action="empById" method="post" commandName="searchBean">
Employee_ID
<form:input path="employeeNumber" />
<input type="submit" name="method" value="FindById" />
</form:form>
<form:form action="empByName" method="post" commandName="searchBean">
Employee_Name
<form:input path="firstName" />
<input type="submit" name="method" value="FindByName" />
</form:form>
<form:form action="empByDeptNo" method="post" commandName="searchBean">
Employee_Name
<form:input path="departmentId" />
<input type="submit" name="method" value="FindByDeptNO" />
</form:form>
Now different search requests will map to the correct controller method.
i get the by default 0 value on my EmployeeId input field i dont know why its happening
Before you add an instance of EmployeeForm to the model, initialize it to what ever default value you would like to have seen in the search page.

Resources