How to add error in Spring MVC simpleformcontroller?

I have this problem in my Spring MVC 2.5 applications and I'm not sure what to do.

Here is my code:

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());
 }
}

How can I add a message when I show my form again so that I can tell the user that adding a station failed?

And how to handle this in my jsp?

+3
source share
2 answers

At first I thought you could use validators, but instead, I think you can do the following:

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());
 }
}

Then in your JSP you can do the following:

<form:errors path="*">

Then all the errors that you associate will appear.

+6
source

. 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>

, , , ( "":

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.

0

Source: https://habr.com/ru/post/1751372/


All Articles