4

How come this code just works? I didn't specify any custom converter or annotation (like @RequestBody or @ModelAttribute) before argument ? Request is filled correctly from this GET call:

http://localhost:8080/WS/foo?token=C124EBD7-D9A5-4E21-9C0F-3402A1EE5E9B&lastSync=2001-01-01T00:00:00&pageNo=1

Code:

@RestController
@RequestMapping(value = "/foo")
public class FooController {

    @RequestMapping(method = RequestMethod.GET)
    public Result<Foo> excursions(Request request) {    
        // ...
    }   

}

Request is just POJO with getters and setters. I use it to shorten argument code because plenty methods uses those same arguments ...

public class Request {

    private String token;
    @DateTimeFormat(pattern = IsoDateTime.DATETIME)
    private Date lastSync;
    private Integer pageNo;

    // getters and setters

}

This was my original method before introducing Request.

@RestController
@RequestMapping(value = "/foo")
public class FooController {

    @RequestMapping(method = RequestMethod.GET)
    public Result<Foo> excursions(@RequestParam String token, @RequestParam @DateTimeFormat(pattern = IsoDateTime.DATETIME) Date lastSync, @RequestParam Integer pageNo) {
        // ...
    }

}

2 Answers 2

2

Request parameters will be mapped to POJOs, as it is happening in your case, by default. Additionally, if you use @ModelAttribute, an attribute in the Model will be created. That attribute can be then used in views, e.g. JSPs, to access the object.

@RequestBody annotation tells that the body of the request is NOT a set of form parameters like

token=C124EBD7-D9A5-4E21-9C0F-3402A1EE5E9B&lastSync=2001-01-01T00:00:00&pageNo=1

but is in some other format, such as JSON.

Sign up to request clarification or add additional context in comments.

Comments

0

This is a feature provided by Spring MVC:

Customizable binding and validation. Type mismatches as application-level validation errors that keep the offending value, localized date and number binding, and so on instead of String-only form objects with manual parsing and conversion to business objects.

You can see it in the doc: http://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/htmlsingle/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.