how to show validation error message if user has not selected any value of spring web mvc dropdown box. Not able to use #Notnull and #Notempty because I'm mapping anothor bean values using #manytoone. How to achieve this?. thanks
#Entity()
#Table(name = "QuestionType")
public class QuestionType {
#Id
#GeneratedValue
#Column(name = "id", nullable = false)
private int id;
#Column(name = "questionTypeName", length = 25, nullable = false)
#Pattern(regexp="[a-z|A-Z|\\s]+$",message = "*invalid")
#Size(max = 25, message = "*invalid")
#NotEmpty(message = "*")
private String questionTypeName;
#ManyToOne
//Here not able to use #Notnull & NotEmpty. I'm getting validator should not be used for primitive type
#JoinColumn(name = "domainid", referencedColumnName = "id", insertable = true, updatable = true)
private Domain domainId;
//getters and setters omited
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="../../tlds/spring-form.tld"%>
<%# taglib prefix="core" uri="../../tlds/c.tld"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Question Type Page</title>
<link href="../../css/default.css" rel="stylesheet" />
</head>
<body>
<form:form commandName="questionType" action="QuestionTypePage.htm" method="post">
<table style="width: 100%; height: 100%;">
<tr height="20px">
<td><span class="label_Heading">Question Type</span></td>
</tr>
<tr height="30px">
<td><form:hidden path="id" />
<div align="center" style="width: 100%; border: solid 1px;"
class="div_Padding">
<span class="label_Normal">Question type</span> <span><form:input
cssClass="textbox_Normal" path="questionTypeName" maxlength="25"/> <form:errors
cssClass="errorMsg" path="questionTypeName" /> </span>
</div>
<div align="center" style="width: 100%; border: solid 1px;"
class="div_Padding">
<span class="label_Normal">Domain</span>
<span>
<form:select path="domainId.id">
<form:option value="0">Select</form:option>
<core:forEach items="${domainList}" var="domain">
<form:option value="${domain.id}">${domain.domainName}</form:option>
</core:forEach>
</form:select><form:errors path="domainId.id" cssClass="errorMsg"/>
</span>
</div></td>
</tr>
<tr height="20px">
<td class="line_Normal">
<table style="width: 100%;">
<tr>
<td><label class="statusMsg">Status :</label><label
class="statusMsg_Small">${statusMsg}</label></td>
<td align="right"><input type="submit" name="button"
value="${buttonValue}" class="button_Normal" /></td>
</tr>
</table>
</td>
</tr>
</form:form>
</body>
</html>
Your data binding is flawed. You should be using the domainId field itself (IMHO that should be named domain instead). Use a Converter to convert to/from that object.
First change the select in your JSP.
<form:select path="domainId" items="${domainList}" itemValue="id" itemLabel="domainName" />
Then your entity should have the #NotNull on the domainId field
#ManyToOne
#JoinColumn(name = "domainid", referencedColumnName = "id", insertable = true, updatable = true)
#NotNull
private Domain domainId;
Finally you need a PropertyEditor to convert the incoming id to a actual Domain object.
public class DomainEditor extends PropertyEditorSupport {
private DomainRepository repository;
public DomainEditor(DomainRepository repository) { this.repository=repository;}
public String getAsText() {
Domain value = (Domain) getValue();
return value != null ? String.valueOf(value.getId()) : "";
}
public void setAsText(String text) {
setValue(text == null ? null : repository.findOne(Integer.valueOf(text));
}
}
You can register this in your #Controller annotated class by adding a #InitBinder annotated method.
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(Domain.class, new DomainEditor(this.repository);
}
A final note for this to properly work make sure that you have a proper implementation of the equals and hashcode methods in the Domain class!
Links
Data Binding / Type Conversion (reference guide)
Related
I am new to Thymeleaf and tried all possible solutions and workaround from web. Desperately I need some help to figure out on what is wrong here.
Not able get cart object(thymeleaf) value updated from html to MVC controller. instead CartViewModel object's fields (userI and products) in cart and modelMap objects are coming as null. even it is not getting values which i passed to populate the table in previous call.
Any help is highly appreciated. Thanks for your valuable time in advance.
Controller debug status
Controller code:
#Controller
public class MyController {
#Autowired
IProductService productService;
#Autowired
IVendorService vendorService;
#RequestMapping(value = "/", method = {RequestMethod.GET})
public String getVendors(VendorViewModel vendorViewModel, final ModelMap modelMap) {
modelMap.addAttribute("vendors", vendorService.getVendors());
return "home";
}
#RequestMapping(value = "/inventory", method = {RequestMethod.POST})
public String getProductsForSelectedVendor(VendorViewModel vendorViewModel, final ModelMap modelMap) {
modelMap.addAttribute("vendors", vendorService.getVendors());
modelMap.addAttribute("cart", new CartViewModel("Nish", productService.getProductsByVendor(vendorViewModel.getId())));
return "home";
}
#RequestMapping(value = "/cart", method = {RequestMethod.POST})
public String saveCart(#ModelAttribute(name = "cart") CartViewModel cart, ModelMap modelMap, BindingResult bindingResult) {
**//not able get cart object value set in html via thymeleaf. **
return "cart";
}
}
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#JsonIgnoreProperties(ignoreUnknown = true)
public class CartViewModel {
private String userId;
//private List<ProductSelected> products;
private List<ProductViewModel> products;
}
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#JsonIgnoreProperties(ignoreUnknown = true)
public class ProductViewModel
{
public String id;
public int qty = 0;
public String handle;
public String title;
public String bodyHTML;
public String vendor;
public String type;
public String tags;
public String variantPrice;
public String imageSrc;
public String imageAltText;
}
<div class="container-main">
<form method="POST" enctype="multipart/form-data" th:object="${vendorViewModel}" th:action="#{/inventory}">
<div>
<div style="float:left;padding-left:10px;">
<label for="selectVendor" class="input-label-name">Select Vendor</label>
</div>
<div style="float:left;padding-left:10px;">
<select id="selectVendor" required="required" th:field="*{id}" style="width:90%">
<option value=""></option>
<option th:each="vendor, iSat : ${vendors}" th:value="${vendor.id}" th:with="test=${vendor.name}" th:text="${vendor.name}">
</option>
</select>
</div>
<div style="float:left;padding-left:10px;">
<input type="submit" value="Get Products" class="btn">
</div>
</div>
</form>
<form method="POST" action="#" role="form" enctype="multipart/form-data" th:action="#{/cart}" th:object="${cart}">
<!-- https://stackoverflow.com/questions/49462788/how-to-post-a-list-to-controller-in-thymeleaf-->
<div style="padding-top: 50px;">
<table id="productTable" class="tableBodyScroll">
<tr>
<th>Quantity</th>
<th>QtyPrice</th>
<th>Handle</th>
<th>Title</th>
<th>Type</th>
<th>Tags</th>
<th>Price</th>
<th>Image</th>
<!-- <th>IN STOCK</th>-->
</tr>
<tr th:id="${prod.id}" th:each="prod,iterStat : ${cart.products}" th:class="${iterStat.odd}? 'odd'">
<td><span class="table-add"><button th:id="'add_' + ${prod.id}" type="button" class="btn btn-rounded btn-sm my-0">+</button></span>
<span type="text" th:id="'count_' + ${prod.id}" th:field="*{products[__${iterStat.index}__].qty}">0</span>
<span class="table-remove"><button th:id="'remove_' + ${prod.id}" type="button" class="btn btn-danger btn-rounded btn-sm my-0">-</button></span>
</td>
<td><span th:id="'qtyPrice_' + ${prod.id}">0</span></td>
<td th:text="${prod.handle}"></td>
<td th:text="${prod.title}"></td>
<td th:text="${prod.type}"></td>
<td th:text="${prod.tags}"></td>
<td th:id="'price_' + ${prod.id}" th:text="${prod.variantPrice}"></td>
<td><img height="50px" width="100px" th:src="${prod.imageSrc}" th:title="${prod.title}" th:alt="${prod.imageAltText}" /></td>
<!-- <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>-->
</tr>
</table>
</div>
<div style="float:left;padding-left:10px;">
<input type="submit" value="Go to Cart" class="btn">
</div>
</form>
</div>
I actually did some work around to overcome my problem using ajax call. But later I came across this, seems to be a better fit for my scenario.
Hope it would help someone.
I have the following code with Thymeleaf and Spring. For some lists that I have the value of the selected option populates the entire object however for some it does not.
public class BeneficiaryUploadCommand {
private List<SchemeCommand> schemeCommandList;
private List<BudgetHeads> budgetHeadsList;
#NotEmpty
private List<BeneficiaryType> beneficiaryTypeLists;
#NotEmpty
private List<FinancialYear> financialYearList;
#NotEmpty
private List<SubSchemes> subSchemesList;
private Date toDate;
private Date fromDate;
#Size(min=10, max = 10)
private String toDate1;
#Size(min=10, max = 10)
private String fromDate1;
#NotEmpty
private List<BenefitType> benefitTypesList;
#NotNull
private Integer beneficiariesProposed;
#NotNull
private Double stateShare;
private Double actualExpenditure;
#NotNull
private Double advancedExpenditure;
#NotNull
private char aadharLinkedOrNot;
#NotNull
private char cropItemDataAvailable;
#NotNull
private String schemeCommandId;
#NotNull
private String budgetHeadsListId;
}
Thymeleaf code is as follows:
<select id="financialYearListId" th:field="*{financialYearList}" style="width:100px; float:left;" >
<option th:value="0" th:text=" Select "></option>
<th:block th:each="finYear : ${beneficiaryData.financialYearList}">
<option th:value="${finYear.id}" th:text="${finYear.financialYear}" label=" - Select - "></option>
</th:block>
</select>
</td>
<td colspan="1" align="right"><font color="red">*</font>
<b>From Date</b>
</td>
<td colspan="1">
<input type="text" th:field="*{fromDate1}" name="from_date" class="date form-control" style="width: 100px; margin: 0px;"/>
</td>
<td colspan="1" align="right"><font color="red">*</font>
<b>To Date</b>
</td>
<td colspan="1">
<input type="text" th:field="*{toDate1}" name="to_date" class="date form-control" style="width: 100px; margin: 0px;"/>
</td>
</tr>
<tr>
<td colspan="1"><font color="red">*</font> <b>Scheme</b></td>
<td colspan="1" width="20%">
<select th:field="*{schemeCommandId}" name="scheme_id" style="width:250px" th:onchange="'getSubSchemesandBudgetHeads(this.value);'">
<th:block th:each="scheme : ${beneficiaryData.schemeCommandList}">
<option th:value="${scheme.id}" th:text="${scheme.schemeName}" label=" - Select - " />
</th:block>
</select>
Now when I select the th:field="*{financialYearList}"
the entire financialyear object of the List object is populated. However with schemeCommandList it only gives the id? I am confused how can some objects be converted whole whereas some it only provides the id.
The difference seems to be that, for the 'financial year' dropdown, your Java class has:
private List<FinancialYear> financialYearList;
which corresponds to the following Thymeleaf markup:
<select id="financialYearListId" th:field="*{financialYearList}"...
However, the 'scheme command' dropdown, has the following markup:
<select th:field="*{schemeCommandId}"...
which is populating the Java field:
private String schemeCommandId;
In other words, the Thymeleaf markup is telling the first dropdown to populate the financialYearList field, where the second one is only telling it to populate the schemeCommandId field, and that seems to be the effect you're seeing.
So, I imagine the solution to get what you want would be to change the Thymeleaf markup for the second dropdown to be:
<select th:field="*{schemeCommandList}"...
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> </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> </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> </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
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>
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.