Can anyone tell me, what is exact meaning of INTERCEPTOR in Struts 2 Framework?
Could you please give me some simple example with Struts interceptor?
Thanks IN Advance!
Think of what the Interceptors is to Struts as Filters is to Servlets. When you request a Struts Action, The Struts Framework sends a request to the called action, but before the action is executed, the invocation can be interpreted by interceptors. Once the're done, the request is passed (as servlet calls it, filtered) to the action.
The reason for interceptors is, you want to do some pre-conditional / post-conditional checking to be sent to the action / returned by the action. A simple example will be File upload. When you send a file to an action in Struts, you can have an interceptor that is used as a pre-condition validator (e.g, the file size must be 5210 bytes exactly = 5MB). If successful, it filters the request to the action (that was called).
I've never used Struts 2 but there's a Wiki on Interceptors at Apache site.
Well Why Interceptors or whats there relevancy in Struts2..These are a part of moduler approach where you have some predefined modules as per the need and you can plug them or unplug them as per your need.
Struts2 is a web frame work and in order to process the request it has to undergo certain steps which are common for every request process cycle so Struts2 develoers have created these module which are indentiifed as common module which every request in web application needs
like when you submit the data we need to conver the data to appropriate form this is struts is being done by the Interceptors if some validation is needed how to do it is being done by interceptors they are somethig which are like modules or plugin plug which ever you want to use and unplug them which you don't do..
in shorter terem these Interceptors is doing all necessary work for you so that you can concentrate on ur business logic
Related
Actually I am trying to understand the DispatcherServlet and came to know that it is following the FrontController Design Pattern.
While trying to understand the FrontController design pattern came across this link
FrontController from Oracle Doc reference
Not much understood as I am beginner, but few things I understood Like Below
If we don't have FrontController we often try to duplicate the code in multiple controller like authentication and Authorization. And because of which maintainability becomes a big issue if we want to change something in future. So having frontController in place we can move the basic functionality to frontController and changes can be done easily.
When I explained Same thing in the interview he asked me what are those basic functionalities. I told Internalization, viewResolver, Authentication, Authorization etc. And now again asked consider like there is no dispatcher Servlet how do you handle those functionalities in each controller?
Since am basically a Desktop Application developer I couldn't answer for his next question.
So here are my questions
Firstly, is my understanding correct?
If my understand is correct, how to answer for the second question of the Interviewer? Which is consider like if there is no dispatcher Servlet how do you handle those functionalities in each controller? means asked me to write some pseudo code of the common functionalities. Which I couldn't as I am swing developer. Could someone please explain me, with some sample code which we repeat across the controller and now with dispatcher we could avoid.
If we Start comparing DispatcherServlet with frontController Design Pattern can we say like LocaleResolver, HandlerMapping, ThemeResolver, ViewResolver, HandlerExceptionResolver, HandlerAdapter, MultipartResolver etc. are Helper classes for DispatcherServlet?
The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request. The front controller may use other helpers to achieve the dispatching mechanism.
Front Controller design pattern could be implemented by either of following two ways.
Using Servlet
Using Filter
Spring Framework implemented FrontController Design Patter using DispatcherServlet for intercepting each request and delegate to responsible controller to process the request.
If interviewer asks you, what happened if you don't have DispatcherServlet then how you manage all these authentication and authorization things, you can simply say that I can define a Filter which will intercept each request. Filter should be responsible for dispatching,authentication and authorization thing. Struts uses Filter to implement FrontController Design pattern.
(1) FrontController is simply the central place where all the external requests are received by and pass each of those requests to the appropriate handler. As you have explained since this is the central place for all the requests, it can be used to perform all the common things like security, logging etc.
(2) DispatcherServlet is the actually the front controller of Spring MVC. It intercepts each request and then dispatches each to the appropriate controller which has been registered in Spring Application Context.
consider like if there is no dispatcher Servlet how do you handle
those functionalities in each controller ?
For this one, I don't think this question implies that you need to write same code in each controller. (If it does, it cannot be a good idea)
You can do something like implementing a separate service which would do those common things (cross cutting concerns) for you can orchestrate all in coming requests.
Front Controller Definition
The front controller is responsible for handling all the requests for
a website. For web application developers, it can be a very useful
structure, as it allows the developers the flexibility and the ability
to reuse the code without having to add again and again.It provides a single point of action to handle the all coming requests to the J2EE web application, it forwards the request to specific application controller to access model and view for presentation
tier resources.
lets check the functionality of the Dispatcher Servlet to see if it is exactly the front end:
Consider the diagram below taken from https://docs.spring.io/spring/docs/3.0.0.M4/reference/html/ch15s02.html:
As you can see in the preceding diagram, the front controller is introduced for the
MVC pattern. It is implemented as a javax.servlet.Servlet servlet such as ActionServlet in struts, FacesServlet in JSF, and DispatcherServlet in Spring MVC. It handles the incoming requests, and delegates the requests to the
specific application controller. That application controller creates and updates the model, and delegates it to the front controller for rendering. Finally, the Front Controller determines the specific view, and renders that model data.
Now Consider the step as:
A user clicks on the browser or submits a web form of the application. The
request leaves the browser, either with some additional information or with
common information. This request lands at Spring's DispatcherServlet, which is a
simple servlet class as other java-based web applications. It is a Front
Controller of the Spring MVC framework, and funnels all the incoming requests
through the single point. The Spring MVC framework centralizes the request
flow control by using this Front Controller.
A user clicks on the browser or submits a web form of the application. The
request leaves the browser, either with some additional information or with
common information. This request lands at Spring's DispatcherServlet, which is a
simple servlet class as other java-based web applications. It is a Front
Controller of the Spring MVC framework, and funnels all the incoming requests
through the single point. The Spring MVC framework centralizes the request
flow control by using this Front Controller.
Once a particular application controller is decided by Spring's DispatcherServlet
with the help of the handler mapping configuration, DispatcherServlet dispatches
that request to the selected controller. This is the actual controller responsiblefor processing information according to the user's request and its parameters.
Once a particular application controller is decided by Spring's DispatcherServlet
with the help of the handler mapping configuration, DispatcherServlet dispatches
that request to the selected controller. This is the actual controller responsiblefor processing information according to the user's request and its parameters.
Once a particular application controller is decided by Spring's DispatcherServlet
with the help of the handler mapping configuration, DispatcherServlet dispatches
that request to the selected controller. This is the actual controller responsiblefor processing information according to the user's request and its parameters.
Spring MVC's DispatcherServlet renders the model to the view, and generates a
user-readable format of the model's information
Finally, that information creates a response, and returns it to the user's browser
by DispatcherServlet.
So The Spring MVC module provides out-of-the-box front controller pattern implementation by introducing the org.springframework.web.servlet.DispatcherServlet class. This is a simple servlet class, and the backbone of the Spring MVC framework. And this Servlet is integrated with the Spring IoC container to benefit the Spring's dependency pattern. Spring's web framework uses Spring for its own configuration, and all controllers are Spring beans. you can see the spring doc https://docs.spring.io/spring/docs/3.0.0.M4/reference/html/ch15s02.html that admitted the usage of front controller design pattern in DispatcherServlet
Answers specifically to your questions:
yes your understanding is okay but for a better view refer to my description
when there is no DispatcherServlet you need to define something to take care of the functionality you need and the best thing is to write a filter including your logic of authentication and authorization
These are not refer as Helper classes as it has it's own definition in OOP, you can consider them components playing part in front controller design pattern implemented version of Spring
More Info:
Majority of the definition comes from the book Spring 5 Design Patterns by Dinesh Rajput, you can refer this book for more info
At present I have a Spring MVC web application, which uses ServletFilter to filter each HTTP request and check whether the user has really purchased the licence by checking and validating the licence file content.
I have mapped the filter in both spring xml file as well as web.xml appropriately. As I have access to HttpServletRequest and HttpServletResponse in the filter, I am able to redirect the user to error page if the validation fails.
So, now as the title suggests is it possible to do the same thing using Spring AOP? How can Spring AOP be configured to get access to the request and response objects created by the container to redirect the user?
How can Spring AOP be configured to get access to the request and
response objects created by the container to redirect the user?
You won't be able to get the same exact behavior as servlet Filters. A Filter operates around the target Servlet by passing in the ServletRequest and ServletResponse objects. In that sense, you can get similar behavior since AOP advice can operate around the joinpoint and intercept arguments that get passed around.
However, the AOP advice can't magically have access to the request and response. It either needs to advise a method that receives them or get them from some ThreadLocal or other container. For example, Spring has RequestContextHolder which you can use to get the HttpServletRequest. But it doesn't have anything to give you the HttpServletResponse (not technically true, but it's not reliable). You could write something similar that does.
Once the advice has access to the objects, it can simply invoke HttpServletResponse#sendRedirect(..) or forward() or whatever.
The best way to implement this would be using exceptions. That way the check and the handling can be different in different situation, e.g. web application vs. normal application.
Your check could be added to particular joinpoints using aop. In case it finds something amiss, it would throw a InvalidLicenseException (extends RuntimeException). Now there are several ways in which you can redirect a request to an error page when an exception is thrown. You could add this to your web.xml :
<error-page><exception-type>InvalidLicenseException</exception-type><location>/license-error.jsp</location></error-page>
Since you're using spring, you could also use annotations. Read this
You can do it out with AOP Advises,
Advice: Advices are actions taken for a particular join point. In
terms of programming, they are methods that gets executed when a
certain join point with matching pointcut is reached in the
application. You can think of Advices as Struts2 interceptors or
Servlet Filters.
So you can configure an advice to take care of validation . you can also configure them to execute at a particular point (i.e) where it needs to be executed .
But remember scope of AOP remains only for method invocation and it doesn't provide response as servlet filters does.
Learn More ..
Simple example here to start with.
I have to execute a struts2 action on server startup rather than on the first request.
Loading data on startup of an application is a common task, you will find several examples on the web. As said in other answers, you should implement a ServletContextListener (that is not Struts2 specific)... you can read a great example here.
The important thing here is understanding the Action concept:
In Struts2 MVC (Model View Controller) Framework, an Action is the Controller (and part of the Model).
Actions are invoked by Requests coming from the Clients (and one Action is created on every request, so they're thread-safe).
This means that you need a Client, that usually means a guy in front of a pc, clicking on a browser... then, a client call is not the right trigger to perform automated, server-side operation on shared objects.
Of course you could implement some form of lazy-initialitazion (eg. with the help of a custom Interceptor) so that the first user would set-up something in the Application scope, and the other users would retrieve the object already populated, but this is not the best way to do it (you should handle the concurrency on the initialitaion, and you would have one user, the first, waiting for operations that the server could have done in the night on startup...).
Write a ServletContextListener, this will be available only one per web application and will get instatiated when the application is deployed.
Here is the post
If you want to some code to run when your web application, aka Servlet Context, starts for the first time, then you should leverage the hooks provided by the technology. The Servlet API provides lifecycle hooks for you to use to fire code at various lifecycle stages of a web application. Since all Struts 2 applications are Servlet API web applications, then you can leverage this yourself.
The ServletContextListener interface provides an init hook method. You simply implement this interface and register your implementation in the web.xml.
Note, if what you need to do is more Struts 2 specific, then you could consider utilizing something from within the Struts 2 API itself.
Load on start-up in servlet and jsp is present as below
You can ask the page to be loaded when the server starts. This is done via the web.xml file
<servlet>
<servlet-name>login</servlet-name>
<jsp-file>/login.jsp</jsp-file>
<load-on-startup>1</load-on-startup>
</servlet>
Normally jsp file is compiles on first hit.
Now the code says precompile a jsp file without waiting for the first hit.
For struts2 you can change programatically in web.xml
<listener>
<listener-class>your listener class</listener-class>
</listener>
refer this link it might be helpful to you
Loadonstart up.
In the config file, there are lots of elements: flow-executor, flow-registry, flow-builder-services, viewFactoryCreator, FlowHandlerAdapter, FlowHandlerMapping, etc.
In what order do they work?
When a request comes in, the servelet will dispatch it to a handler, then I guess the spring web flow framework will somehow parse the flow and return a view. But how exactly does the spring web flow framework handle the request? And in what order do those elements defined in the config file work?
Here is a nice image of the request lifecycle taken from the link. Also here is an article giving you the life-cycle events.
.
I'm just getting started on JavaServer Faces and it looks very attractive. However I'd like to use my own servlets in the same web application as JSF.
This might be really obvious, but what are the best practices for integrating JSF with a "normal" servlets-based application? This would include accessing JSF data from the servlets (read and write).
If your servlets are well-written, they should already not have any business logic inside, but just pure request/response controlling/preprocessing/postprocessing logic. The business logic should already be placed in standalone javabean-like domain/model classes. The database logic should already be placed in standalone DAO classes. And so on. You can just reuse them all in JSF.
That said, it may be good to know that JSF (when running on top of Servlet API --the common case) manages request scoped beans as attributes of HttpServletRequest, the session scoped beans as attributes of the HttpSession, the application scoped beans as attributes of ServletContext. It may also be good to know that all of those request, session and application attributes are accessible by ExternalContext#getRequestMap(), #getSessionMap() and #getApplicationMap(). You should now realize that you can just access them the usual way from inside a servlet.
In any case, when there is technical need to access the FacesContext inside a Servlet or a Filter, then immediately stop coding it and rethink your approach based on the above facts. Shouldn't it better be done in a new managed bean? Or maybe a PhaseListener?
You don't have to integrate servlets with JSF. This is contrary to the nature of JSF, which is "component based" rather than "action based".
JSF has managed beans whose methods get called when you press a button. You have both the request and response available (using FacesContext.getCurrentContext().getExternalContext()), but they shouldn't really be needed - all the data is automatically populated by JSF in the fields of the managed bean.
If you want servlets that do not integrated with JSF but work in the same application, then you just have to map them to a url that doesn't conflict with the url of the JSF servlet.