Spring MVC Request input - Tuong-Nguyen/Spring GitHub Wiki

Client can pass data into a controller's handler method by 3 ways:

  • Query parameters
  • Path variable
  • Form parameters

Query parameters

Use annotation @RequestParam

  • defaultValue attribute: default value of the request parameter if it's not specified.

Example

  • Request URL: /spittles?max=238900&count=50
  • SpitterController
    @RequestMapping(method=RequestMethod.GET)
    public List<Spittle> spittles(
            @RequestParam(value="max", defaultValue=MAX_LONG_AS_STRING) long max,
            @RequestParam(value="count", defaultValue="20") int count) {
        return spittleRepository.findSpittles(max, count);
    }

Path parameters

  • Use annotation @PathVariable
  • If no value attribute is given for @PathVariable, it assumes the placeholder’s name is the same as the method parameter name.

Example

  • Request URL /show/{spittleId}. Two ways are the same:
    • @PathVariable long spittleId
    • @PathVariable("spittleId") long spittleId
  • SpitterController
    @RequestMapping(value="/{spittleId}", method=RequestMethod.GET)
    public String spittle(@PathVariable long spittleId, Model model) {
        model.addAttribute(spittleRepository.findOne(spittleId));
        return "spittle";
    }

Form parameters

Example

JSP page registerForm.jsp

<form method="POST">
    First Name: <input type="text" name="firstName" /><br/>
    Last Name: <input type="text" name="lastName" /><br/>
    Username: <input type="text" name="username" /><br/>
    Password: <input type="password" name="password" /><br/>
    <input type="submit" value="Register" />
</form>

SpitterController

    @RequestMapping(value="/register", method=POST)
    public String processRegistration(Spitter spitter) {
        spitterRepository.save(spitter);
    }
  • Spitter parameter has firstName, lastName, username, and password properties that will be populated from the request parameters of the same name.
⚠️ **GitHub.com Fallback** ⚠️