Loading spring context in web application after some servlet - spring

We need to load the spring application context in our web application after one of our servlets is initialized, so I wonder what is the best way to do it?
I know that it's recommended to use the listener in web.xml, but it's obviously not good for us because in this case the context will be loaded before the first servlet. I saw that there was this class - ContextLoaderServet - in Spring 2.5, but it's absent in Spring 3.0. So I guess we should write some dummy servlet ourselves with the sole purpose of loading the context? Is there any better way?
Thanks.

OK, so if you have this legacy servlet that sets stuff up, then you will need to persuade the Spring servlet to load after it.
This is straightforward - use Spring's DispatcherServlet to load the Spring context, and use the standard <load-on-startup> in web.xml to dictate the startup order, e.g.
<servlet>
<servlet-name>LegacyServlet</servlet-name>
<servlet-class>com.xy.LegacyServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Related

Is the load-on-startup tag in web.xml mandatory?

Is the load-on-startup tag a mandatory tag in web.xml to load dispatcher servlet in spring? Will our dispatcher servlet get initialized if it doesn't mention this tag?
yes it's required, if you expect to dispatch or render anything using spring.
No, it is not mandatory. If you do not specify "load-on-startup" tag, your project will still work fine, except for the fact that the servlet will take slightly more time to load for the first request. This tag is helpful if you have multiple servlets and you want to control the loading flow. If you have multiple servlets, then the servlet which has the least "load-on-startup" value will be loaded first.
In the below example, servlet1 will be loaded first, then servlet2 will be loaded, and so on.
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>X</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>Y</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Spring MVC DispatcherServlet mapping / vs /*

<servlet>
<servlet-name>springmvcdemo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvcdemo</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
vs
<servlet>
<servlet-name>springmvcdemo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvcdemo</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I know there are duplicated questions but i'm still confused. My understanding is that when using /* , every request will go through this servlet (It means all .jsp, .html,etc will end up in this ). / will make this servlet the default servlet ( if there are exact URL installed..., return ) But it seem to me that when using / every request all still go through The DispatcherServlet no matter what. I can't open any .jsp file directly. Can someone explain to me more about this?
As per the Servlet specification, mapping for "/" means default servlet meaning if there is no explicit servlet matching the request, then this default servlet would be serving the request. For e.g., there is a servlet named "default" defined in Tomcat server common configuration web.xml which is inherited by all applications. This servlet serves the static contents like css,images etc which are typically not mapped in applications web.xml. Similarly there is a special Servlet which handles requests for jsp files ( all request ending with *.jsp as naturally these will be needed to be compiled to Servlets which would then process the request). So if you override the default servlet to be any other servlet in the application web.xml, then all requests not handled by any other servlet goes to this servlet and if this Servlet is not capable to serving request, it will not work.
If you declare Spring dispatcher servlet as the default Servlet, then you will not be able to serve static contents from container provided Servlet. Instead there is a special handler provided which can load static resources from configurable path pattern from directory / classpath. You need to use <mvc:resources/> tag for this feature. However if you still want to use container provided Servlet for serving resource you would need to use
<mvc:default-servlet-handler/> in the spring configuration. You can read more about this approach and its prons/cons here - section 15.12.4

About multiple containers in spring framework

In a typical Spring MVC project there two "containers": One created by ContextLoaderListener and the other created by DispatchServlet.
I want to know, are these really two IoC container instance?( I see two bean config files, one is root-context.xml the other is servlet-context.xml)
If there are 2 containers, then what's the relationship?
Can the beans declared in one container be used in the other?
From the Spring Official Website:
The interface org.springframework.context.ApplicationContext
represents the Spring IoC container and is responsible for
instantiating, configuring, and assembling the aforementioned beans.
The container gets its instructions on what objects to instantiate,
configure, and assemble by reading configuration metadata. The
configuration metadata is represented in XML, Java annotations, or
Java code.
Again from official Doc:
In the Web MVC framework, each DispatcherServlet has its own
WebApplicationContext, which inherits all the beans already defined in
the root WebApplicationContext. These inherited beans can be
overridden in the servlet-specific scope, and you can define new
scope-specific beans local to a given Servlet instance.
Now coming to your Question, as is stated here:
In Spring Web Applications, there are two types of container, each of
which is configured and initialized differently. One is the
“Application Context” and the other is the “Web Application Context”.
Lets first talk about the “Application Context”. Application Context
is the container initialized by a ContextLoaderListener or
ContextLoaderServlet defined in the web.xml and the configuration
would look something like this:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:*-context.xml</param-value>
</context-param>
In the above configuration, I am asking spring to load all files from
the classpath that match *-context.xml and create an Application
Context from it. This context might, for instance, contain components
such as middle-tier transactional services, data access objects, or
other objects that you might want to use (and re-use) across the
application. There will be one application context per application.
The other context is the “WebApplicationContext” which is the child
context of the application context. Each DispatcherServlet defined in
a Spring web application will have an associated
WebApplicationContext. The initialization of the WebApplicationContext
happens like this:
<servlet>
<servlet-name>platform-services</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:platform-services-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
You provide the name of the spring configuration file as a servlet
initialization parameter. What is important to remember here is that
the name of the XML must be of the form -servlet. xml.
In this example, the name of the servlet is platform-services
therefore the name of our XML must be platform-service-servlet.xml.
Whatever beans are available in the ApplicationContext can be referred
to from each WebApplicationContext. It is a best practice to keep a
clear separation between middle-tier services such as business logic
components and data access classes (that are typically defined in the
ApplicationContext) and web- related components such as controllers
and view resolvers (that are defined in the WebApplicationContext per
Dispatcher Servlet).
Check these links
Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-basics
There aren't two separate containers created. Typically, you want spring to instantiate the object declared in the servlet-context.xml when the object is required. So, you map the servlet-context.xml configuration file to the Dispatcher Servlet i.e. you want to initialize the object when a request hits the dispatcher servlet.
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Where as, if you want to initialize the object and perform action when the context is being loaded you would declare the configuration file with in the context-param tags of your deployment descriptor.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
You could test this out by writing by declaring separate beans in the servlet-context.xml and root-context.xml and then, autowiring them in a custom Context Loader Listener class. You would find only the root-context instances are initialized and servlet-context beans are null.
ApplicationContext a registry of components (beans).
ApplicationContext defines the beans that are shared among all the servlets i.e. root context configuration for every web application.
spring*-servlet.xml defines the beans that are related WebApplicationContexts here DispatcherServlet.
Spring container can have either single or multiple WebApplicationContexts.
Spring MVC have atleast 2 container -
Application Context declared by
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
Servlet context declared by -
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
And a web application can define any number of DispatcherServlet's. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener, if any, will be shared. Thus can have any number of child containers.

How do you share Spring beans between different Spring contexts?

We have an application which uses Spring BlazeDS integration. So far we have just been using Spring and Flex, and it is working fine. We now have a requirement to add some Spring MVC controllers as well. The Spring BlazeDS documentation states that the way to do this is to declare two sperate contexts in the web.xml, as follows:
<servlet>
<servlet-name>flex</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>flex</servlet-name>
<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
Here is my question: There are Spring beans which are required to be used within both contexts - the spring-mvc one and the flex one. How can one do this - how can one declare a bean (either in xml or by component scanning) in one context and allow it to be shared with beans declared in the other context?
Thanks !
Create a parent context by using ContextLoaderListener. The DispatcherServlet contexts will automatically become children of that context.
Create your shared beans in the parent context and refer to them in beans in the child contexts.
If you are using <component-scan> make sure you don't accidentally scan classes into multiple contexts. See my answer here.
Add this to your web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/YOUR_APP_CONTEXT.xml</param-value>
</context-param>
Both beans defined via scanning and direct definitions will be available for your BlazeDS and SpringMVC endpoints.

Can someone explain the Spring web.xml file?

I'm new to Java Enterprise and to Spring but I have a strong grasp of standard Java. I am looking through an existing web application project. The project uses Tomcat/Spring/Hibernate which I understand is fairly common. It also uses DWR for remote method invocations. I'm finding it somewhat difficult to separate responsibilities: what Tomcat is responsible for, what Spring is responsible for, how a request gets from one to the other, and how the major pieces of Spring fit together. I've read a great deal of documentation on Spring, particularly about beans and bean factory and am still in process of reading more. Any advice you guys have would be welcome, but I'll provide some specific questions.
Question 1: Where does the web.xml fit into things (when is it used/called, and where is it called from)?
Code sample 1:
<servlet>
<servlet-name>qrst</servlet-name>
<display-name>qrst Servlet</display-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
What does the above snippet do (or, what does it cause to happen)? At some point in my web app qrst.jsp gets used; is it the DispatcherServlet that calls qrst.jsp using the servlet name? Else what is the significance of the servlet name? What is load on startup?
Code sample 2:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/someLocation/some-servlet.xml
</param-value>
</context-param>
Links or explanation of what the above does? I can see from looking at the XML file that it contains bean definitions and I do understand what beans are and how they are used, but I don't know any other details about this and would like to.
Code sample 3:
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR</display-name>
<servlet-class>
org.directwebremoting.servlet.DwrServlet
</servlet-class>
<init-param>
<param-name>classes</param-name>
<param-value>
somepackage.someclass
</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
From what I read about beans, I believe those init-param elements are just parameters that get set in the servlet's java class. What's the significance of the servlet name, and what about the load on startup? The web app somehow "knows" when an AJAX (dwr) call is happening versus when the web app is being loaded for the first time (when its loading for the first time it should use qrst.jsp). How does it know this? How does it decide to route the request to DWR instead of to qrst.jsp? Where does it do this?
Thanks.
Servlets are JavaEE's idiom for answering HTTP requests. You program the behavior of your application in a Servlet which will respond to a request.
Tomcat is a Servlet container, which means you deploy your application in Tomcat and it will manage all the communication infrastructure for you: it accepts connections, manages database connections(*) and will call upon your servlets to handle incoming requests.
web.xml is part of any JavaEE application, not Spring. Your code sample 1 declares that your app will use an instance of class org.springframework.web.servlet.DispatcherServlet to handle incoming requests.
Although servlets are the basic foundations for JavaEE development, it is not advised to create your own; instead, with Spring, you create MVC controllers. Then the DispatcherServlet will call upon these controllers to handle the requests. It's just another indirection (but a very powerful one!)
is it the DispatcherServlet that calls qrst.jsp using the servlet name?
Not directly. It's just a coincidence that your servlet and the JSP file have the same name.
What is loaded on startup?
Your code sample 2 instructs the DispatcherServlet to load the beans from file /someLocation/some-servlet.xml. If there are controller beans in this file and according to how you configured the url mapping, beans from this file will answer the incoming requests. See the reference.
I believe those init-param elements are just parameters that get set in the servlet's java class
The init-param elements in web.xml are for the servlet class.
The web app somehow "knows" when an AJAX (dwr) call is happening versus when the web app is being loaded for the first time (when its loading for the first time it should use qrst.jsp). How does it know this?
Missing from the question are either the <servlet-mapping> element (found in web.xml), or the url mappings (found in the spring files). These are responsible for deciding whether an URL should be handled by the dispatcher servlet or the dwr servlet.
For instance, with an servlet mapping like below:
<servlet-mapping>
<servlet-name>qsrt</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dwr</servlet-name>
<url-pattern>*.dwr</url-pattern>
</servlet-mapping>
Then all URLs ending in .do will be answered by the dispatcher servlet, and those ending with .dwr will be handled by the dwr servlet. Here's where the names of the servlets are important.
JSP files are a different story. The container will simply use them to handle a URL ending in *.jsp. Do not create your onw servlet mapping for URLs ending in *.jsp. This will only cause headaches. This is probably unspecified behavior.
Edit:
However, the URL in the browser's address bar always looks the same: it would always invoke the qrst servlet
Then it is possible that your servlet-mapping is so broad (something like: <url-pattern>/*</url-pattern>) that it will handle anything you throw at the server and never give a chance for the other servlets to handle it.
Last but not least, when working with DWR or any Ajax technology, install the HttpFox extension for Firefox so you can monitor the Ajax calls of your application.

Resources