Short question: when asking for a static resource to my spring mvc application, I get a 500 error with a NullPointerException thrown at the end of the request processing at org.apache.coyote.Response.setContentType(Response.java:452)
Long question:
I'm using Spring 3.2.5 in a Maven project developed with Netbeans.
Here is my pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>net.pluce</groupId>
<artifactId>WorkTime</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>WorkTime</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
</dependencies>
<build>
... build infos
</build>
I configured my application to get Restfuls urls, so my web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified #Configuration classes. Fully-qualified packages may also be
specified for component-scanning -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>net.pluce.worktime.config.AppConfig</param-value>
</context-param>
<!-- Bootstrap the root application context as usual using ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/JSP/*</url-pattern>
</servlet-mapping>
<!-- Declare a Spring MVC DispatcherServlet as usual -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<!-- Again, config locations must consist of one or more comma- or space-delimited
and fully-qualified #Configuration classes -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>net.pluce.worktime.config.MvcConfig</param-value>
</init-param>
</servlet>
<!-- map all requests for /app/* to the dispatcher servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
I use the JspServlet trick because if I don't, the spring servlet try to handle my calls to view like "/WEB-INF/JSP/blabla.jsp"
My folder structure:
src
main
java
my/packages/to/config.MvcConfig
my/packages/to/config.AppConfig
webapp
META-INF
context.xml
WEB-INF
JSP
index.jsp
web.xml
assets
css
myassets.css
js
jquery.js
resources
log4j.properties
test
This is my AppConfig class:
#Configuration
public class AppConfig {
private String mongoUrl = "localhost";
private String mongoDb = "worktime";
public #Bean MongoFactoryBean mongo() {
MongoFactoryBean mongo = new MongoFactoryBean();
mongo.setHost(mongoUrl);
return mongo;
}
public #Bean MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo().getObject(), mongoDb);
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
And my MvcConfig class:
#Configuration
#EnableWebMvc
#ComponentScan({"net.pluce.worktime"})
public class MvcConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/JSP/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
}
}
I've a controller which maps to the root and serves jsp correctly:
#Controller
public class IndexCtrl {
#Autowired
private MongoOperations ops;
#RequestMapping("/")
public String renderIndex(Model mav){
return "index";
}
}
And when I try to get my assets: GET http://localhost:8080/MyContextPath/assets/js/jquery.js, I get a 500 error:
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
cause mère
java.lang.NullPointerException
org.apache.coyote.Response.setContentType(Response.java:452)
org.apache.catalina.connector.Response.setContentType(Response.java:806)
org.apache.catalina.connector.ResponseFacade.setContentType(ResponseFacade.java:245)
org.springframework.web.servlet.resource.ResourceHttpRequestHandler.setHeaders(ResourceHttpRequestHandler.java:240)
org.springframework.web.servlet.resource.ResourceHttpRequestHandler.handleRequest(ResourceHttpRequestHandler.java:146)
org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:49)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Reading the (relevant part of the) log:
17:15:00,652 DEBUG DispatcherServlet:823 - DispatcherServlet with name 'dispatcher' processing GET request for [/WorkTime/assets/js/jquery.js]
17:15:00,657 TRACE DispatcherServlet:1088 - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#4bbc3c6] in DispatcherServlet with name 'dispatcher'
17:15:00,658 DEBUG RequestMappingHandlerMapping:220 - Looking up handler method for path /assets/js/jquery.js
17:15:00,659 DEBUG RequestMappingHandlerMapping:230 - Did not find handler method for [/assets/js/jquery.js]
17:15:00,660 TRACE DispatcherServlet:1088 - Testing handler map [org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping#4331fe97] in DispatcherServlet with name 'dispatcher'
17:15:00,660 TRACE BeanNameUrlHandlerMapping:127 - No handler mapping found for [/assets/js/jquery.js]
17:15:00,660 TRACE DispatcherServlet:1088 - Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#7418df8] in DispatcherServlet with name 'dispatcher'
17:15:00,660 DEBUG SimpleUrlHandlerMapping:169 - Matching patterns for request [/assets/js/jquery.js] are [/assets/**]
17:15:00,661 DEBUG SimpleUrlHandlerMapping:194 - URI Template variables for request [/assets/js/jquery.js] are {}
17:15:00,661 DEBUG SimpleUrlHandlerMapping:124 - Mapping [/assets/js/jquery.js] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#60cf9880] and 1 interceptor
17:15:00,662 TRACE DispatcherServlet:1122 - Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#5d252d27]
17:15:00,662 TRACE DispatcherServlet:1122 - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter#33b78b37]
17:15:00,662 DEBUG DispatcherServlet:912 - Last-Modified value for [/WorkTime/assets/js/jquery.js] is: -1
17:15:00,663 DEBUG ResourceHttpRequestHandler:173 - Trying relative path [js/jquery.js] against base location: ServletContext resource [/assets/]
17:15:00,674 DEBUG ResourceHttpRequestHandler:178 - Found matching resource: ServletContext resource [/assets/js/jquery.js]
17:15:00,674 DEBUG ResourceHttpRequestHandler:132 - Determined media type 'application/javascript' for ServletContext resource [/assets/js/jquery.js]
17:15:00,675 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#60cf9880]: java.lang.NullPointerException
17:15:00,676 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#60cf9880]: java.lang.NullPointerException
17:15:00,676 TRACE DispatcherServlet:1028 - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#16fd089a
17:15:00,677 DEBUG DispatcherServlet:959 - Could not complete request
java.lang.NullPointerException
at org.apache.coyote.Response.setContentType(Response.java:452)
at org.apache.catalina.connector.Response.setContentType(Response.java:806)
at org.apache.catalina.connector.ResponseFacade.setContentType(ResponseFacade.java:245)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.setHeaders(ResourceHttpRequestHandler.java:240)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.handleRequest(ResourceHttpRequestHandler.java:146)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:49)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
17:15:00,680 TRACE AnnotationConfigWebApplicationContext:332 - Publishing event in WebApplicationContext for namespace 'dispatcher-servlet': ServletRequestHandledEvent: url=[/WorkTime/assets/js/jquery.js]; client=[127.0.0.1]; method=[GET]; servlet=[dispatcher]; session=[C2D001FA38DB36BD6286C598E46652D2]; user=[null]; time=[38ms]; status=[failed: java.lang.NullPointerException]
17:15:00,681 TRACE AnnotationConfigWebApplicationContext:332 - Publishing event in Root WebApplicationContext: ServletRequestHandledEvent: url=[/WorkTime/assets/js/jquery.js]; client=[127.0.0.1]; method=[GET]; servlet=[dispatcher]; session=[C2D001FA38DB36BD6286C598E46652D2]; user=[null]; time=[38ms]; status=[failed: java.lang.NullPointerException]
What I read:
- My request is processed by Spring dispatcher servlet
- the request is mapped to ResourceHttpRequestHandler
- ResourceHttpRequestHandler finds the matching resource in my files
- it determines the good media type "application/javascript"
- a NullPointerException is thrown when the Response is being written.
I had a look to the Response.setContentType() method and found nothing worth a NullPointerException.
Thanks in advance
Related
I am currently using SpringBoot and a #Configuration JavaClass to register the Servlet HttpRequestHandlerService
But It always tells me that is is not available
Here is my code Class for the registration of the bean:
#Configuration
public class WebConfiguration extends SpringBootServletInitializer {
private static final String SERVLET_NAME = "DataFileServlet";
/**
* Initializer servlet context initializer.
*
* #return the servlet context initializer
*/
#Bean
public ServletContextInitializer initializer() {
return servletContext -> {
servletContext.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", "true");
servletContext.setInitParameter("contextConfigLocation", "classpath:applicationContext.xml");
servletContext.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "1");
servletContext.setInitParameter("primefaces.THEME", "admin");
servletContext.setInitParameter("primefaces.FONT_AWESOME", "true");
servletContext.setInitParameter("com.sun.faces.sendPoweredByHeader", "false");
servletContext.setInitParameter("javax.faces.CLIENT_WINDOW_MODE", "url");
};
}
/**
* Is used to register the servlet HttpRequestHandler.
*
* #return the servlet "registartionBean"
*/
#Bean
public ServletRegistrationBean<HttpRequestHandlerServlet> dataFileServletRegistration() {
ServletRegistrationBean<HttpRequestHandlerServlet> registrationBean = new ServletRegistrationBean<>(new HttpRequestHandlerServlet());
registrationBean.setName(SERVLET_NAME);
registrationBean.setLoadOnStartup(1);
return registrationBean;
}
/**
* Is responcable for registering a filter.
*
* #return the filter "registrationBean"
*/
#Bean
public FilterRegistrationBean<CharacterEncodingFilter> encodingFilter() {
FilterRegistrationBean<CharacterEncodingFilter> registrationBean = new FilterRegistrationBean<>(new CharacterEncodingFilter());
registrationBean.setEnabled(true);
registrationBean.setOrder(1);
registrationBean.addInitParameter("encoding","UTF-8" );
registrationBean.addInitParameter("forceEncoding", "true");
return registrationBean;
}
/**
* Is resposible for registering a new listener.
*
* #return the listener "registrationBean"
*/
#Bean ServletListenerRegistrationBean<IntrospectorCleanupListener> IntrospectorCleanupListener(){
ServletListenerRegistrationBean<IntrospectorCleanupListener> registrationBean = new ServletListenerRegistrationBean<>();
registrationBean.setListener(new IntrospectorCleanupListener());
return registrationBean;
}
}
and here is my Stacktrace
2019-02-14 16:16:35.151 ERROR 5468 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : StandardWrapper.Throwable
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'DataFileServlet' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:772)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
at org.springframework.web.context.support.HttpRequestHandlerServlet.init(HttpRequestHandlerServlet.java:60)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1123)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:974)
at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext.load(TomcatEmbeddedContext.java:83)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
at java.util.TreeMap$ValueSpliterator.forEachRemaining(TreeMap.java:2897)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext.lambda$deferredLoadOnStartup$0(TomcatEmbeddedContext.java:65)
at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext.doWithThreadContextClassLoader(TomcatEmbeddedContext.java:108)
at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedContext.deferredLoadOnStartup(TomcatEmbeddedContext.java:64)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.performDeferredLoadOnStartup(TomcatWebServer.java:282)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:200)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.startWebServer(ServletWebServerApplicationContext.java:311)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:164)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at de.Application.main(Application.java:33)
2019-02-14 16:16:35.233 INFO 5468 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-02-14 16:16:35.234 ERROR 5468 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Failed to destroy the filter named [Tomcat WebSocket (JSR356) Filter] of type [org.apache.tomcat.websocket.server.WsFilter]
java.lang.AbstractMethodError: null
at org.apache.catalina.core.ApplicationFilterConfig.release(ApplicationFilterConfig.java:301)
at org.apache.catalina.core.StandardContext.filterStop(StandardContext.java:4543)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5345)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1398)
at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1387)
at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
at java.util.concurrent.FutureTask.run(FutureTask.java)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.stopInternal(ContainerBase.java:974)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1398)
at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1387)
at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
at java.util.concurrent.FutureTask.run(FutureTask.java)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.stopInternal(ContainerBase.java:974)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.core.StandardService.stopInternal(StandardService.java:475)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.core.StandardServer.stopInternal(StandardServer.java:995)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.startup.Tomcat.stop(Tomcat.java:408)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.stopTomcat(TomcatWebServer.java:250)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.stop(TomcatWebServer.java:306)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.stopAndReleaseWebServer(ServletWebServerApplicationContext.java:320)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at de.Application.main(Application.java:33)
2019-02-14 16:16:35.244 INFO 5468 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-02-14 16:16:35.309 ERROR 5468 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'DataFileServlet' that could not be found.
Action:
Consider defining a bean named 'DataFileServlet' in your configuration.
And my WebXML
<?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_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>1</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>primefaces.FONT_AWESOME</param-name>
<param-value>true</param-value>
</context-param>
<!-- security: don´t send x-powered-by-header -->
<context-param>
<param-name>com.sun.faces.sendPoweredByHeader</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>javax.faces.CLIENT_WINDOW_MODE</param-name>
<param-value>url</param-value>
</context-param>
<servlet>
<servlet-name>DataFileServlet</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataFileServlet</servlet-name>
<url-pattern>/DataFileServlet</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
What Can I do to get It to work properly?
HttpRequestHandlerServlet delegates to an HttpRequestHandler bean. This is described in the class's javadoc:
delegates to an HttpRequestHandler bean defined in Spring's root web application context. The target bean name must match the HttpRequestHandlerServlet servlet-name
When defining the registration bean for the servlet you have set its name to DataFileServlet. As a result, when the servlet receives a request, it is attempting to retrieve a bean named DataFileServlet. This is failing as there is no bean defined with that name.
To use HttpRequestHandlerServlet as you have configured it, you need to define an HttpRequestHandler bean named DataFileServlet:
#Bean(name="DataFileServlet")
public HttpRequestHandler dataFileServlet() {
return (request, response) -> {
// Handler implementation
};
}
I start with Spring Web (following Spring documentation) and i have a little problem with the initialization
Every time i have the stack trace : "java.lang.IllegalArgumentException: Failed to register servlet with name 'dispatcher'.Check if there is another servlet registered under the same name."
Here are my files :
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">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified #Configuration classes. Fully-qualified packages may also be
specified for component-scanning -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.lacunasaurus.configuration.SpringApplicationConfiguration</param-value>
</context-param>
<!-- Bootstrap the root application context as usual using ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Declare a Spring MVC DispatcherServlet as usual -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<!-- Again, config locations must consist of one or more comma- or space-delimited
and fully-qualified #Configuration classes -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.lacunasaurus.configuration.SpringWebApplicationInitializer</param-value>
</init-param>
</servlet>
home.html
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Hello World!</h1>
Greeting : ${greeting}
</body>
</html>
ControllerHome
package com.lacunasaurus.web.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class ControllerHome {
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("greeting", "Hello World from Spring 4 MVC");
return "welcome";
}
#RequestMapping(value = "/helloagain", method = RequestMethod.GET)
public String sayHelloAgain(ModelMap model) {
model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
return "welcome";
}
}
Spring configuration
package com.lacunasaurus.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages = {"com.lacunasaurus.service"})
public class SpringApplicationConfiguration {
}
Webinitializer
package com.lacunasaurus.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringApplicationConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/*"};
}
}
And my webconfig
package com.lacunasaurus.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.lacunasaurus.web.controllers")
public class WebConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".html");
return viewResolver;
}
}
I use maven and "4.3.4.RELEASE" spring version
My pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lacunasaurus.vapologie</groupId>
<artifactId>test-web</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Vapologie Webapp</name>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>test</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</build>
</project>
and the full stack trace :
12-Dec-2016 23:16:35.543 SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/vapologie-web]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1780)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Failed to register servlet with name 'dispatcher'.Check if there is another servlet registered under the same name.
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.registerDispatcherServlet(AbstractDispatcherServletInitializer.java:98)
at org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.onStartup(AbstractDispatcherServletInitializer.java:71)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:169)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5170)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 10 more
12-Dec-2016 23:16:35.544 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDescriptor Erreur lors du déploiement du descripteur de configuration C:\Users\Aurélien\AppData\Roaming\NetBeans\8.2\apache-tomcat-8.0.27.0_base\conf\Catalina\localhost\tes-web.xml
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/vapologie-web]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:729)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1780)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Thank for your help :)
I finally find a way to initialize by java code :)
In my 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">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
</web-app>
And i change my WebConfig to extends the WebMvcConfigurerAdapter
public class VapologieWebConfig extends WebMvcConfigurerAdapter
But now i have warnings because spring can't redirect me to my view :(
[2016-12-13 03:38:10,170] Artifact test-web:war exploded: Artifact is being deployed, please wait...
13-Dec-2016 15:38:12.283 INFOS [RMI TCP Connection(3)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
13-Dec-2016 15:38:12.523 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.ContextLoader.initWebApplicationContext Root WebApplicationContext: initialization started
13-Dec-2016 15:38:12.672 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.support.AnnotationConfigWebApplicationContext.prepareRefresh Refreshing Root WebApplicationContext: startup date [Tue Dec 13 15:38:12 CET 2016]; root of context hierarchy
13-Dec-2016 15:38:12.782 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.support.AnnotationConfigWebApplicationContext.loadBeanDefinitions Registering annotated classes: [class com.lacunasaurus.test.configuration.SpringApplicationConfiguration]
13-Dec-2016 15:38:13.213 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.<init> JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
13-Dec-2016 15:38:13.350 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.ContextLoader.initWebApplicationContext Root WebApplicationContext: initialization completed in 826 ms
13-Dec-2016 15:38:13.363 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.DispatcherServlet.initServletBean FrameworkServlet 'dispatcher': initialization started
13-Dec-2016 15:38:13.371 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.support.AnnotationConfigWebApplicationContext.prepareRefresh Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Dec 13 15:38:13 CET 2016]; parent: Root WebApplicationContext
13-Dec-2016 15:38:13.373 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.support.AnnotationConfigWebApplicationContext.loadBeanDefinitions Registering annotated classes: [class com.lacunasaurus.test.configuration.testWebConfig]
13-Dec-2016 15:38:13.568 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.<init> JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
13-Dec-2016 15:38:14.108 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.register Mapped "{[/],methods=[GET]}" onto public java.lang.String com.lacunasaurus.test.web.controllers.ControllerHome.sayHello(org.springframework.ui.ModelMap)
13-Dec-2016 15:38:14.110 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.register Mapped "{[/helloagain],methods=[GET]}" onto public java.lang.String com.lacunasaurus.test.web.controllers.ControllerHome.sayHelloAgain(org.springframework.ui.ModelMap)
13-Dec-2016 15:38:14.167 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.initControllerAdviceCache Looking for #ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Dec 13 15:38:13 CET 2016]; parent: Root WebApplicationContext
13-Dec-2016 15:38:14.436 INFOS [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.servlet.DispatcherServlet.initServletBean FrameworkServlet 'dispatcher': initialization completed in 1072 ms
[2016-12-13 03:38:14,456] Artifact test-web:war exploded: Artifact is deployed successfully
[2016-12-13 03:38:14,456] Artifact test-web:war exploded: Deploy took 4 286 milliseconds
13-Dec-2016 15:38:14.865 AVERTISSEMENT [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/test/WEB-INF/views/home.html] in DispatcherServlet with name 'dispatcher'
13-Dec-2016 15:38:15.785 AVERTISSEMENT [http-nio-8080-exec-3] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/test/WEB-INF/views/home.html] in DispatcherServlet with name 'dispatcher'
13-Dec-2016 15:38:19.982 INFOS [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Déploiement du répertoire D:\Serveurs\apache-tomcat-8.5.9\webapps\manager de l'application web
13-Dec-2016 15:38:20.086 INFOS [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory D:\Serveurs\apache-tomcat-8.5.9\webapps\manager has finished in 103 ms
----------------- EDIT ------------------------
I found the solution !
In full java configuration, the web config class need to implement the servlet handling method to activate the configurer
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
Now I can show my home page :)
Thanks to everyone who help me to find the solution
I found this same question in here few times, but I couldn't find an answer to that.
When I run my application, Im getting the following error
javax.ws.rs.NotFoundException: Could not find resource for full path: http://localhost:8080/RemoteQuartzScheduler/rest/TestClass/hello
at org.jboss.resteasy.core.registry.ClassNode.match(ClassNode.java:73)
at org.jboss.resteasy.core.registry.RootClassNode.match(RootClassNode.java:48)
at org.jboss.resteasy.core.ResourceMethodRegistry.getResourceInvoker(ResourceMethodRegistry.java:444)
at org.jboss.resteasy.core.SynchronousDispatcher.getInvoker(SynchronousDispatcher.java:234)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:171)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Here is the pom file of the project (I only added the main parts)
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.9.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-servlet-initializer</artifactId>
<version>3.0.9.Final</version>
</dependency>
</dependencies>
And here is my web.xml file
<web-app version="3.0" 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">
<display-name>RemoteQuartzScheduler</display-name>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- this should be the same URL pattern as the servlet-mapping property -->
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
</servlet>
Here is my Test.java class
#Path("/TestClass")
public class Test implements Serializable{
private static final long serialVersionUID = -262701666015379272L;
#GET
#Path("/hello")
public Response heloMessage() {
String result = "Hello Word!!!!!!!!!";
return Response.status(200).entity(result).build();
}
}
Please tell me where did I do wrong?? Thanks in advance
I haven't gotten a chance to test your version (with the web.xml), and honestly I don't work much with xml when I do use Resteasy, so I won't go trying to explain what is wrong (if anything) with the web.xml.
But when working with an javax.xs.rs.core.Application subclass, we can define an #ApplicationPath("/path") annotation. This defines a servlet for our JAX-RS application, with the url mapping of /path/*. This is specified in the JAX-RS spec.
You can see more here about this deployment option, as well as others, in section 2.3.2 Configuration - Servlet. This is a 1.1 spec (you are using 2.0), but the deployment options are similar. I just couldn't find an html link to the 2.0. You can download the pdf though from here.
You can also read more about deployments with Resteasy here in the documentation.
But basically, what this deployment option does is scan for annotations of #Path, #Provider, etc for the application. The reason is that JAX-RS will first look for classes and object in overridden getClasses() and getSingletons(), respectively. If then return empty sets, this tell JAX-RS to do scanning (per the spec).
I am able to access REST services from the browser url: http://localhost:8080/assignment/services/services/test/test1
From My servlet, I use to call service method as shown below. Now I need to call through REST services but getting below error.
URL url = new URL("http://localhost:8080/assignment/services/services/"+userName+"/"+password);
System.out.println("URL-->"+url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while(bufferedReader.readLine() != null){
result = bufferedReader.readLine();
}
// result = userService.login(userName, password);
System.out.println(result);
here is the error:
INFO: Reloading Context with name [/assignment] is completed
URL-->http://localhost:8080/assignment/services/test/test1
Jul 30, 2013 12:52:02 PM org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor processRequest
WARNING: No root resource matching request path /assignment/services/test/test1 has been found, Relative Path: /test/test1. Please enable FINE/TRACE log level for more details.
Jul 30, 2013 12:52:02 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: javax.ws.rs.NotFoundException
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:172)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:100)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:271)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:203)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:137)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:158)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java
...
Jul 30, 2013 12:52:02 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [LoginServlet] in context with path [/assignment] threw exception
java.io.FileNotFoundException: http://localhost:8080/assignment/services/services/test/test1
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1623)
at com.viasat.test.login.servlet.LoginServlet.process(LoginServlet.java:77)
at com.viasat.test.login.servlet.LoginServlet.doPost(LoginServlet.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Service class:
#Service
#Path("/services/")
public class UserServiceImpl implements UserService {
#GET
#Path("{userName}/{password}")
#Produces(MediaType.TEXT_XML)
public String login(#PathParam("userName")String username, #PathParam("password")String password)
throws JAXBException, PropertyException, FileNotFoundException {
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/beans.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.abc.test.login.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>
Update:
pom.xml:
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
Now Javax.ws.rs.NotFoundException gone, but, File not found exception still comes.
Solution-1
One of the solution is that version issue with CXF and Spring. I have made cxf version to 2.5.2 which avoids javax.ws.rs.NotFoundException.
Now I have updated to
<spring.version>3.2.2.RELEASE</spring.version>
<cxf.version>2.5.2</cxf.version>
I was using 2.7.5 cxf version.
Solution -2
In my service class I have made
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) instead of
#Produces(MediaType.TEXT_XML)
The URL you are using to fire the GET request has two services levels:
http://localhost:8080/assignment/services/services/"
but in your REST service class, there is only one 'services' level in Path. You may need to change the Path Param to like this:
#Service
#Path("/services/")
public class UserServiceImpl implements UserService {
#GET
#Path("services/{userName}/{password}")
#Produces(MediaType.TEXT_XML)
public String login(#PathParam("userName")String username, #PathParam("password")String password)
throws JAXBException, PropertyException, FileNotFoundException {
I think "services" is by default the path where CXF exposes the auto-generated WADLs and therefore cannot be used in a resource path.
Try either changing "services" to another word in your web.xml and Service class (#Path) or change the CXF servlet config like so (see the service-list-path param):
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<init-param>
<param-name>service-list-path</param-name>
<param-value>web-services</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Reference: http://cxf.apache.org/docs/jaxrs-services-description.html (section Service listings and WADL queries almost at the end).
Note that you can override the location at which listings are provided
(in case you would like '/services' be available to your resources)
using 'service-list-path' CXFServlet parameter
one common reason for this error is that cxf cannot find a restful implementation for the restful service to match the request to the resource method later. the spec is ambiguious in this area but your jaxrs annotations in the interface must match implementation in cxf.
--eliani
As described in CXF project throws java.lang.NoClassDefFoundError: javax/ws/rs/NotFoundException the
Error can be solved by adding
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0-m10</version>
</dependency>
I am having a strange issue with a Spring web application. This is from the Tomcat log:
GRAVE: Exception lors de l'envoi de l'évènement contexte initialisé (context initialized) à l'instance de classe d'écoute (listener) org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.jverstry.Configuration.WebConfig; nested exception is java.io.FileNotFoundException: class path resource [java/lang/Object.class] cannot be opened because it does not exist
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:267)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:203)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:622)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1247)
at org.apache.catalina.manager.HTMLManagerServlet.start(HTMLManagerServlet.java:714)
at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:219)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:186)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1770)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: class path resource [java/lang/Object.class] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:49)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:257)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:149)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:126)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:219)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:149)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:126)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:263)
... 36 more
16-sept.-2012 15:51:56 org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
I have seen similar questions on SO, but none related to java/lang/Object.class. I hae no idea what is causing this.
This is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.jverstry.Configuration</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>mytest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/mytest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file></welcome-file>
</welcome-file-list>
</web-app>
Here is my WebConfig class:
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = {"com.jverstry", "org.krams"})
#ImportResource("WEB-INF/spring-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver
= new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
}
That is most peculiar.
Lets start with the what we do know. The class java.lang.Object and the corresponding java/lang/Object.class file most certainly do exist. If they didn't then is is highly unlikely that the JVM would have started in the first place.
So how come you get the exception?
My theory it that somewhere in your codebase (or the libraries you are using) there is a classloader that is breaking the rules. When it is asked to load a resource, a well behaved class loader will first delegate up the class loader chain to see if its parent classloader can load the resource. I suspect that what is happening is that the broken classloader is skipping the delegation step and just trying to load the resource itself. If the "rt.jar" is not on its list of JARs, etc (and it normally won't be) then the class loader won't find the Object.class file ... and you will get a FileNotFoundException.
UPDATE
I think I understand. If your Java installation was corrupted to the extent that it couldn't load java.lang.Object, then the JVM wouldn't boot. And if it had already booted before the corruption, then it wouldn't be trying to load the Object class.
But it is not trying to do that. It is actually trying to read the Object.class file. And the stacktrace seem to be saying that this is occurring in Spring's annotation processing code.
So I think that something has triggered a servlet restart after the Java installation was compromised. And the restart caused the spring configuration to be done again. Why it worked when you rebooted is a mystery ... unless the problem was due to a hardware error or stuck device driver that was cleared by the reboot.
(The post you found describes a different scenario ... where the JVM fail during its bootstrap. Your scenario is more complicated.)
It turns out my JRE6 installation was somehow corrupted. I reinstalled it manually and now I don't have an issue anymore. I have also found another post which might explain why the issue would disappear after rebooting.