如何在RedirectView中传递绑定结果对象

时间:2014-07-15 19:31:03

标签: spring jsp jstl

我是Spring的新手,如果表单有错误,我正在尝试重定向到同一页面。我成功重定向,但问题是表单有一个动态下拉列表,当我返回一个模型对象时,不会呈现值。或者当我做ModelAndView(新的RedirectView(“查找”))时,我能够呈现下拉值,但我无法显示错误消息。

代码:jsp:lookup.jsp

<form:form   name="lookupForm" method="POST"  action="search.html"        enctype="multipart/form-data"  >
<div style= "color:red">
<form:errors path="empId" /></br>
<form:errors path="companyName" />
</div>
<form:label path="companyName">Company</form:label>
<select name= "companyList" path="companyName">
<option value="Select">Select</option>
<c:forEach  var="element" items="${listCompany}"> 
<option value="${element.companyName}">${element.companyName}</option>
</c:forEach>
</select>
<form:label path="empId">Employee ID</form:label>
<form:textarea name="empId" path="empId" rows="5" cols="30"/>
<input type="submit" name="search" value="Search"/>

控制器:

@RequestMapping(value = "/lookup", method = RequestMethod.GET)
public ModelAndView lookupFormView(ModelAndView model,BindingResult result) {
List<Employee> listCompany = employeeDAO.getCompany();
Employee newContact = new Employee();           
model.addObject("listCompany", listCompany);
model.addObject("command", newContact);
model.setViewName("lookup");
return model;  
}


@RequestMapping(value = "/search", params = "search", method = RequestMethod.POST)
public ModelAndView lookupEmployee(HttpServletRequest request,HttpServletResponse  response, @ModelAttribute("command") Employee emp,BindingResult result) throws Exception{
empValidator.validate(emp, result);
String lookupEmpId = null;
if (result.hasErrors()) {
return  new ModelAndView(new RedirectView("lookup"));
//return  new ModelAndView("lookup");
}
else{
        -----

如果我使用这个返回新的ModelAndView(new RedirectView(“lookup”));它重定向到lookup.jsp,呈现下拉值但是没有显示错误消息。 如果我使用这个返回新的ModelAndView(“查找”);它重定向到lookup.jsp,显示错误,但不呈现动态下拉值。

请帮助我找出我的代码的哪一部分是错误的,或者他们是一种显示错误消息和呈现动态下拉值的方法

1 个答案:

答案 0 :(得分:0)

只需返回视图名称并在模型本身中设置错误消息。只需检查JSP中的错误消息(如果找到),然后显示它。

示例代码:

@RequestMapping(value = "/search", params = "search", method = RequestMethod.POST)
public String lookupEmployee(HttpServletRequest request,HttpServletResponse response, 
                    @ModelAttribute("command") Employee emp,BindingResult result) throws Exception{
    empValidator.validate(emp, result);
    String lookupEmpId = null;
    if (result.hasErrors()) {
       emp.setErrorMessage("Your error message.");
       return  "lookup";
    }else{
       ...
       return "successPage";
    }
 }