How to integrate JSF with custom servlets? - java

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.

Related

What is the purpose of having multiple spring "application context"

Per the Spring Documentation, application context is:
Central interface to provide configuration for an application. This is read-only while the application is running, but maybe reloaded if the implementation supports this.
In some applications, there are multiple application contexts. What's the purpose and benefit of having multiple application contexts? I want to understand the logic behind it. Why would one do it?
P.S: In spring doc use is written. I want to know the pros of having multiple application contexts and the rationale behind it.
The root context is the parent of every dispatcher servlet context/child context. Beans defined in root context are visible to each dispatcher servlet context/child context but not vice-versa.
Typically, root context is used to define all cross-cutting beans such as security, transactions, and other configurational beans, while the dispatcher context or child context contains those beans that are specifically related to MVC.
We create multiple dispatcher servlets when we need multiple sets of MVC configuration. For e.g. we may have a REST API alongside a traditional MVC application or an unsecured and a secure section of a website.
Cannot comment so putting the answer:-
Java Spring multiple ApplicationContext
Hope this answer your question
It is useful to implement a layered architecture (model objects, data access, services, web services, mvc app etc).
As M.Deinum said it is good to have one root context that loads the others and helps keeping them separated.
Here is the official doc for the architecture of Spring Framework applications: https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/overview.html

What is FrontController design pattern? How much level is DispatcherServlet using it?

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

How to make legacy HttpServlet Spring web aware

We have a legacy HttpServlet class that is the backbone of our application. At this point, the app doesn't have any Spring libraries in it. We are looking to introduce Spring, in particular so we can use Spring-Data in conjunction with Hibernate.
I was wondering if there is a way to make this legacy Servlet web-aware so we can have Request and Session scopes injected. In particular, we would like to be able to inject the HttpServletRequest object into some beans.
One of the main reasons we need to do this, is for a weird multi-tenancy solution we have in place. Hibernate can handle Multi-Tenancy using a combination of a AbstractMultiTenantConnectionProvider and a CurrentTenantIdentifierResolver When using Spring-JPA's Repositories, you lose control of the session creation. One way to take care of this is to implement the CurrentTenantIdentifierResolver Since our tenant identifier is partially determined by something that comes in on the request, it is necessary to inject the request into our CurrentTenantIdentifierResolver implementation.
Also, it would be great to get Spring involved for all the other benefits it can provide in a legacy app.
Do you know how we can accomplish this?
You can define org.springframework.web.context.ContextLoaderListener within your web.xml, which will load your spring application context.
Then, within your servlet code, you access the context using WebApplicationContextUtils.getWebApplicationContext(servletContext) helper method.
Take a look at the Spring docs here:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#web-integration-common

Single servlet for application

Is it possible to have an application such as shopping cart, to have a single servlet in the entire application, which will result into a single entry in web.xml? If yes, how?
Sure. There are in fact several webapp frameworks (e.g. Struts and JSF) based on a single servlet that dispatches incoming requests to application-specific controller classes after mapping URL components to controllers and parameters.

Spring 2.5 managed servlets: howto?

Correct me if anything is wrong.
As I understand, all Spring functionality, namely DI works when beans are got thru
Spring Context, ie getBean() method.
Otherwise, none can work, even if my method is marked #Transactional and I will
create the owning class with a new operator, no transaction management will be provided.
I use Tomcat 6 as a servlet container.
So, my question is: how to make Servlet methods managed by Spring framework.
The issue here is that I use a framework, and its servlets extend the functionality of
basic java Servlets, so they have more methods. Still, web.xml is present in an app as usual.
The thing is that I do not control the servlets creation flow, I can only override a few methods
of each servlet, the flow is basically written down in some xml file, but I control this process
using a graphical gui.
So, basically, I only add some code to a few methods of each Servlet.
How to make those methods managed by Spring framework? The basic thing I need to do is
making these methods transactional (#Transactional).
comment to Bozho:
#Bozho Let's see. In these servlets' methods I work with framework capabilities, let's say special variables that are got and saved in the current session. And what is needed, is looping through those framework-based collections while saving some values in a database. What you suggest is introducing a new very complex object, so that it could be passed to a service layer. (Service layer will not know anything about framework, its classes and objects kept in current Session! First, we "wrap" framework based collections to such a object, so copy everything into it. Then, again, the Service layer method should either save changes in a database or, worse case, return a new complex object so that Servlet framework method could update framework variables depending on the result of Service layer method execution. It is a workaround but do you think it is a good idea?
You can also define your servlets directly in the Spring application context. You'll need a "proxy" servlet registered in web.xml and delegating to the servlet instance which is configured as bean in the applicationContext.xml. Proxy servlet is configured with the name of the target servlet bean, it discovers this bean via WebApplicationContextUtils.getRequiredWebApplicationContext().getBean(...) and delegates all the processing to the target servlet. In this case an instance of your servlet is completely managed by Spring.
I'd suggest restructuring your code - making servlet methods transactional is not a good thing to do. Put the transactional logic in a separate, service class, and either
obtain these spring-managed classes by WebApplicationContextUtils.getRequiredWebApplicationContext().getBean(..) or
in your servlet init() method obtain the ApplicationContext with the above method and call appCtx.getAutowireCapableBeanFactory().autowireBean(this). This way you can inject the transactional classes in your servlet as if it was spring-managed.
Now, you can do all this, but it is definitely not a beautiful way to go. I'd suggest using Spring MVC or any other MVC framework (which support spring integration of its components)
If this is all not possible, as a last resort I think you can use #Configurable (on your servlets) with a <context:load-time-weaver/>.
You should take a look how Spring proxy filters:
http://grepcode.com/file/repository.springsource.com/org.springframework/org.springframework.web/3.0.2/org/springframework/web/filter/DelegatingFilterProxy.java
In theory you could easily make the same sort of proxy for servlets and DispatcherServlet is sort of a proxy.

Categories

Resources