Spring MVC - Response - spring

How can I access the response object from a bean? To get the request object I use the following.
ServletRequestAttributes attr = (ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes();
Is there something similar to the above for response object?

If you are in a web application context (which it looks like you are) you can auto wire in the HttpServletRequest or HttpServletResponse.
The request/response from the current request scope will be injected.
#Component
public class SomeComponentInAWebApplicationContext {
#Autowired
private HttpServletRequest request;
#Autowired
private HttpServletResponse response;
...
}

Related

#ConfigurationProperties object returned null in spring boot application

I have a config object which is mapped to the config file as below:
#Data
#Component
#ConfigurationProperties("app.cors")
public class DomainProperties {
private Map<String, String> domainMap;
}
and my application.properties config file looks like:
app.cors.domainMap.local=localhost:8080
app.cors.domainMap.onlive=test.com
I am trying to read the values in the domainMap from the above properties file, to set them as Access-Control-Allow-Origin headers for the response of my application. What I did so far is:
public class HeaderInterceptor extends HandlerInterceptorAdapter {
#Autowired
private DomainProperties domainProperties;
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
List<String> domainList= domainProperties.getDomainMap().values().stream().collect(Collectors.toList());
domainList.stream().forEach(domain -> response.addHeader("Access-Control-Allow-Origin", domain));
return super.preHandle(request, response, handler);
}
but the problem is I received back a null domainProperties object, therefore a NullPointerException is thrown here.
Can anyone explain me why did I get a null domainProperties object here? and how to resolve this problem. Thank you in advanced!

Difference between SessionBean and SessionAttribute

What is the difference between SessionBean and SessionAttribute, what is the best way to add an object to a session? For example:
SessionBean:
#Component
#Scope(value = "session")
class A {
...
}
SessionAttribute:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
A a = new A();
session.setAttribute("A", a);
}
They're very similar and both of those objects can be retrieved through HttpSession object.
The only difference between them is that SessionBean will be injected by Spring and session attribute will be added to session by programmer using HttpSession#setAttribute(String, Object)) method.
I would use SessionBean if you know that this bean would be required in session and you also know all required state or the behaviour of the bean and SessionAttribute when you receive the information in runtime.

Spring Data Rest - How to receive Headers in #RepositoryEventHandler

I'm using the latest Spring Data Rest and I'm handling the event "before create". The requirement I have is to capture also the HTTP Headers submitted to the POST endpoint for the model "Client". However, the interface for the RepositoryEventHandler does not expose that.
#Component
#RepositoryEventHandler
public class ClientEventHandler {
#Autowired
private ClientService clientService;
#HandleBeforeCreate
public void handleClientSave(Client client) {
...
...
}
}
How can we handle events and capture the HTTP Headers? I'd like to have access to the parameter like Spring MVC that uses the #RequestHeader HttpHeaders headers.
You can simply autowire the request to a field of your EventHandler
#Component
#RepositoryEventHandler
public class ClientEventHandler {
private HttpServletRequest request;
public ClientEventHandler(HttpServletRequest request) {
this.request = request;
}
#HandleBeforeCreate
public void handleClientSave(Client client) {
System.out.println("handling events like a pro");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements())
System.out.println(names.nextElement());
}
}
In the code given I used Constructor Injection, which I think is the cleanest, but Field or Setter injection should work just as well.
I actually found the solution on stackoverflow: Spring: how do I inject an HttpServletRequest into a request-scoped bean?
Oh, and I just noticed #Marc proposed this in thecomments ... but I actually tried it :)

Can you use request scoped #Context variables in a singleton ContextResolver in JAX-RS?

I'm using Jersey 1.13 with Spring. I've got a ContextResolver defined like so:
#Provider
public class ThemeSourceContextResolver implements ContextResolver<ThemeSource> {
#Context private HttpServletRequest request;
#Override
public ThemeSource getContext(Class<?> type) {
return new DefaultThemeSource(request);
}
}
<bean id="themeSourceContextResolver" scope="singleton" class="com.example.ThemeSourceContextResolver" />
Is the above valid? Specifically, is it "legal" (or does it make sense) to use the #Context private HttpServletRequest request in a ContextResolver? Since the ContextResolver is a singleton, does Jersey/JAX-RS do some threadlocal proxy magic or something to allow it to have access to the HttpServletRequest of every request?
It's not valid. #Context is injected only into JAX-RS resources. ContextResolver<?> has nothing to do with request context, mostly because it's a singleton, as you said.
To update this answer for Jersey 2.14:
The answer is now "sometimes". Jersey does indeed do proxy magic for specific #Context variables, namely HttpHeaders, Request, UriInfo and SecurityContext. Your specific case, HttpServletRequest, is not supported.
See https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e2578.

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?
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.

Resources