如何在Spring MVC simpleformcontroller上添加错误?

时间:2010-06-23 11:29:12

标签: spring spring-mvc

我在Spring MVC 2.5应用程序中遇到此问题,我不知道该怎么做。

这是我的代码:

public class AddStationController extends SimpleFormController {
 private SimpleStationManager stationManager;

 protected ModelAndView onSubmit(HttpServletRequest request,
   HttpServletResponse response, Object command, BindException errors)
   throws Exception {
  StationDetails detail = (StationDetails) command;
  //add to DB
  int return = stationManager.addStation(detail);

  //return value: 1 = successful, 
  //    if not = unsuccessful

  if(return != 1){
   //how can I add error so that when I display my formview ,
   //I could notify the user that saving to the db is not successful?
   showform();
  }
  return new ModelAndView("redirect:" + getSuccessView());
 }
}

当我再次显示我的formview时,如何添加一些消息以便我可以告诉用户添加电台不成功?

如何在我的jsp中处理它?<​​/ p>

2 个答案:

答案 0 :(得分:6)

我起初认为您可能想要使用Validators,但我认为您可以执行以下操作:

public class AddStationController extends SimpleFormController {
 private SimpleStationManager stationManager;

 protected ModelAndView onSubmit(HttpServletRequest request,
   HttpServletResponse response, Object command, BindException errors)
   throws Exception {
  StationDetails detail = (StationDetails) command;
  //add to DB
  int return = stationManager.addStation(detail);

  //return value: 1 = successful, 
  //    if not = unsuccessful

  if(return != 1){
   //Account for failure in adding station
   errors.reject("exception.station.submitFailure", "Adding the station was not successful");
   showform(request, response, errors);
  }
  return new ModelAndView("redirect:" + getSuccessView());
 }
}

然后在JSP中,您可以执行以下操作:

<form:errors path="*">

然后你绑定的任何错误都会显示在那里。

答案 1 :(得分:0)

有几种方法可以做到这一点。我不想使用showForm()方法b / c我想要更多控制。所以我做了以下其中一项,我相信你的问题会有几个替代答案。

如果你不想让特定字段的b / c失败,你可以像这样在模型上发回错误:

ModelAndView mav = new ModelAndView(this.getFormView());
mav.addObject(this.getCommandName(), command);
mav.addObject("errorMessage", "The thing you tried to do failed");
return mav;

然后在你的jsp中你会这样做:

<c:if test="${not empty errorMessage}">
  ${errorMessage}
</c:if>

如果您有一个导致错误的特定字段,您可以将错误附加到特定字段(这样会拒绝称为“alternateid”的字段的长度:

errors.rejectValue("alternateId", "longerThan",
new Object[] { Integer.valueOf(2) }, "Please enter at least two characters.");
ModelAndView mav = new ModelAndView(this.getFormView());
mav.addAllObjects(errors.getModel());
mav.addObject(this.getCommandName(), command);
return mav;

然后在您的jsp中,您将使用表单标记库并执行此操作:

<form:errors path="alternateId"/>

假设您正在使用spring form标记库。