Stefano L
Stefano L

Reputation: 1583

Map @CookieValue, @RequestHeader etc. to POJO in Spring Controller

I have a bunch of params in my controller and want to map all of them to a separate POJO to keep readability. There is also a @CookieValue, @RequestHeader I need to evaluate and aim for a solution to also map them to that POJO. But how?

I saw a possible solution on a blog but it doesn't work, the variable stays null.

Controller:

@RequestMapping(path = MAPPING_LANGUAGE + "/category", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
public String category(CategoryViewResolveModel model) {
    doSomething();
}

And my POJO is this:

public class CategoryViewResolveModel {

private String pageLayoutCookieValue;

public CategoryViewResolveModel() {
}

public CategoryViewResolveModel(
        @CookieValue(value = "SOME_COOKIE", required = false) String pageLayoutCookieValue) {
    this.pageLayoutCookieValue = pageLayoutCookieValue;
}

... some other RequestParams, PathVariables etc.
}

Upvotes: 3

Views: 2052

Answers (2)

Orest
Orest

Reputation: 6748

According to the documentation it's not possible for @CookieValue and @RequestHeader.

This annotation is supported for annotated handler methods in Servlet and Portlet environments.

Upvotes: 3

Peter
Peter

Reputation: 1789

Take a look at: https://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-creating-a-custom-handlermethodargumentresolver/ instead of using getParameter to access request parameters you can use getHeader to retrieve the header value and so define your CategoryViewResolveModel just as you were requesting

Upvotes: 1

Related Questions