I am a Spring newbie and have to deal with a method in a Spring controller which works but I would like to improve the code somewhat.
The method is partly implemented in Spring and is required to validate what a user enters on a page. This has two stages: the first is to check that the user's input is numeric, and then to check the database to make sure that the user exists for the value entered.
The method is:
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(@RequestParam("id") String id,
SessionStatus sessionStatus,
Model model) {
Integer personId = null;
try {
personId = Integer.parseInt(id);
}
catch(NumberFormatException e) {
model.addAttribute("message", "Please enter a valid ID.");
sessionStatus.setComplete();
return "errorPage";
}
Person person = null;
person = personService.get(personId);
if (person == null) {
model.addAttribute("message", "Please enter a valid ID.");
sessionStatus.setComplete();
return "errorPage";
}
model.addAttribute("person", person);
sessionStatus.setComplete();
return "userPage";
}
I'd like to use a Spring Validator here but I'm told that these are for form validation of business objects rather than a simple variable.
Or if a Validator can't be used, can I use Spring's own messaging to display errors on the page to the user?
So I would have something like this on the form:
<form:form action="/login" method="get">
<form:input path="id" />
<form:errors path="id" />
<input type="submit" value="Submit">
<input type="Reset" value="Reset">
</form:form>
Can anyone suggest how this method can be improved?