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
解决方案
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:
com.sun.jersey
jersey-server
1.8
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:
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">
Restful Web Application
jersey-serlvet
com.sun.jersey.spi.container.servlet.ServletContainer
com.sun.jersey.config.property.packages
com.test.rest
1
jersey-serlvet
/rest/*
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