Reputation: 592
How to create simple webserver in Java using Eclipse, Tomcat and Jersey i.e steps to follow?
We are creating simple webserver using the below links:
but we got an error like this:
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
Upvotes: 1
Views: 6661
Reputation: 15908
Copy all your Jersey jars, including jersey-servlet-1.12.jar, in your lib folder. Look that you have included it in the build path.
Upvotes: 0
Reputation: 6487
Have maven running. Then run this command(press enter if it asks sth):
mvn archetype:generate -DgroupId=com.test.rest -DartifactId=test -DarchetypeArtifactId=maven-archetype-webapp
It will create you a simple webapp. Now create the source package as src/main/java/com/test/rest, and create a simple class as following with a name "test" in it:
package com.test.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("/test")
public class test{
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}
At that point you should get errors, resolve them by adding this dependency to your pom:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
you can run a dummy "mvn clean install" so that maven will download the repository and your errors will disappear.
Now, go to webapp/WEB-INF and configure your web.xml as follows:
<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>Restful Web Application</display-name>
<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>com.test.rest</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>
here we said which classes to be loaded and also gave a small prefix with "/rest". so your webservice will start with this prefix.
Now you are ready, build the app, and add the jar file under tomcat/webapps folder. when you run your tomcat you can reach to your webservice via:
(url_to_tomcat_server/jar_name/prefix_at_web_xml/prefix_at_java_rest_class/dummy_text_requested_byclass)
localhost:8080/test/rest/test/blabla
Note: tested and running
Upvotes: 3