First time I'm trying a WebService using jersey. The below code I got from some blog.
I am getting following 500 error when I'm trying Java Web service using jersey client
javax.servlet.ServletException: Servlet.init() for servlet Jersey Root REST Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
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:1008)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:79)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.init(WebAppResourceConfig.java:102)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.<init>(WebAppResourceConfig.java:89)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.<init>(WebAppResourceConfig.java:74)
com.sun.jersey.spi.container.servlet.WebComponent.getWebAppResourceConfig(WebComponent.java:672)
com.sun.jersey.spi.container.servlet.ServletContainer.getDefaultResourceConfig(ServletContainer.java:415)
com.sun.jersey.spi.container.servlet.ServletContainer.getDefaultResourceConfig(ServletContainer.java:582)
com.sun.jersey.spi.container.servlet.WebServletConfig.getDefaultResourceConfig(WebServletConfig.java:87)
com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:703)
com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:678)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:203)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
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:1008)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)'
Below is my web.xml file
<?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>RestFulWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Root REST Service</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 Root REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>'
Here i tried adding the package also that didn't help:
Added only one jar file jersey-bundle-1.14.jar. The following is my Jersey server
package com.rest.server;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.rest.data.Hello;
// POJO, no interface no extends
// The class registers its methods for the HTTP GET request using the #GET annotation.
// Using the #Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML.
// The browser requests per default the HTML MIME type.
//Sets the path to base URL + /hello
#Path("/hello")
public class HelloWorldRest {
#GET
#Path("/{param}/")
public String getMsg(#PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return output;
}
#GET
#Path("/world")
public String getFixedMsg(String msg) {
String output = "Jersey say : fixed path" + msg;
return output;
}
// This method is called if TEXT_PLAIN is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
System.out.println("sayPlain");
return "Hello Jersey";
}
// This method is called if XML is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
System.out.println("sayXML");
return "" + " Hello Jersey" + "";
}
// This method is called if HTML is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
System.out.println("sayHTML");
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
// This method is called if JSON is request
#GET
//#Path("helloworld")
#Produces(MediaType.APPLICATION_JSON)
public Hello sayJsonHello() {
return new Hello("Hello", "Jersey");
}
#POST
#Produces(MediaType.APPLICATION_JSON)
public Hello createHello(Hello hello)
{
System.out.println("post");
return hello;
}
}'
currently I'm trying only with GET hitting the following url http://localhost:8080/RestFulWeb/hello, I am getting the 505 error.
DO i missed any jar files , but i didn't get any compile time error.
This is caused by the missing of asm.jar,
Add this dependency
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
While writing a webservice I was getting following error:
INFO: Scanning for root resource and provider classes in the packages:
com.webservice.services
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
at com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:79)
at com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104)
at com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:78)
at com.webservice.StartWebService.startAttrService(StartWebService.java:32)
at com.webservice.StartWebService.main(StartWebService.java:20)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.ClassVisitor
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 5 more
I included asm.jar in my java project and error gone.
I was following steps from restful-web-services-first-application-mock-service-using-pure-java
Related
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.
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 am trying to run java rest webservice program. constantly i am getting this error
Exception in thread "main" java.lang.NoClassDefFoundError: org/glassfish/hk2/api/ServiceLocatorFactory$CreatePolicy
at org.glassfish.jersey.internal.inject.Injections._createLocator(Injections.java:141)
at org.glassfish.jersey.internal.inject.Injections.createLocator(Injections.java:113)
at org.glassfish.jersey.server.internal.RuntimeDelegateImpl.<init>(RuntimeDelegateImpl.java:63)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at javax.ws.rs.ext.FactoryFinder.newInstance(FactoryFinder.java:117)
at javax.ws.rs.ext.FactoryFinder.find(FactoryFinder.java:165)
at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:135)
at javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:120)
at javax.ws.rs.core.UriBuilder.newInstance(UriBuilder.java:95)
at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
at co.test.RestClient.getBaseUri(RestClient.java:31)
at co.test.RestClient.main(RestClient.java:18)
Caused by: java.lang.ClassNotFoundException: org.glassfish.hk2.api.ServiceLocatorFactory$CreatePolicy
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 16 more
java classes are
Hello.java
package co.test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/hello")
public class Hello {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayStringHello(){
String Str="this is hello plain";
return Str;
}
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHTMLHello(){
String Str="<html><title>title</title><body><h1>hello from html</h1></body></html>";
return Str;
}
#GET
#Produces(MediaType.TEXT_XML)
public String sayXMLHello(){
String Str="<?xml version=\"1.0\"><title>title</title><body><h1>hello from html</h1></body>";
return Str;
}
}
RestClient.java
package co.test;
import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.jersey.client.ClientConfig;
public class RestClient {
public static void main(String[] args) {
ClientConfig config= new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target= client.target(RestClient.getBaseUri());
String plain=target.path("rest").path("hello").request().accept(MediaType.TEXT_PLAIN).get(String.class);
String html=target.path("rest").path("hello").request().accept(MediaType.TEXT_HTML).get(String.class);
String xml=target.path("rest").path("hello").request().accept(MediaType.TEXT_XML).get(String.class);
System.out.println(plain);
System.out.println(html);
System.out.println(xml);
}
private static URI getBaseUri(){
return UriBuilder.fromUri("http://localhost:8080/RestWSDemo/").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" 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>RestWSDemo</display-name>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>JerseyRestService</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>co.test</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JerseyRestService</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hello
</body>
</html>
and the jar files i am using are:
can anyone help me with this? thank you
I am trying to call my servlet GetAttributeValueServlet from apache tomcat and this error has been shown.
The Servlet is in CloudWebServerClient.
Severe: Servlet.service() for servlet [servlet.GetAttributeValueServlet] in context with path [/CloudWebServiceClient] threw exception
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.lang.NullPointerException
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}hostname
java.lang.NullPointerException
at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:796)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.client.service.WebServiceProxySoapBindingStub.getAttributeValue(WebServiceProxySoapBindingStub.java:297)
at com.client.service.WebServiceProxyProxy.getAttributeValue(WebServiceProxyProxy.java:50)
at servlet.GetAttributeValueServlet.doGet(GetAttributeValueServlet.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
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: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:100)
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:409)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
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" version="3.0">
<display-name>CloudWebServiceServer</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<display-name>GetAttributeValueServlet</display-name>
<servlet-name>GetAttributeValueServlet</servlet-name>
<servlet-class>com.src.servlet.GetAttributeValueServlet</servlet-class>
</servlet>
<servlet>
<display-name>Apache-Axis Servlet</display-name>
<servlet-name>AxisServlet</servlet-name>
<servlet-class>org.apache.axis.transport.http.AxisServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAttributeValueServlet</servlet-name>
<url-pattern>/CloudWebServiceClient/WebContent/GetAttributeValueServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/servlet/AxisServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>*.jws</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<servlet>
<display-name>Axis Admin Servlet</display-name>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>org.apache.axis.transport.http.AdminServlet</servlet-class>
<load-on-startup>100</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/servlet/AdminServlet</url-pattern>
</servlet-mapping>
</web-app>
GetAttributeValueServlet:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.client.service.WebServiceProxy;
import com.client.service.WebServiceProxyProxy;
/**
* Servlet implementation class GetAttributeValueServlet
*/
#WebServlet("/GetAttributeValueServlet")
public class GetAttributeValueServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetAttributeValueServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("text/xml;charset=utf-8");
String EntityID=request.getParameter("entity_id");
String AttrName=request.getParameter("attrName");
//String Value=request.getParameter("value");
System.out.println(EntityID+AttrName);
WebServiceProxy wsp = new WebServiceProxyProxy();
System.out.println("Huuu"); //just to see if it is coming to this point and yes it comes to this point and after that throws exception!
String isGet = wsp.getAttributeValue(EntityID, AttrName);
System.out.println("Hagfgfg"); //it doesn't shows this value!
PrintWriter pw = response.getWriter();
pw.print(isGet);
return;
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Before using values you pull from request.getParameter() you should check them to see if they are null and do something if they are.
String entityID = request.getParameter("entity_id");
if(entityID==null)
{
entityID = "";
//or maybe print a message to user "Entity ID is required field" and return;
}
Or you can make sure they're not null like this:
String entityID = "" + request.getParameter("entity_id");
This would mean if what comes out of request.getParameter() was null, now it will be the String value "null" rather than null.
I resolved it.... The problem was in parameter attrName which was Null and it was because of wrong function call ;) thanx anyways
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);
}