Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Servlet Request object in a POJO class

I need to get the current page URL in a POJO that is being called from an Acegi class (need to add some custom logic for the app I'm working on) and need to retrieve the HttpServletRequest so that I can get the subdomain of the URL (on which the logic is based).

I've tried to add:

@Autowired
private HttpServletRequest request;

...

public void setRequest(HttpServletRequest request) {
    this.request = request;
}

public HttpServletRequest getRequest() {
    return request;
}

However when I try to use the request object in my code, it is null.

Any idea what I am doing wrong or how I can better go about doing this?

like image 648
NRaf Avatar asked Jun 10 '11 00:06

NRaf


1 Answers

If the bean is request scoped you can autowire the HttpServletRequest like you are doing.

@Component @Scope("request") public class Foo {     @Autowired private HttpServletRequest request;      // } 

Otherwise you can get the current request as follows:

    ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();     HttpServletRequest req = sra.getRequest();      

This uses thread-local under the covers.

If you are using Spring MVC that's all you need. If you are not using Spring MVC then you will need to register a RequestContextListener or RequestContextFilter in your web.xml.

like image 112
sourcedelica Avatar answered Sep 24 '22 17:09

sourcedelica