Spring MVC: log all requests, even the resource not founds - spring

How can I log all requests in Spring MVC, even the resource not founds ones?
I guess interceptors can not log resource not found requests. What do you suggest?

Have you tried using implementation of javax.servlet.Filter?
Filter in contrary to Spring's interceptor is part of a Java's standard and is executed by the servlet container for each incoming HTTP request..
Spring MVC use exactly one servlet and that is DispatcherServlet which, as the name suggest, disptach received request to correct controller which process the request futher.
Spring even provide few concrete implementations of Filter that can log incoming request for you such as: CommonsRequestLoggingFilter or ServletContextRequestLoggingFilter.
You can choose one of the above implementations or implement Filter interface by yourself - whatever you decide, by using Filter you should be able to log every single request received by your servlet container.

Related

Which one is executed in localhost - DispatcherServlet or OncePerRequestFilter?

I'm hitting an API locally through a Postman.
Which one is executable in localhost - DispatcherServlet class or OncePerRequestFilter class ?
What is the use of DispatcherServlet in Spring MVC ?
The DispatcherServlet is a central servlet that helps in dispatching the request to the controllers. It is integrated with Spring IoC (Inversion of Control) Container (which is responsible for managing the life-cycle of the bean). This also provides various functionality for the development of the web applications. It acts as Front Controller for the web application.
Screenshot of what happens behind scenes in Spring MVC(From Spring Docs) :
What is the use of OncePerRequestFilter ?
It is a class that guarantees the execution of a method based on the request to be allowed, on any servlet container.
Q : Which one is executable in localhost - DispatcherServlet class or OncePerRequestFilter class ?
First the request will be dispatched by the DispatcherServlet. Then, filter will be called because filter acts as wall in between DispatcherServlet and Controllers. If the request meets criteria of the filter, then the request is allowed to hit the particular API. Otherwise, that request is filtered out.
According to the documentation-
org.springframework.web.filter.OncePerRequestFilter "guarantees to be just executed once per request". Under what circumstances a Filter may possibly be executed more than once per request?
And it will be executed for the localhost also. It must be executed whenever any request is generated.

how requests gets handled by dispacther servlet?

Would like to know how many instances of dispatcher servlet is created in a real time environment.
When there are multiple requests coming to the application, and if spring creates singleton objects how does one object handles multiple requests?
What happens when there are so many people accessing the website and since dispatcherServlet object is only one and all requests are handled by same object, won't it create any performance issue?
As M. Deinum says, one servlet to rule them all. I'll try to provide a very general description of the ServletDispatcher life cycle.
When the request leaves the browser it carries with it information from the user. This goes to the DispatcherServlet the front controller which is the single servlet that delegates requests to other components.
DispatcherServlet's job is to send the request to the right controller. Since a application can have many controllers DispatcherServlets get the help to decide which one to send it to by consulting the handler mapping
The DispatcherServlet sends the request to the destination controller,
The controller packs up the model-data and identifies the name of the view that is showing the output and sends this back to the dispatcherservlet.
DispatcherServlet consults with the viewResolver and looks up the view that is set to display the data.
The view is implemented (by a JSP for example) by using the model data to generate output. Which is sent back to the client.
This all happens very fast (ms) which means that thousands of requests can be handled in a very short time.

Using Server Request and Response filters for ThreadLocal storage in a RestEasy based service

I am currently working on a RESTeasy based RESTful service. I have a filter class which serves as a server request filter as well as a server response filter (i.e. it implements ContainerRequestFilter and ContainerResponseFilter interfaces).
At the beginning of the request, I use the filter to put an object into ThreadLocal. This object is used by the resources throughout the request. At the end of the request, before sending out the response, the filter removes the object from ThreadLocal.
My question is that is there a guarantee that the the request filter, the resource and the response filter will all execute in the same thread? Is there a possibility that after the request filter puts the object into ThreadLocal, a different thread will execute the request (and thus not have access to the object)?
I was sure that this was the case but then I saw this http://jersey.576304.n2.nabble.com/Does-filter-method-of-ContainerRequestFilter-run-in-resource-method-thread-td7582648.html (official Jersey forum) and now I have doubts.
javax.ws.rs.container.ContainerRequestContext.setProperty(...)
and
javax.ws.rs.container.ContainerRequestContext.getProperty(...)
are probably the right approach. The javadoc states:
In a Servlet container, the properties are synchronized with the ServletRequest and expose all the attributes available in the ServletRequest. Any modifications of the properties are also reflected in the set of properties of the associated ServletRequest.

Spring mvc interceptor Basics

I am new to Spring and currently working on a spring application.
I am very confused regarding the spring interceptor and Interceptor in Spring security.
I have below doubts.
1. What is the use of Interceptor ? Is it used to modify the requested url or to validate the url ?
2. Is it possible that through interceptor i can modify my url /Test/MyTest to /Test/Intercept/MyTest ?
3. If Interceptor is only used to vaidate the url then only by url-pattern=/"somevalue" it will work or need to implement Interceptorhandler ?
Please help me out to understand these basic functionalities of interceptor.
I went through lot of sites but still not clear about all these concepts.
An interceptor is somewhat like a filter. A filter processes the request and response around a servlet and an interceptor processes the request and optionally the model around a spring controller. Common uses are pre-processing a request to ensure that a condition is realized (preHandle), or populating the model with attributes common to different controller methods (postHandle). afterCompletion is mainly used to perform cleanup at the end of request processing.
Actually interceptor can do three things
preHandle(…) – called just before the action
postHandle(…) – called immediately after the action
afterCompletion(…) – called just before sending response to view
Best example of prehandle is-checking whether the user is logged in or not.
Hope you have got some idea of interceptor
Spring MVC Interceptor is similar to Servlet Fiter Concept. Spring MVC provides ability to define set of classes called interceptor which will be called before and after a request being served. Interceptor will implement HandlerInterceptor which following thee methods need to be implemented:
preHandle() : Called before the handler execution
postHandle() : Called after the handler execution
afterCompletion() : Called after the complete request has finished
There is a good tutorial by MKYONG which I recommend you to have a look at it that I found it helpful in understanding the fundamental concept of interceptor. Hope that helps to get you started.

Spring HandlerInterceptor vs Servlet Filters

HandlerInterceptors in Spring can now be configured to be invoked only on certain URLs using <mvc:interceptors>.
Servlet Filters can achieve same functionality (logging, security etc). So which one should be used?
I think with Interceptors, one can use ModelAndView object to work with Models so it has more advantages. Can anyone draw out scenarios where Filters or Interceptors have advantages over the other?
The org.springframework.web.servlet.HanderInterceptor Interface JavaDoc itself has a two paragraphs that discuss this question:
HandlerInterceptor is basically similar to a Servlet 2.3 Filter, but
in contrast to the latter it just allows custom pre-processing with
the option of prohibiting the execution of the handler itself, and
custom post-processing. Filters are more powerful, for example they
allow for exchanging the request and response objects that are handed
down the chain. Note that a filter gets configured in web.xml, a
HandlerInterceptor in the application context.
As a basic guideline, fine-grained handler-related preprocessing tasks
are candidates for HandlerInterceptor implementations, especially
factored-out common handler code and authorization checks. On the
other hand, a Filter is well-suited for request content and view
content handling, like multipart forms and GZIP compression. This
typically shows when one needs to map the filter to certain content
types (e.g. images), or to all requests.
Spring Handler interceptors allow you to hook into more parts of the request lifecycle, and get access to more information in the process. They're often more intimately coupled to the request/response cycle than filters.
Filters are more suitable when treating your request/response as a black box system. They'll work regardless of how the servlet is implemented.
If you're using Spring MVC, there's little reason to write new logic as a servlet filter. Everything filters can do, interceptors can do more easily and more elegantly.
Remember also, servlet filters have been around for much longer than interceptors.
With a Spring interceptor, you have access to the Handler which may be useful. Also, with a Spring interceptor, you have access to execute logic before the view renders and after the view is rendered.
Servlet Filter:
A filter as the name suggests is a Java class executed by the servlet container for each incoming http request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
This behaviour allow to implement common functionality reused in many different contexts.
As shown in the figure above, the filter runs in the web container so its definition will also be contained in the web.xml file.
The filter include three main methods:
init: Executed to initialize filter using init-param element in
filter definition.
doFilter: Executed for all HTTP incoming request that satisfy
"url-pattern".
destroy: Release resources used by the filter.
Interceptor:
Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sofisticated behaviour because can access to all Spring context.
The Spring interceptor are execute in SpringMVC context so they have be defined in rest-servlet.xml file:
The interceptor include three main methods:
preHandle: Executed before the execution of the target resource.
afterCompletion: Executed after the execution of the target resource
(after rendering the view).
postHandle: Intercept the execution of a handler.

Resources