ServletContextListener not being invoked - servlets

I creating a Java EE 7 project using Eclipse Maven plugin. My problem is when I run the application the class that implements SerlvetContextListener does not get invoked. What is causing this problem?
#WebListener
public class ApplicationContextListener implements ServletContextListener{
#Override
public void contextInitialized(ServletContextEvent sce)
{
Request request = new HttpRequest(sce);
new Thread (request).start();
HibernateUtil.getSessionFactory();
}
#Override
public void contextDestroyed(ServletContextEvent sce)
{
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<listener>com.kyrogaming.AppServletContextListener</listener>
<!-- Jersey Mapping -->
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.kyrogaming.webservices</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
<!-- end Jersey Mapping -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

To summarize JNL's and Ted Goddard's answers:
For a ServletContextListener (or other listeners, such as a ServletContextAttributeListener or a ServletRequestAttributeListener) to be loaded by the servlet container, you need to tell the container about it. As described in the API docs, there are three ways to do this:
Declare it in the deployment descriptor (web.xml):
com.kyrogaming.AppServletContextListener
or annotate its class with #WebListener (see "Note about annotations" below)
or register it programatically, via the methods in ServletContext, such as addListener().
Note about annotations
Method 1) and 3) will always work. For method 2) (annotations) to work, the servlet container must be configured to scan the classes in the classpath, to find the annotated listener classes.
The webapp's own classes (under WEB-INF/classes) and libraries (JARs under WEB-INF/lib) will not be scanned if the web.xml contains the attribute metadata-complete="true" (the attribute defaults to false). See the Java Servlet Specification Version 3.0, chapter 8.1, "Annotations and pluggability".
In a web application, classes using annotations will have their annotations processed only if they are located in the WEB-INF/classes directory, or if they are packaged in a jar file located in WEB-INF/lib within the application. The web application deployment descriptor contains a new “metadata-complete” attribute on the web-app element. The “metadata-complete” attribute defines whether the web descriptor is complete, or whether the class files of the jar file should be examined for annotations and web fragments at deployment time. If “metadata-complete” is set to "true", the deployment tool MUST ignore any servlet annotations present in the class files of the application and web fragments. If the metadata-complete attribute is not specified or is set to "false", the deployment tool must examine the class files of the application for annotations, and scan for web fragments.
So, to allow the container to find annotated classes in JARs, make sure the web.xml sets metadata-complete="false", or does not set it at all.
Note that setting this may delay the application startup; see for example What to do with annotations after setting metadata-complete="true" (which resolved slow Tomcat 7 start-up)? .
Unfortunately, that still does not explain why the ServletContextListener in the question is not loaded. Note that the web.xml in the question does not metadata-complete, meaning it defaults to false, thus classpath scanning is enabled. There is probably some other problem; this checklist hopefully helps in finding it.

Using metadata-complete="false" in web.xml fixed this issue for me.
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="false">

In web.xml you also need to specify the <listener-class>.
<listener>
<listener-class>
com.kyrogaming.AppServletContextListener
</listener-class>
</listener>

For the record, I'm adding yet another possible (and rather vicious) cause of ServletContextListener not being invoked.
This can happen when you have a java.lang.LinkageError, that is when you forgot to add <scope>provided</scope> to your javax.servlet-api dependency.
In such a case the listener instance is created but only the static part is executed, not the contextInitialized and contextDestroyed methods.
You shall discover only when you invoke some servlet, as the linkage error is not raised during listener instantiation.

There is one other extremely rare scenario which can cause this. (which took me 4 hours to uncover)
If you're using Tomcat10 then you can't use javax.servlet library in your maven/gradle.
Tomcat9 still has javax.servlet, but Tomcat10 migrated to jakarta.servlet
Tomcat10 expects to have Listener class that uses jakarta.servlet.ServletContextListener
So use this maven dependency: (scope is provided, because Tomcat10 already has such library)
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>

The running container might need to explicitly allow scanning for annotations:
Ex for jetty:
cd [JETTY_BASE]
java -jar [JETTY_HOME]/start.jar --add-module=annotations

In a Spring-Boot 1.3+ scenario, you need to have the package for the class annotated with #WebListener (and #WebFilter, #WebServlet) fall under the #ServletComponentScan package scope.
Per Baeldung.

Related

Weblogic upgrade to 12c: deployment fails because url mapped to multiple servlet

I've recently setup a new Weblogic 12c environment. On deploying an application that I know works in Weblogic 11g I get the error "The url-pattern /resources/* in web application is mapped to multiple Servlets."
The mapping it's referring to is in the web.xml inside the application.ear that's being deployed, but it's only mapped once:
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
The project doesn't contain any other references to the url pattern /resources/*, can someone explain where the duplicated mapping is coming from and how I can work around it?
The closest issue I could find is this: https://bugster.forgerock.org/jira/si/jira.issueviews:issue-html/OPENAM-7947/OPENAM-7947.html, which has been marked as unreproducible.
Full stack trace from deployment:
<Error> <Deployer> <BEA-149205> <Failed to initialize the application "<application_name>" due to error weblogic.application.ModuleException: weblogic.management.DeploymentException: [HTTP:101401]The url-pa
ttern /resources/* in web application <application_name> is mapped to multiple Servlets.
weblogic.application.ModuleException: weblogic.management.DeploymentException: [HTTP:101401]The url-pattern /resources/* in web application <application_name> is mapped to multiple Servlets.
at weblogic.application.internal.ExtensibleModuleWrapper.prepare(ExtensibleModuleWrapper.java:114)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100)
at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:192)
at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:187)
at weblogic.application.utils.StateMachineDriver$ParallelChange.run(StateMachineDriver.java:83)
at weblogic.application.utils.StateMachineDriver.nextStateInParallel(StateMachineDriver.java:144)
at weblogic.application.internal.flow.ModuleStateDriver.parallelPrepare(ModuleStateDriver.java:46)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:75)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:55)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:731)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:243)
at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:66)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:158)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:65)
at weblogic.deploy.internal.targetserver.AppDeployment.prepare(AppDeployment.java:158)
at weblogic.management.deploy.internal.DeploymentAdapter$1.doPrepare(DeploymentAdapter.java:41)
at weblogic.management.deploy.internal.DeploymentAdapter.prepare(DeploymentAdapter.java:193)
at weblogic.management.deploy.internal.AppTransition$1.transitionApp(AppTransition.java:31)
at weblogic.management.deploy.internal.ConfiguredDeployments$2.doItem(ConfiguredDeployments.java:684)
at weblogic.management.deploy.internal.parallel.BucketInvoker.invoke(BucketInvoker.java:138)
at weblogic.management.deploy.internal.ConfiguredDeployments.transitionAppsParallel(ConfiguredDeployments.java:692)
at weblogic.management.deploy.internal.ConfiguredDeployments.prepare(ConfiguredDeployments.java:322)
at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:202)
at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:207)
at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:129)
at weblogic.server.AbstractServerService.postConstruct(AbstractServerService.java:76)
at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1262)
at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:332)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:374)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:232)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:85)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2020)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1213)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1144)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
If you use web annotations in java code, you don't have to declare the servlet in the web.xml file any more.
You can try by removing the corresponding "servlet" and "servlet-mapping" tags in web.xml
It seems that WebLogic 12.1.3 can deal with double declaration (inline annotation & xml) but not anymore in WebLogic 12.2.
I had this error with #webservice annotation when I specified the "serviceName" parameter and when I declared the servlet in web.xml file with the same value.
The issue doesn't exist in version 12.1.3 (which happened to be the version we were meant to be upgrading to).
Weblogic as of version 12.2.1.3 automatically registers a JAX-RS servlet to the path /resources/* in certain scenarios (e.g. some dependency like jackson-jaxrs-json-provider "requests" it via annotation/spi/moduleinfo). But if this path is already registered by another service the mentioned error is thrown.
There are 3 possible solutions one can try:
In our case the issue was coming from classpath scanning for web services components, and finding annotated services in the webservices-rt jar. That scanning needed to be switched off.
Setting the metadata-complete attribute to true in the web.xml descriptor if your Web application does not have any annotations and if you have the version set to 2.5 or higher to avoid unnecessary scanning of the Web applications classes for annotations. E.g.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>Sample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/sample</url-pattern>
</servlet-mapping>
</web-app>
Alternatively, you can turn off annotation processing and DI for all the Web applications by setting -Dweblogic.servlet.DIDisabled=true flag when starting WebLogic Server.
Registering another path for jersey in the web.xml to e.g. /jersey/*
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/jersey/*</url-pattern>
</servlet-mapping>
Try removing the FATP jars which were added after 12.2 upgrade. This worked for me.

getRequestDispatcher(.).forward(req,res) throws java.io.FileNotFoundException

I have upgraded my Servlet from 2.4 to 3.0 and deployed my application on Websphere 8.5.5.8. Application Server starts properly.
When I try to access my home.jsp page in browser it throws:
Controller Main Error OG1000SRVE0190E: File not found: /servlet/com.platform7.affina.operations.servlet.ValidateLoginUser
When I try to debug, code hits my Main Controller Servlet (which is in same package) but inside Controller servlet class I am calling:
this.getServletContext().getRequestDispatcher("Servlet/com.platform7.affina.operations.servlet.ValidateLoginUser").forward(request, response);
Which throws:
FileNotFoundException for Servlet/com.platform7.affina.operations.servlet.ValidateLoginUser.
But ValidateLoginUser is in the same package and classes folder location!
Folder structure:
\NEED4SPEEDCell02\operations_1.ear\OperationsWeb.war\WEB-INF\classes\com\platform7\affina\operations\servlet
ControllerMain.class and ValidateLoginUser.class are in same servlet package.
my Web.xml file:
<servlet>
<servlet-name>servletMain</servlet-name>
<servlet-class>com.platform7.affina.operations.servlet.ControllerMain</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>servletMain</servlet-name>
<url-pattern>/controllerMain</url-pattern>
</servlet-mapping>
So when I access my URL: it hits ControllerMain.class but inside this class I am calling another servlet which is not part of web.xml but is located in same package of ControllerMain.class.
When I print realpath: this.getServletContext().getRealPath("/"));
I get:
C:\WebSphere858\AppServer\profiles\AppSrv01\installedApps\NEED4SPEEDCell02\operations_1.ear\OperationsWeb.war
I tried using getNamedDispatcher(..) too but throws: null.
Same code works fine on Websphere 7 and even works on Websphere 8.5.5.5
Due to security reasons the default setting for com.ibm.ws.webcontainer.disallowServeServletsByClassname property has been changed.
Please Note:This APAR has changed the default value of the
WebContainer custom property
com.ibm.ws.webcontainer.disallowServeServletsByClassname from false to
true so that no security threat could occur. Prior to this change, it
was up to the developer to remember to change the custom property to
true before deploying into production.
Property Name:
com.ibm.ws.webcontainer.disallowServeServletsByClassname Description:
If set to true, disallows the use of serveServletsByClassnameEnabled
at the application server level, overriding any setting of
serveServletsByClassnameEnabled at the application level. This
property affects all applications. Values: true(default)/false
You will need to add that custom property to the Web Container and set it to false for serving servlets by class name.
But as BalusC suggested, you should add your servlet to web.xml in the form:
<servlet>
<servlet-name>servletMain</servlet-name>
<servlet-class>com.platform7.affina.operations.servlet.ValidateLoginUser</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>servletMain</servlet-name>
<url-pattern>/validateLoginUser</url-pattern>
</servlet-mapping>
and change that forward to:
this.getServletContext().getRequestDispatcher("/validateLoginUser").forward(request, response);
And do the same with your other class from the same package.
You seem to be relying on the legacy InvokerServlet which is known to have major security holes. This was deprecated in Tomcat 5 and clones (WebSphere 4) and removed in Tomcat 7 and clones (WebSphere 6).
You're not supposed to use it anymore. Just map the servlet on a normal URL pattern and invoke it. Assuming that the servlet is mapped on an URL pattern of /validateLoginUser via #WebServlet("/validateLoginUser") annotation on the servlet class, or via <url-pattern>/validateLoginUser</url-pattern> in web.xml mapping on the servlet, then you can get a request dispatcher on it as below:
request.getRequestDispatcher("/validateLoginUser");
Or, just refactor shared code to a plain Java class with a method and invoke it the usual Java way. It's these days kind of weird to have shared validation logic tight coupled in a servlet.
See also:
How to invoke a servlet without mapping in web.xml?
To make above upgrade working, I did few other changes as below for future references.
Mainly, I have to change binding files for websphere.
Previously, I had two bindings ibm-web-bnd.xmi and ibm-web-ext.xmi
ibm-web-bnd.xmi
<?xml version="1.0" encoding="UTF-8"?>
<com.ibm.ejs.models.base.bindings.webappbnd:WebAppBinding xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:com.ibm.ejs.models.base.bindings.webappbnd="webappbnd.xmi" xmi:id="WebAppBinding_1226331113121" virtualHostName="default_host">
<webapp href="WEB-INF/web.xml#WebApp"/>
<resRefBindings xmi:id="ResourceRefBinding_1226331113121" jndiName="AffinaDataSource_pma">
<bindingResourceRef href="WEB-INF/web.xml#ResourceRef_AffinaDataSource_pma"/>
</resRefBindings>
</com.ibm.ejs.models.base.bindings.webappbnd:WebAppBinding>
ibm-web-ext.xmi
<?xml version="1.0" encoding="UTF-8"?>
<com.ibm.ejs.models.base.extensions.webappext:WebAppExtension
xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"
xmlns:com.ibm.ejs.models.base.extensions.webappext="webappext.xmi"
xmi:id="WebAppExtension_1226331113121"
serveServletsByClassnameEnabled="true">
<webApp href="WEB-INF/web.xml#WebApp"/>
<jspAttributes xmi:id="JSPAttribute_1226331113121" name="reloadEnabled" value="true"/>
<jspAttributes xmi:id="JSPAttribute_1226331113122" name="reloadInterval" value="10"/>
</com.ibm.ejs.models.base.extensions.webappext:WebAppExtension>
So as per servlet3 and Websphere 8.5.5.8, I change to replace above two .xmi files with ibm-web-bnd.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-bnd xmlns="http://websphere.ibm.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd" version="1.0">
<virtual-host name="default_host"/>
<resource-ref name="AffinaDataSourceAlias_pma" binding-name="AffinaDataSource_pma"/>
</web-bnd>
and then while installing application on Websphere 8.5.5.8, it use to throw outofmemmory error, so to fix that I change below max memory parameter from 256m to 512m in wsadmin.bat
C:\WebSphere858\AppServer\bin\wsadmin.bat
set PERFJAVAOPTION=-Xms256m -Xmx512m -Xquickstart
Hope this helps.

What is right way to supply initialization for log4j2 in a Spring MVC Webapp using Java Config and no web.xml?

I have a Spring MVC Web App (4.0) with log4j2. This webapp uses no web.xml and takes care of configuration through Java Config. Log4j2 configuration needs to take place in an external config file, not on the classpath.
In a previous incarnation with web.xml we had
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>file:///path/to/log4j2.xml</param-value>
</context-param>
and this worked.
In the new web.xml-less world, I tried this:
public class WebappInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer
{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("WebappInitializer.onStartup()");
servletContext.setAttribute("log4jConfiguration", "file:///path/to/log4j2.xml");
This does not work. It seems to happen too late and in any event doesn't work. The logs show:
ERROR StatusLogger No Log4j context configuration provided. This is very unusual.
WebappInitializer.onStartup()
and no log4j logging occurs.
What is the right way to replace this context-param declaration with web.xml in a web.xml-less Spring MVC app?
UPDATE:
I can make this problem go away by adding the following web.xml:
<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>file:///path/to/log4j2.xml</param-value>
</context-param>
</web-app>
Surely, there must be a better way!
I believe you can reconfigure log4j2 to a new config file during runtime like this.
LoggerContext context = (LoggerContext)LogManager.getContext(false);
context.setConfigLocation(URI.create("path to file"));
context.reconfigure();
Could just add this to your onStartup.
Probably this is a little too late, but you can do the following to set the log4j2 configuration to an external path:
public class ApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext)
throws ServletException {
servletContext.setInitParameter(Log4jWebSupport.LOG4J_CONFIG_LOCATION, "file:///path/to/log4j2.xml");
I haven’t tested it but the following should be worth a try; replace your servletContext.setAttribute(…) call in the onStartup(…) method with the following Log4jConfigurer call:
Log4jConfigurer.initLogging("file:///path/to/log4j2.xml")
This is basically what happens under the hood when you use log4jConfigLocation in the <context-param> of a web.xml file (via Log4jWebConfigurer, see code).
I’m only wondering if this will also work with log4j2, although I wouldn’t expect the <context-param> way to work with it either. Did you also use log4j2 when you were still using the web.xml file?

Java WAR - Load Spring beans from an external JAR

I would like to load inside my Spring MVC Web Application (packaged as WAR) some Spring framework beans annotated with #Service from an external jar, which is in charge of accessing a database and located in the classpath under /WEB-INF/lib. If possible, it would be desirable to load them automatically using the #Autowired annotation.
I have followed successfully the solution in this link1:
this.ctx = new ClassPathXmlApplicationContext("services-context.xml");
this.myAService = ctx.getBean("myAService");
However, this solution uses Spring API function getBean which is considered a bad practice (see link2).
I also tried, without luck two more things to load the external jar´s applicationContext:
WAR´s appContext.xml:
<import resource="classpath*:/WEB-INF/lib/pathToExternalJar/applicationContext.xml">
WAR´s web xml -> load the jar´s appContext as described here (link3). (e.g. *applicationContext.xml):
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:localSpringContext.xml
classpath:*applicationContext.xml
</param-value>
</context-param>
What is the best approach to load those beans properly and how should it be done?
WAR´s appContext.xml and WAR´s web xml are both feasible. If you need to run integration tests based on both localSpringContext.xml and external jar's applicationContext.xml frequently, I recommend the WAR´s appContext.xml approach.
Updated1:
WAR´s appContext.xml:
<import resource="classpath:{classpath}/applicationContext.xml"/>
WAR´s web xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:localSpringContext.xml
classpath:{classpath}/applicationContext.xml
</param-value>
</context-param>
For example, if your applicationContext.xml is under package :com/gmail/hippoom
you can get it by classpath:com/gmail/hippoom/applicationContext.xml or classpath*:applicationContext.xml with wildcard.

#WebServlet annotation with Tomcat 7

In my application, I had a servlet which was defined like this in the web.xml:
<servlet>
<display-name>Notification Servlet</display-name>
<servlet-name>NotificationServlet</servlet-name>
<servlet-class>com.XXX.servlet.NotificationServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>NotificationServlet</servlet-name>
<url-pattern>/notification/*</url-pattern>
</servlet-mapping>
After moving to use Tomcat 7, I would like to use the #WebServlet annotation that will do the job.
Here is the way I did it:
#WebServlet( name="NotificationServlet", displayName="Notification Servlet", urlPatterns = {"/notification"}, loadOnStartup=1)
public class NotificationServlet extends HttpServlet {
And it does not work.
Could someone please tell me what I did wrong?
Provided that you're sure that you're using Tomcat 7 or newer, the webapp's web.xml has to be declared conform Servlet 3.0 spec in order to get Tomcat to scan and process the annotations. Otherwise Tomcat will still run in a fallback modus matching the Servlet version in web.xml. The support for servlet API annotations was only added in Servlet 3.0 (Tomcat 7).
So, the root declaration of your web.xml must look like below (make sure you remove any DOCTYPE from web.xml too, otherwise it will still be interpreted as Servlet 2.3!).
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
Further, there's a minor difference in the URL pattern. The URL pattern /notifications will let the servlet only listen on requests on exactly that path. It does not kick in on requests with an extra path like /notifications/list or something. The URL pattern /notifications/* will let the servlet listen on requests with extra path info as well.
The minimum #WebServlet annotation should thus look like this
#WebServlet("/notifications/*")
The rest of attributes are optional and thus not mandatory to get the servlet to function equally.
See also:
Our servlets wiki page
One may also want to check for having two classes with an annotations with the same name:
#WebServlet(name = "Foo", urlPatterns = {"/foo"})
public class Foo extends HttpServlet {
//...
}
And:
#WebServlet(name = "Foo", urlPatterns = {"/bar"})
public class Bar extends HttpServlet {
//...
}
In this cases, one of the servlets will not work. If you don't use the name, leave it out, like #BalusC suggests. I got the strange behavior that one of the servlets only worked right after changing and compiling it, but not after compilation without changes.
Additionally, in order to use these annotations and compile your code you must import the corresponding dependency in your pom.xml, but as provided cause your "Servlet 3.0" compliant server already has this.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>

Resources