Using Interceptors to validate the requests in Spring Web.
I've extended HandlerInterceptorAdapter to implement postHandle method.
I want to check the value inside application response object and accordingly do some action.
I tried IOUtils to get the app response object but getting a "" string.
public class XYZInterceptor extends HandlerInterceptorAdapter {
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
// need to retrieve application response object
return;
}
}
After going through many docs, and hands on I figured out that the input stream / output steam can be accessed only once. The response object would already have written output stream somewhere before it reaches postHandler. So output stream is empty in response object of postHandle.
If you wish to access response object in postHandle is to setAttribute for request object with actual response object.
Related
I am trying to access httpServletRequest inside a component class. I tried it in several ways.
#Component
public class MyService{
#Resource
WebServiceContext wsCtxt;
public void myWebMethod(){
MessageContext msgCtxt = wsCtxt.getMessageContext();
HttpServletRequest req = (
(HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST);
String clientIP = req.getRemoteAddr();
}
This didn't work for me. because WebServiceContext is always null. Then I tried same code inside Web service class. Then that code is working. My Requirement it to get HttpServletRequest inside component class. (ultimately What i am trying to do it get client host from request header).
It this possible to do ?. Are there any alternatives for this ?
Method #1
Have you tried passing the request object into your component by passing it in as an argument to your service method, and from your service to your component method?
// in your controller... Spring provides the request object
public String myController(HttpServletRequest request, ...) {
//...
myService.myServiceMethod(request,...);
}
// in your service...
public void myServiceMethod(HttpServletRequest request, ...) {
//...
myComponent.myWebMethod(request,...);
}
// in your component
public String myWebMethod(HttpServletRequest request, ...) {
// use the raw request object
}
Method #2
Also, DispatcherServlet exposes the request object by wrapping it in a ServletRequestAttributes object, which in turn is stored in a ThreadLocal variable. The actual storing takes place in RequestContextHolder and its static methods. You can access it as follows:
public void myWebMethod(){
//...
RequestAttributes reqAttr = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes servlReqAttr = (ServletRequestAttributes)reqAttr;
HttpServletRequest req = servlReqAttr.getRequest();
//...
}
Although a little verbose, you can see what's going on.
You could also condense it:
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
I hope this helps!
I am really not sure if this is feasible using Spring 3.2 MVC.
My Controller has a method declared as below:
#RequestMapping(method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody List<Foo> getAll(){
return service.getAll();
}
Questions:
What is the meaning of #ResponseStatus(HttpStatus.OK) ?
Does it signifies that the method will always return a HttpStatus.OK status code.
What if an exception is thrown from the service layer?
Can I change the Response Status on occurrence of any exception?
How can I handle multiple response statuses depending on conditions in the same method?
#ResponseStatus(HttpStatus.OK) means that the request will return OK if the handling method returns normally (this annotation is redundant for this case, as the default response status is HttpStatus.OK). If the method throws an exception, the annotation does not apply; instead, the status will be determined by Spring using an exception handler.
How can I handle multiple response statuses depending on conditions in the same method?
That question has already been asked.
Can I change the Response Status on occurrence of any exception
You have two choices. If the exception class is one of your own, you could annotate the exception class with #ResponseStatus. The other choice is to provide the controller class with an exception handler, annotated with #ExceptionHandler, and have the exception handler set the response status.
If you return a ResponseEntity directly, you can set the HttpStatus in that:
// return with no body or headers
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
If you want to return an error other than 404, HttpStatus has lots of other values to choose from.
You cannot set multiple status value for #ResponseStatus. One approach I can think of is to use #ExceptionHandler for response status which is not HttpStatus.OK
#RequestMapping(value = "login.htm", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.OK)
public ModelAndView login(#ModelAttribute Login login) {
if(loginIsValidCondition) {
//process login
//.....
return new ModelAndView(...);
}
else{
throw new InvalidLoginException();
}
}
#ExceptionHandler(InvalidLoginException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
public ModelAndView invalidLogin() {
//handle invalid login
//.....
return new ModelAndView(...);
}
I am building a HTTP proxy with netty, which supports HTTP pipelining. Therefore I receive multiple HttpRequest Objects on a single Channel and got the matching HttpResponse Objects. The order of the HttpResponse writes is the same than I got the HttpRequest. If a HttpResponse was written, the next one will be written when the HttpProxyHandler receives a writeComplete event.
The Pipeline should be convenient:
final ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("writer", new HttpResponseWriteDelayHandler());
pipeline.addLast("deflater", new HttpContentCompressor(9));
pipeline.addLast("handler", new HttpProxyHandler());
Regarding this question only the order of the write calls should be important, but to be sure I build another Handler (HttpResponseWriteDelayHandler) which suppresses the writeComplete event until the whole response was written.
To test this I enabled network.http.proxy.pipelining in Firefox and visited a page with many images and connections (a news page). The problem is, that the browser does not receive some responses in spite of the logs of the proxy consider them as sent successfully.
I have some findings:
The problem only occurs if the connection from proxy to server is faster than the connection from proxy to browser.
The problem occurs more often after sending a larger image on that connection, e.g. 20kB
The problem does not occur if only 304 - Not Modified responses were sent (refreshing the page considering browser cache)
Setting bootstrap.setOption("sendBufferSize", 1048576); or above does not help
Sleeping a timeframe dependent on the responses body size in before sending the writeComplete event in HttpResponseWriteDelayHandler solves the problem, but is a very bad solution.
I found the solution and want to share it, if anyone else has a similar problem:
The content of the HttpResponse is too big. To analyze the content the whole HTML document was in the buffer. This must be splitted in Chunks again to send it properly. If the HttpResponse is not chunked I wrote a simple solution to do it. One needs to put a ChunkedWriteHandler next to the logic handler and write this class instead of the response itself:
public class ChunkedHttpResponse implements ChunkedInput {
private final static int CHUNK_SIZE = 8196;
private final HttpResponse response;
private final Queue<HttpChunk> chunks;
private boolean isResponseWritten;
public ChunkedHttpResponse(final HttpResponse response) {
if (response.isChunked())
throw new IllegalArgumentException("response must not be chunked");
this.chunks = new LinkedList<HttpChunk>();
this.response = response;
this.isResponseWritten = false;
if (response.getContent().readableBytes() > CHUNK_SIZE) {
while (CHUNK_SIZE < response.getContent().readableBytes()) {
chunks.add(new DefaultHttpChunk(response.getContent().readSlice(CHUNK_SIZE)));
}
chunks.add(new DefaultHttpChunk(response.getContent().readSlice(response.getContent().readableBytes())));
chunks.add(HttpChunk.LAST_CHUNK);
response.setContent(ChannelBuffers.EMPTY_BUFFER);
response.setChunked(true);
response.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
}
}
#Override
public boolean hasNextChunk() throws Exception {
return !isResponseWritten || !chunks.isEmpty();
}
#Override
public Object nextChunk() throws Exception {
if (!isResponseWritten) {
isResponseWritten = true;
return response;
} else {
HttpChunk chunk = chunks.poll();
return chunk;
}
}
#Override
public boolean isEndOfInput() throws Exception {
return isResponseWritten && chunks.isEmpty();
}
#Override
public void close() {}
}
Then one can call just channel.write(new ChunkedHttpResponse(response) and the chunking is done automatically if needed.
I am trying to implement a filter that uses MockHttpServletRequest to add a header to the request object. I want to use that header for preauthentication. This is the filter class..
public class MockAuthFilter implements Filter{
private FilterConfig filterConfig = null;
private static String loggedInUserName = "myId";
private static String httpRequestHeaderName = "SM_ID";
private Logger logger = Logger.getLogger(MockAuthFilter.class);
#Override
public void destroy() {
this.filterConfig = null;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(this.filterConfig.getServletContext() == null){}
HttpServletRequest httpRequest = (HttpServletRequest) request;
MockHttpServletRequest mRequest = new MockHttpServletRequest(this.filterConfig.getServletContext());
if(mRequest.getHeader(httpRequestHeaderName)==null ||
!mRequest.getHeader(httpRequestHeaderName).equalsIgnoreCase(loggedInUserName))
mRequest.addHeader(httpRequestHeaderName, loggedInUserName);
mRequest.setMethod("GET");
mRequest.setRequestURI(httpRequest.getRequestURL().toString());
logger.debug("**********************exiting doFilter() method*****************");
chain.doFilter(mRequest, response);
}
#Override
public void init(FilterConfig config) throws ServletException {
this.filterConfig = config;
}
}
but there is not url populated when the request reaches the next filter in the filter chain of Spring Security. I see following lines in the log file..
[2011-10-13 16:52:35,114] [DEBUG] [http-8080-1] [com.app.filter.MockAuthFilter:doFilter:55] - **********************exiting doFilter() method*****************
[2011-10-13 16:52:35,114] [DEBUG] [http-8080-1] [com.app.filter.MockAuthFilter:doFilter:55] - **********************exiting doFilter() method*****************
[2011-10-13 16:52:35,114] [DEBUG] [http-8080-1] [org.springframework.security.web.util.AntPathRequestMatcher:matches:103] - Checking match of request : ''; against '/static/**'
[2011-10-13 16:52:35,114] [DEBUG] [http-8080-1][org.springframework.security.web.util.AntPathRequestMatcher:matches:103] - Checking match of request : ''; against '/static/**'
As you can see there was no url in the request object passed onto AntPathrequestMatcher's matches method..
I have checked mockrequest object right before chain.doFilter() method and it contains the url value in its requestURI field. if URI and URL aren't the same thing here, what changes should I make here so that url is maintained in the request object..
Don't use MockHttpServletRequest like that. It's for testing, not for production code. The appropriate way to wrap a request and/or response in a filter to modify its behavior later on is with HttpServletRequestWrapper and HttpServletResponseWrapper.
Why are you even trying to wrap or remove the original request if all you want is to add a header? Just use addHeader() on the incoming request.
Trying to change the request method and request URI in the filter as you're doing may have unexpected consequences and will almost certainly not do what you probably expect it to do. By the time the request hits your filter, the filter chain has already been built based on the original state of the request. Changing it now won't affect where it ends up going.
I've been thinking if it is possible to handle Multipart request that is not an Action request. There is a reason why it seems impossible to me :
Only ActionRequest implements
getFile() kind of methods. I can't
find any easy way how to get the file
out of request other than Action
request
What if I don't use a html form to upload a file and I don't want a view to be rendered after action request - render phase happens always after the action phase.
What if I want to create a post request (with file(s)) by ajax and use #ResourceMapping handler. How do I get it out of ResourceRequest ?
Thank you very much for your thoughts.
This is the "pattern" that is afaik the best way of handling Multipart requests
Action request from view layer goes to this method:
#ActionMapping(params = "javax.portlet.action=sample")
public void response(MultipartActionRequest request, ActionResponse response) {
response.setRenderParameter("javax.portlet.action", "success");
List<MultipartFile> fileList = request.getFiles("file");
}
render phase follows :
#RequestMapping(params = "javax.portlet.action=success")
public ModelAndView process(RenderRequest request, Model model) throws IOException {
Map map = new HashMap();
map.put("test", new Integer(1));
return new ModelAndView("someView", map);
}
You create a "bean" view :
#Component("someView")
public class SomeView extends AbstractView {
private Logger logger = Logger.getLogger(SomeView.class);
#Override
protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("Resolving ajax request view - " + map);
JSONObject jsonObj = new JSONObject(map);
logger.info("content Type = " + getContentType());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonObj.toString());
response.getWriter().flush();
}
}
You add BeanNameViewResolver into your servlet/portlet context:
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="1" />