How to set classpath in Spring mvc app? - spring-mvc

I have two different web apps on my server. One is Spring mvc app and other is struts app. Libraries for these apps are at different locations. Following is my Spring mvc app structure:
All jar files for Spring mvc app are in WEB-INF/lib directory. Following is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>My project</display-name>
<servlet>
<servlet-name>route</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>route</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
When I run spring app, it shows exception:
[org.springframework.web.servlet.DispatcherServlet] (MSC service thread 1-6) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.myproject.scm.dao.LoginDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/route-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.addAnnotatedClass(Ljava/lang/Class;)Lorg/hibernate/cfg/Configuration;
But when I run Spring mvc app without struts app, it runs fine. Maybe there are conflicting libraries?
Can I add classpath in my Spring mvc app, so that it look library jars at proper location?

JBoss 7 ships with Hibernate 3. You'll have to exclude it in your jboss-deployment-structure if you want to use Hibernate 4. Take a look at https://docs.jboss.org/author/display/AS7/Implicit+module+dependencies+for+deployments for more information on implicit dependencies.

Related

Web.xml servlet-class references to non-existent class "ClassName"

I am working on a project and hit a brick wall. I couldn't find any resources or bug reports to solve this issue. I have a maven project setup as maven-archetype-webapp. I am new to JEE and it took me sometime to get this far but I have a better understanding of how some of this works. I have hit a brick wall and don't know how to solve the problem below.
I get the following warnings within the web.xml file
servlet-class references to non-existent class "servlets.RegisterServlet"
servlet-class references to non-existent class "servlets.HomePageServlet"
file name references to "index" that does not exist in web content
I get the following error in WildFly 10.x.
Caused by: java.lang.ClassNotFoundException: servlets.RegisterServlet from [Module "deployment.PracticeProject.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.createServletConfig(UndertowDeploymentInfoService.java:723)
... 6 more
The java classes appear in the directory structure of the war so its packaging it correctly. For the entities, session beans and servlets I have a scope of provided for the dependencies of the pom.xml file.
My directory structure is as follows:
My web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>PracticeProject</display-name>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>servlets.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>HomePageServlet</servlet-name>
<servlet-class>servlets.HomePageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HomePageServlet</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index</welcome-file>
</welcome-file-list>
</web-app>
edit:
CHKJ3013E: The URL Mapping "" is invalid. web.xml /PracticeProject/src/main/webapp/WEB-INF org.eclipse.jst.j2ee.webapplication.internal.impl.ServletMappingImpl#53667dce (urlPattern: , name: null) Validation Message

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.

Unable to load spring application Context

I want to load myapp-servlet.xml as my web application context. I have neither defined spring contextLoaderListner not have defined context params, only the dispatcher servlet is defined.
<display-name>myapp</display-name>
<description/>
<servlet>
<servlet-name>myapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
config file is present in /WEB-INF/myapp-servlet.xml and I'm expecting it to be loaded. But I'm getting the following exception
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
I'm want to know why the default applicationContext.xml file is looked for even when context-param and contextLoaderListener is not defined?
Just add the appropriate context-param for your Spring config file:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/myapp-servlet.xml</param-value>
</context-param>
There is probably a default config file location in the Spring code... Seems like a good opportunity to UTSL...
Just add
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
to your web.xml

Tomcat7 deploy Fail: org.apache.catalina.LifecycleException: Failed to start component /w org.springframework.web.servlet.DispatcherServlet

I have a very sample web.xml written below:
The problem is...If I remove org.springframework.web.servlet.DispatcherServlet section, I can successfully deploy my project in Tomcat7 as a simple JSP-Servlet app. However, once I use Spring MVC, my deployment will FAIL - Encountered exception org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/WebMVCProj2]]
How can I fix this error?
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
Spring Web MVC Application
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<!-- I can remove the part below to make deployment successful -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
I add Spring MVC dependency from Enterprise Bundle Repository (EBR). I also use Eclipse Dynamic Web Module 3.0 which Tomcat7 should support. My jre is 1.6.x 64bits used by Tomcat and my project. I also use Web Deployment Assembly in Eclipse.
Here is my complete exception:
SEVERE: Error deploying web application archive E:\MyServers\apache-tomcat-7.0.30\webapps\WebMVCProj2.war
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/WebMVCProj2]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:618)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:963)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1600)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
You should have applicationContext.xml in web-inf folder or you have to define contextConfigLocation in your web.xml
<!-- Spring Context -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/application-contexts/*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
It would be more helpful, if you could post exception trace.
you can check your servlet class is having any annotation like #WebServlet(". I resolved the similar issue by removing the annotation in servlet class.

What is causing the mapping failure in this Spring MVC app?

I'm trying to get a very simple Spring #mvc app to work and I'm running into what appears to be a mapping error.
From web.xml:
<servlet>
<servlet-name>works</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>works</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
The controller:
#Controller
#RequestMapping("/test")
public class TESTController {
private static Logger appLogger = Logger.getLogger("AppLogFile");
public String serviceRequest( Model model)
{
appLogger.info("======================= TESTController GET ===============================");
model.addAttribute("returnString","TESTController handled the request") ;
return "SingleStringView";
}
works-servlet.xml:
<context:component-scan base-package="com.ami.dbconnect.controller" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean id="TESTController" class="com.ami.dbconnect.controller.TESTController"></bean>
<!-- view resolver not shown -->
The app is deployed to Tomcat 7 at /webapps/works. The Tomcat file structure is:
webapps
/works
/WEB-INF
/classes
/lib
I'm trying to invoke the controller with the url: localhost:8080/works/test
In tomcat7-stdout I see:
1106 [pool-2-thread-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Published WebApplicationContext of servlet 'works' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.works]
1106 [pool-2-thread-1] INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'works': initialization completed in 728 ms
1106 [pool-2-thread-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Servlet 'works' configured successfully
14068 [http-apr-8080-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'works' processing GET request for [/works/test]
14071 [http-apr-8080-exec-2] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/works/test] in DispatcherServlet with name 'works'
So my question (finally!):
Is Spring not recognizing the annotations in the controller? If not, what could be wrong in this simple set up?
Thanks for any help or advice,
beeky
You need to move #RequestMapping annotation to your serviceRequest method.
#RequestMapping at class level may be used to specify common path prefix for all #RequestMapping-annotated of that class, but it doesn't take any effect without annotations at method level.
Maybe problem is in the servlet mapping section?
Try to change:
<servlet-mapping>
<servlet-name>works</servlet-name>
<url-pattern>/works/*</url-pattern>
</servlet-mapping>
And try again.

Resources