Spring mvc interceptor Basics - spring

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.

Related

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

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.

springmvc with rest - delegating request to different versions of rest controllers

I am designing a REST controller layer with the concept of different versioning which might happen in the future.
I am thinking of having separate classes with version number as follows.
#RequestMapping("/v1/api")
#RestController
class V1RestController {
}
#RequestMapping("/v2/api")
#RestController
class V2RestController {
}
Or V2RestController might extend V1RestController depending on the requirements. This is just a draft idea. But my question is if there is any Spring MVC api which can catch the URL and look up the version '/v1/api or /v2/api' and delegate the request to the right controller.
Based on my research, the best way is to make it backward-compatible, but i am sure that the reality is different and there would be some cases to have different implementations.
I know that there are other ways to design the rest controller layer for different versioning, but for now, i would like to take this approach.
Any help would be appreciated.
But my question is if there is any Spring MVC api which can catch the URL and look up the version '/v1/api or /v2/api' and delegate the request to the right controller.
DispatcherServlet intercepts the request (what to intercept it looks in "web.xml" ), and then DispatcherServlet looks at the request URL and looks for the controller whose "value" parameter (the "#RequestMapping" annotation) matches the request URL, if a match is found: control is transferred in the corresponding controller. Something like this.

For validating session attribute, which is better in spring - Interceptor or Spring AOP?

In my application, after a user is logged in, every time he sends a request (get/post), before calling the method in controller, i want to verify the session attribute set in the request (i set a session attribute during his login). I see that this can be implemented through spring interceptors (OR) spring AOP. which one should i use?. I have a feeling interceptors are outdated. Or is there a way in spring security which does this for me?
So you want this intercept to happen only for all the controller methods ..? Does the controller have Base URL that its getting invoked for (post/get/delete)...? Is it more like you want to intercept the http request for a particualt URL ..? like this one
<intercept-url pattern="/styles/**" filters=" .." />
If your use case is boiled down to a particular URL pattern then you can write a custom filter extending GenericFilterBean and you can plug it to the filters attribute.So this will get called for every request matching url pattern and in your custom filter you can do whatever you wanted to do.
What if you try implementing a simple Filter? You can extend already existing Spring filter, or create your own by implementing javax.servlet.Filter
The spring security way seems the best way to me with access to specific roles also can be assigned. very good example given in http://www.mkyong.com/spring-security/spring-security-form-login-using-database/

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.

Filters vs Interceptors in Struts 2

What's the difference, really, between filters and interceptors? I realize that interceptors fire before and after an action, recursively, and filters can be configured to fire on actions and on certain url patterns. But how do you know when to use each one?
In the book I'm reading on Struts 2, it seems that interceptors are being pushed and I even followed a tutorial to write an Authentication Interceptor to make sure a user is logged in. However, if the user tries to access a URL that doesn't have an action associated with it, the interceptor doesn't catch it, which means I'd have to associate an action with every jsp that I want to be secure. That doesn't seem right.
I can make an Authentication Filter that handles URLs so that I don't have to do that, but then, what's the point of interceptors?
The most significant difference is that "interceptors" are a part of the Struts 2 framework, and are only part of the request handling that is done by the Struts 2 framework. "Filters" on the other hand are a part of the Servlet Specifcation; in other words, they are part of the Servlet API. If you are using Struts 2, you should use interceptors for wrapping functionality around your Struts 2 actions. If you are trying to wrap functionality around requests coming to your webapp, but not being handled by Struts 2, then a filter might be more appropriate.
BTW, the entire Struts 2 Framework is deployed inside a filter configured in your web app, declared in your webapp's deployment descriptor ( web.xml ) like:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
This filter, which is configured to catch all requests URL patterns, is the entry point into the entire Struts 2 framework.
I hope that helps.
the interceptor stack fires on every request.
filters only apply to the urls for which they are defined.
edit -- you use one or the other depending on need. Lets say you need to verify a cookie is present for every request. User an interceptor. Lets say that you need to pop up an external app on some requests (driven by a url), use a filter.
I think interceptors are the more commonly used tool...
why would you have a url with no associated action?
What is Interceptor ?
The Struts 2 Framework uses the concept of Interceptors to share the solution for some common concerns by different actions.
As we know the framework invokes a particular Action object on the submssion of a request for it. But before executing of Action, the invocation is intercepted by some other object to provide additional processing required.
Similarly after the execution of Action, the invocation can be intercepted again. This intercepting object is known as Interceptor.
So the purpose of using Interceptor is to allow greater control over controller layer and separate some common logic that applies to multiple actions.
Struts 2 framework has already provided its own set of Interceptors which can be used in the application to provide required processing before and after the Action classs execution.
One of those is "Alias Interceptor" that I am going to discuss here.
Alias Interceptor:
Alias Interceptor is used in case of Action chaining. Action chaining means one Action calls other Action after successful execution of first action.
This interceptor aliases a named parameter to a different parameter name. In action chaining, when two different action classes share a common parameter with a different name, this Interceptor is used to give an alias name to a parmeter of first action class, which matches the parameter name in the second action class.
The alias expression of action should be in the form of :
#{ 'name1' : 'alias1' , 'name2' : 'alias2' }
As per the struts 2 life cycle/architecture no interceptors are executed before filter. So if there is no action mapping for your request then it's failing in while passing through filter.
As a rule of thumb
Filters are run before each request. The struts itself is a filter.
interceptors can run before, after struts actions. They will not run if the request does not end with .action.
So, some example of filters could be:
If you want to compress your js and css files, you should go for filters not interceptors.
If you want only certain IP address access your web site you must develop it as filter and check request ip address.
If you want to safe your site against CSRF attack you must write a filter to check CSRF token on requests.
If you want to log your site response per request time, you can use a filter to calculate the time before and after chain.doFilter(request, response)
Theoretically you can develop an struts web application without developing your own interceptors and using filtersonly. But you will face lots problem and code boiler filters.
Lots of struts 2 features are build with interceptors, you can find it in struts-default.xml (https://struts.apache.org/docs/struts-defaultxml.html) the list will help to find when interceptors can be used. (For example ParametersInterceptor runs before actions to apply submited form values to actions)
While working with interceptors you can easily access struts features, for example getText from message resources, get current action name and name space, change the action flow.
Considering above here are some cases which can be developed by interceptors:
If you want that only logged in users can access certain actions, you must develop it with interceptors.
If you want to keep track which actions user is navigation. You can use an interceptor to keep track of visited actions.
If you want to handle your action errors in a single point, you can use an interceptor which catch all invocation.invoke()
The interceptors are providing the filter and Chain of Responsibility design pattern for struts actions, while filters provide this pattern to your whole web application.
Struts 2 Framework is not dependent on Servlet API.
Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation.
Filter is a part of Servlet API so Struts 2 Framework uses the concept of Interceptors to share the solution for some common concerns by different actions.
Also you can easily write test cases for Interceptor and Action class.

Resources