How to validate @RequestParam in Spring to use con

2019-09-20 11:01发布

问题:

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?

回答1:

Steps to add a validation.

  1. Write a validator Class and implement the Validator Class give the implementation for orerridden method

    import org.springframework.validation.Errors;
    import org.springframework.validation.ValidationUtils;
    import org.springframework.validation.Validator;
    
    public class LoginValidator implements Validator{
    
     @override
     public void validate(Object login, Errors err ){
         //Write your logic to follow up your Login validation
         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "field.required", "UserName Required field");
         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required", "Password Required field");
     }
    
    }
    
  2. Then create a bean entry in the *-servlet.xml

  3. In the JSP add the error Logic

Thanks Pavan