DeejUK
DeejUK

Reputation: 13501

Binding from Headers in Spring MVC

Can Spring MVC bind HTTP headers to Java classes?

I've got three headers, and I'd like to marshall them into a POJO, much like you'd do with a form or a request body.

Upvotes: 0

Views: 1090

Answers (1)

Rob Lockwood-Blake
Rob Lockwood-Blake

Reputation: 5066

I can see two ways that you could achieve this with Spring and request or prototype scoped beans.

It is worth first being clear on the different scopes of beans and how Spring creates proxies for different scopes if you are not already.

The first method uses Spring Expression Language to directly reference the current HttpServletRequest instance.

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyClass
{
     @Value({#request.getHeader('headerName')})    
     private String myHeaderValue;

     public String getMyHeaderValue()
     {
            return myHeaderValue;
     }
}

An alternative is to simply inject the current HttpServletRequest as a constructor parameter:

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyClass
{

     private String myHeaderValue;

     @Autowired 
     public MyClass(HttpServletRequest httpServletRequest)
     {
           this.myHeaderValue = httpServletRequest.getHeader("headerValue");
     }

     public String getMyHeaderValue()
     {
           return this.myHeaderValue;
     }
 }

You can then inject this bean into your Controller or Service beans as needed:

@Controller
public class MyController
{
       @Autowired   
       private MyClass myClass;
}

Either method should let you achieve what you want, you can pick which best suits your requirements and preferences.

Upvotes: 1

Related Questions