This question already has answers here:
Failed to load ApplicationContext caused by ArrayIndexOutOfBoundsException in ClassReader
(5 answers)
Closed 5 years ago.
Hi guys i've been having trouble with one of my controllers, when I go to call it it throws an ArrayIndexOutOfBoundsException and I have no idea why. I've tried changing the configuration of web.xml and everything over and over and am getting nowhere. I get the following exception when attempting to call /categories:
SEVERE: StandardWrapper.Throwable
java.lang.ArrayIndexOutOfBoundsException: 3145
at org.springframework.asm.ClassReader.readClass(Unknown Source)
at org.springframework.asm.ClassReader.accept(Unknown Source)
at org.springframework.asm.ClassReader.accept(Unknown Source)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:54)
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.ConfigurationClassBeanDefinitionReader.checkConfigurationClassCandidate(ConfigurationClassBeanDefinitionReader.java:302)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:172)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:142)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:599)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:407)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Nov 03, 2017 8:59:19 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet rest
java.lang.ArrayIndexOutOfBoundsException: 3145
at org.springframework.asm.ClassReader.readClass(Unknown Source)
at org.springframework.asm.ClassReader.accept(Unknown Source)
at org.springframework.asm.ClassReader.accept(Unknown Source)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:54)
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.ConfigurationClassBeanDefinitionReader.checkConfigurationClassCandidate(ConfigurationClassBeanDefinitionReader.java:302)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:172)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:142)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:599)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:407)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
This is the FinderController class:
package uk.co.igindex.multilingualtranslation.application.rest;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import uk.co.igindex.multilingualtranslation.application.rest.response.FinderTranslationResponse;
import uk.co.igindex.multilingualtranslation.domain.Locale;
import uk.co.igindex.multilingualtranslation.eai.cache.FinderTranslationCache;
import uk.co.igindex.multilingualtranslation.eai.cache.TranslationCache;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
#Controller
#RequestMapping("/finder")
public class FinderController {
FinderTranslationCache finderCache;
TranslationCache translationCache;
#Autowired
public FinderController(FinderTranslationCache finderTranslationCache, TranslationCache translationCache) {
this.finderCache = finderTranslationCache;
this.translationCache = translationCache;
}
#RequestMapping(value = "/underlyings", method = RequestMethod.GET, headers = "content-type=application/json")
#ResponseBody
public String getUnderlyingTranslations() {
FinderTranslationResponse f = new FinderTranslationResponse();
for (Locale localeKey : finderCache.getUnderlyingTranslationKeys().keySet()) {
for (String combinedKey : finderCache.getUnderlyingTranslationKeys().get(localeKey).keySet()) {
f.addLocaleTranslation(localeKey.getValue(), finderCache.getUnderlyingTranslationKeys().get(localeKey).get(combinedKey),
translationCache.getCacheEntryFromCombinedKey(combinedKey));
}
}
return jsonify(f.returnLocaleMap());
}
#RequestMapping(value = "/contracts", method = RequestMethod.GET, headers = "content-type=application/json")
#ResponseBody
public String getContractTranslations() {
FinderTranslationResponse f = new FinderTranslationResponse();
f.addLocaleTranslation("en_GB", "translationKey", "translationValue");
f.addLocaleTranslation("en_GB", "translationKeysd", "translationValue");
f.addLocaleTranslation("en_GB", "translationKey3", "translationValue");
return jsonify(f.returnLocaleMap());
}
#RequestMapping(value = "/categories", method = RequestMethod.GET, headers = "content-type=application/json")
#ResponseBody
public String getCategoryList() {
StringBuilder sb = new StringBuilder();
for (String s : finderCache.getCategory()) {
sb.append(s + "\n");
}
return sb.toString();
}
#RequestMapping(value = "/miscellaneous", method = RequestMethod.POST, headers = "content-type=application/json")
#ResponseBody
public Map<String, String> getMiscellaneousTranslations(Set<String> words, String locale){
return new HashMap<>();
}
public String jsonify(Map map) {
JSONObject jsonObject = new JSONObject();
jsonObject.putAll(map);
return jsonObject.toString();
}
public void setTranslationCache(TranslationCache translationCache) {
this.translationCache = translationCache;
}
public void setFinderCache(FinderTranslationCache finderCache) {
this.finderCache = finderCache;
}
}
This is the web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<description>Multi-lingual Translation Web Application.</description>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:properties/multilingualtranslation/multilingualtranslation-log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jExposeWebAppRoot</param-name>
<param-value>false</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:MultilingualTranslation-jdbc.xml,
classpath*:MultilingualTranslation-config.xml,
classpath*:MultilingualTranslation-service.xml,
classpath*:MultilingualTranslation-jms.sf.xml,
classpath*:MultilingualTranslation-jndi.xml
</param-value>
</context-param>
<listener>
<listener-class>uk.co.igindex.multilingualtranslation.application.listener.MultilingualTranslationsContextListener</listener-class>
</listener>
<servlet>
<servlet-name>MultilingualTranslationDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- <init-param>
<param-name>wl-dispatch-policy</param-name>
<param-value>ClientVerificationWorkManager</param-value>
</init-param>-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--
Remoting servlet to support remote calls over HTTP (i.e. http
invoker).
-->
<servlet>
<servlet-name>remoting</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>remoting</servlet-name>
<url-pattern>/remoting/*</url-pattern>
</servlet-mapping>
<!--
<servlet>
<servlet-name>CXFServlet</servlet-name>
<display-name>CXF Servlet</display-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/webservice/*</url-pattern>
</servlet-mapping>-->
<servlet-mapping>
<servlet-name>MultilingualTranslationDispatcher</servlet-name>
<url-pattern>/translation</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MultilingualTranslationDispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<!-- MONITOR -->
<servlet>
<servlet-name>monitor</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/monitor-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>monitor</servlet-name>
<url-pattern>/monitor/*</url-pattern>
</servlet-mapping>
<resource-ref>
<description>Oracle DB Connection</description>
<res-ref-name>multilingualtranslationservice/jdbc/datasource/MultilingualTranslationService</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
and this is the rest-servlet.xml class
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="uk.co.igindex.multilingualtranslation.application.rest" />
<mvc:annotation-driven />
<import resource="classes/MultilingualTranslation-service.xml"/>
<bean id="finderController"
class="uk.co.igindex.multilingualtranslation.application.rest.FinderController">
</bean>
</beans>
Your problem happens here:
#RequestMapping(value = "/categories", method = RequestMethod.GET, headers = "content-type=application/json")
#ResponseBody
public String getCategoryList() {
StringBuilder sb = new StringBuilder();
for (String s : finderCache.getCategory()) {
sb.append(s + "\n");
}
return sb.toString();
}
The problem happens in your finderCache.getCategory(). where your getCategory has no items in it.
Please check with a debugger what finderCache.getCategory() has
If this isnt the problem, please post the logcat of your error.
Related
I created a jsp file register.jsp in which I am getting the details of the user and trying to save it in the database
RegisterServlet.java
package com.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.model.User;
import com.service.RegisterService;
public class RegisterServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String firstName = request.getParameter("firstName");
String middleName = request.getParameter("middleName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
String userId = request.getParameter("userId");
String password = request.getParameter("password");
User user = new User(firstName,middleName,lastName, email,userId, password);
try {
RegisterService registerService = new RegisterService();
boolean result = registerService.register(user);
out.println("<html>");
out.println("<head>");
out.println("<title>Registration Successful</title>");
out.println("</head>");
out.println("<body>");
out.println("<center>");
if(result){
out.println("<h1>Thanks for Registering with us :</h1>");
out.println("To login with new UserId and Password<a href=login.jsp>Click here</a>");
}else{
out.println("<h1>Registration Failed</h1>");
out.println("To try again<a href=register.jsp>Click here</a>");
}
out.println("</center>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<display-name>MVCApplication</display-name>
<servlet>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.controller.LoginServlet</servlet-class>
</servlet>
<servlet>
<display-name>RegisterServlet</display-name>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.controller.RegisterServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>InsertDataItem</servlet-name>
<servlet-class>com.controller.InsertDataItem</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InsertDataItem</servlet-name>
<url-pattern>/InsertDataItem</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
Error
**exception**
javax.servlet.ServletException: Error instantiating servlet class com.controller.RegisterServlet
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
**root cause**
java.lang.ClassNotFoundException: com.controller.RegisterServlet
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
Whenever I submit my details to register in the database this error
pops up!. Can anyone please help me ??
You will need to ensure that the RegisterServlet class is actually available to the servlet container.
Typically, inside the WEB-INF directory, you will have the following directories:
lib
classes
You will need to make sure that the class is available inside the classes directory or the class is inside a JAR in the lib directory
I have web application with spring, spring security, spring session with hazelcast.
It is running on clustered environment.
I see this exception in logs from time to time but can't reproduce it in locally.
It looks like some itercetptor or filter does not work correctly.
Any suggestion how to find the cause of the problem?
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:328) [catalina.jar:8.0.35]
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318) [catalina.jar:8.0.35]
at org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler.handleRequest(DefaultServletHttpRequestHandler.java:122) ~[spring-webmvc-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51) ~[spring-webmvc-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) [spring-webmvc-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) [servlet-api.jar:na]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.1.RELEASE.jar:4.3.1.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) [catalina.jar:8.0.35]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) [catalina.jar:8.0.35]
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:720) [catalina.jar:8.0.35]
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:584) [catalina.jar:8.0.35]
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:523) [catalina.jar:8.0.35]
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:436) [catalina.jar:8.0.35]
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:379) [catalina.jar:8.0.35]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:176) [catalina.jar:8.0.35]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [catalina.jar:8.0.35]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) [catalina.jar:8.0.35]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [catalina.jar:8.0.35]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528) [catalina.jar:8.0.35]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099) [tomcat-coyote.jar:8.0.35]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672) [tomcat-coyote.jar:8.0.35]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520) [tomcat-coyote.jar:8.0.35]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476) [tomcat-coyote.jar:8.0.35]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.0.35]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" 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" version="2.5">
<display-name>xxxx</display-name>
<description>xxxx</description>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>ch.qos.logback.classic.selector.servlet.ContextDetachingSCL</listener-class>
</listener>
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.xxxxx.services.authentication.xxxxApplicationContextInitializer</param-value>
</context-param>
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter>
<filter-name>LoggerContextFilter</filter-name>
<filter-class>ch.qos.logback.classic.selector.servlet.LoggerContextFilter</filter-class>
</filter>
<filter>
<filter-name>PageExpiryFilter</filter-name>
<filter-class>com.xxxxx.web.filters.PageExpiryFilter</filter-class>
</filter>
<filter>
<filter-name>CharacterEncodingFilter</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>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter>
<filter-name>sessionIpAddressSecurityFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggerContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>PageExpiryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>sessionIpAddressSecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>yyyy</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/webmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>yyyy</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error-page</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/resourceNotFound</location>
</error-page>
<error-page>
<error-code>405</error-code>
<location>/resourceNotFound</location>
</error-page>
<error-page>
<error-code>400</error-code>
<location>/resourceNotFound</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/notAuthorized</location>
</error-page>
<error-page>
<error-code>401</error-code>
<location>/notAuthorized</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/serverError</location>
</error-page>
<error-page>
<error-code>503</error-code>
<location>/serverError</location>
</error-page>
<error-page>
<error-code>504</error-code>
<location>/serverError</location>
</error-page>
<jsp-config>
<taglib>
<taglib-uri>http://xx.xx.xxx.com/tlds/functions</taglib-uri>
<taglib-location>/WEB-INF/tags/review.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
PageExpiryFilter:
public class PageExpiryFilter implements javax.servlet.Filter {
private static final int HOUR_TO_MINUTE = 60;
private static final int DAY_TO_MINUTE = 60 * 24;
private static final int MONTH_TO_MINUTE = 60 * 24 * 30;
private static final int WEEK_TO_MINUTE = 60 * 24 * 7;
private PageExpiryFilterPropertiesLoader loader = new PageExpiryFilterPropertiesLoader();
private final Pattern pattern = Pattern.compile("^(\\d+)(m|M|h|d|w)$");
private final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
private Map<String, Integer> pathRegex;
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) {
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
final String path = httpServletRequest.getRequestURI();
final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
setResponseHeader(path, httpServletResponse);
}
chain.doFilter(request, response);
}
private void setResponseHeader(final String path, final HttpServletResponse httpServletResponse) {
String expiryDate;
for (final String regex : pathRegex.keySet()) {
if (path.matches(regex)) {
final Integer age = pathRegex.get(regex);
expiryDate = createExpiryDate(age);
httpServletResponse.setHeader("Expires", expiryDate);
}
}
}
private String createExpiryDate(final Integer age) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, age);
return dateFormat.format(calendar.getTime());
}
#Override
public void init(final FilterConfig filterConfig) throws ServletException {
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
pathRegex = new LinkedHashMap<String, Integer>();
Properties properties = loader.loadProperties("/expires.properties");
populatePathRegex(properties);
}
private void populatePathRegex(final Properties properties) {
for (Entry<Object, Object> property : properties.entrySet()) {
Integer expirationInMinutes = getExpirationInMinutes(((String) property.getValue()).trim());
pathRegex.put((String) property.getKey(), expirationInMinutes);
}
}
private Integer getExpirationInMinutes(final String value) {
Integer minutes = 0;
if (value != null && value.length() != 0) {
final Matcher matcher = pattern.matcher(value);
if (matcher.matches()) {
final int val = Integer.parseInt(matcher.group(1));
final String denomination = matcher.group(2);
minutes = calculateMinutes(val, denomination);
} else {
throw new IllegalArgumentException("Invalid pattern '" + value + "'" + " for '" + value
+ "'. Valid patterns are '2m' for 2 minutes, '10h' for 10 hours, '1d' for 1 day, '1w' for 1 week, '1M' for 1 month");
}
}
return minutes;
}
private Integer calculateMinutes(final int val, final String denomination) {
int factor;
if ("m".equals(denomination)) {
factor = 1;
} else if ("h".equals(denomination)) {
factor = HOUR_TO_MINUTE;
} else if ("d".equals(denomination)) {
factor = DAY_TO_MINUTE;
} else if ("M".equals(denomination)) {
factor = MONTH_TO_MINUTE;
} else {
factor = WEEK_TO_MINUTE;
}
return val * factor;
}
public void setLoader(final PageExpiryFilterPropertiesLoader loader) {
this.loader = loader;
}
#Override
public void destroy() {
}
}
I've just started my first simple spring program. I'm trying to make a Rest API using Jersey framework with spring. Its a very basic simple program to fetch list of countries. But, however it throws the error. I've gone through other solutions, none of them worked.
Web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Error which I get is
SEVERE: StandardWrapper.Throwable
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1359)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:180)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:799)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:795)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
My program
package org.arpit.java2blog.jaxrs;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.arpit.java2blog.bean.Country;
#Path("/countries")
public class CountryRestService {
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Country> getCountries() {
System.out.println("Getting countries");
List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries = createCountryList();
return listOfCountries;
}
#GET
#Path("{id: \\d+}")
#Produces(MediaType.APPLICATION_JSON)
public Country getCountryById(#PathParam("id") int id) {
List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries = createCountryList();
for (Country country : listOfCountries) {
if (country.getId() == id)
return country;
}
return null;
}
// Utiliy method to create country list.
public List<Country> createCountryList() {
Country indiaCountry = new Country(1, "India");
Country chinaCountry = new Country(4, "China");
Country nepalCountry = new Country(3, "Nepal");
Country bhutanCountry = new Country(2, "Bhutan");
List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
return listOfCountries;
}
}
URL
http://localhost:8080/HelloWeb/rest/countries
What is missing in this one?
You don't have your Jersey servlet (ServletContainer) configured in your web.xml to pick up any resource classes. So Jersey starts up with no resources registered.
With web.xml generally the way to go, is to set an init-param to tell Jersey to scan a certain package for classes annotated with #Path and #Provider. To do that, just add the following
<servlet>
<servlet-name>jersey-serlvet</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>the.package.you.want.to.scan</param-value>
</init-param>
...
</servlet>
I'm trying to implement a REST WS. The following code works ok:
#Path("/MyRest")
#WebService
public class MyService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/{id}")
public Response test(#PathParam("id") String id) {
String str = "{\"status\":\"ok\",\"id\":\"" + id + "\"}";
return Response.status(200).entity(str).build();
}
}
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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>WSRest</display-name>
<servlet>
<servlet-name>Jersey REST Service</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>test</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Now i'm trying to do it with an Interface. The interface would be like follows, I guess:
#Path("/MyRest")
#WebService
public interface IService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/{id}")
public Response test(#PathParam("id") String id);
}
And now the WS implementation would be like this, right?:
public class MyService implements IService{
#Override
public Response test(#PathParam("id") String id) {
String str = "{\"status\":\"ok\",\"id\":\"" + id + "\"}";
return Response.status(200).entity(str).build();
}
}
I'm getting "HTTP Status 500 - Servlet.init() for servlet Jersey REST Service threw exception" when I try to "run" it again :/
Any ideas? Thanks in advance.
Full exception:
type Exception report
message Servlet.init() for servlet Jersey REST Service threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet Jersey REST Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2430)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2419)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)
root cause
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:491)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:321)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:376)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:559)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2430)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2419)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)
An example of a web method using an interface:
Web service implementation:
#Path("/WS")
#WebService
public class WebService implements IWebService {
#Override
#POST
#Consumes("application/json")
#Produces("application/json")
#Path("/Login")
public Response Login(JSONObject data) {
//stuff here
}
}
Interface:
public interface IWebService {
#POST
#Consumes("application/json")
#Produces("application/json")
#Path("/Login")
public Response Login(JSONObject data);
}
I have a problem for mapping my servlet with my Java Server Page, using the JSF framework and especially the commandLink tag.
When I click on the commandLink it only reload the same productList.jsp.
Here is my map web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Epimarket</display-name>
<servlet>
<servlet-name>mainServlet</servlet-name>
<servlet-class>com.epimarket.controller.EpimarketServlet</servlet-class>
<init-param>
<param-name>listURL</param-name>
<param-value>productList.jsp</param-value>
</init-param>
<init-param>
<param-name>editURL</param-name>
<param-value>productEdit.jsp</param-value>
</init-param>
<init-param>
<param-name>errorsURL</param-name>
<param-value>errors.jsp</param-value>
</init-param>
</servlet>
<filter>
<filter-name>MyFacesExtensionsFilter</filter-name>
<filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
<init-param>
<param-name>maxFileSize</param-name>
<param-value>20m</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<url-pattern>/faces/myFacesExtensionResource/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.PRETTY_HTML</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
<param-value>true</param-value>
</context-param>
<servlet-mapping>
<servlet-name>mainServlet</servlet-name>
<url-pattern>/do/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
Here is the faces-config.xml
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<application>
<locale-config>
<default-locale>fr</default-locale>
</locale-config>
</application>
<navigation-rule>
<from-view-id>/*</from-view-id>
<navigation-case>
<from-outcome>productList</from-outcome>
<to-view-id>/productList.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>productEdit</from-outcome>
<to-view-id>/productEdit.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>chart</from-outcome>
<to-view-id>/chart.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Here is my link to create a new Product (access editProduct.jsp page)
<h:commandLink id="createProductLink" value="Ajouter un produit" action="/do/edit"/>
Prefix h is for
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
And finally my doGet and doEditProduct methods in my Servlet :
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
if (initErrors.size() != 0)
{
req.setAttribute("erreurs", initErrors);
getServletContext().getRequestDispatcher(urlErrors).forward(req, res);
return ;
}
String reqType = req.getMethod().toLowerCase();
String action = req.getPathInfo();
if (action == null)
action = "/list";
if (reqType.equals("get") && action.equals("/list"))
{
doProductList(req, res);
return ;
}
if (reqType.equals("get") && action.equals("/delete"))
{
doDeleteProduct(req, res);
return ;
}
if (reqType.equals("get") && action.equals("/edit"))
{
doEditProduct(req, res);
return ;
}
if (reqType.equals("post") && action.equals("/validate"))
{
doValidateProduct(req, res);
return ;
}
doProductList(req, res);
}
private void doEditProduct(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
int id = Integer.parseInt(req.getParameter("id"));
Product product = null;
if (id != -1)
product = service.getProduct(id);
else
{
product = new Product();
product.setId(new BigDecimal(-1));
}
req.setAttribute("editError", "");
req.setAttribute("id", product.getId());
req.setAttribute("name", product.getName());
req.setAttribute("description", product.getDescription());
req.setAttribute("price", product.getPrice());
getServletContext().getRequestDispatcher((String)params.get("editURL")).forward(req, res);
}
Thank you for your help
With JSF you must not used servlets. You use managed beans.
In order to fix the above code, you should provide an action method, and invoke that method from your command button. In order to get more into the spirit of JSF, I'd suggest starting with a tutorial and/or a sample JSF probject.