Jetty + Jersey简单RESTful例子

工程pom文件


	4.0.0
	com.rest.demo
	demo-rest
	war
	0.0.1-SNAPSHOT
	demo-rest Maven Webapp
	http://maven.apache.org
	
		
			junit
			junit
			3.8.1
			test
		
		
			org.eclipse.jetty
			jetty-server
			9.3.8.v20160314
		
		
			org.eclipse.jetty
			jetty-servlet
			9.3.8.v20160314
		
		
			com.sun.jersey
			jersey-server
			1.19.1
		
		
			com.sun.jersey
			jersey-servlet
			1.19.1
		
	
	
		demo-rest
	


写一个JettyServer

package com.demo.jetty;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import com.sun.jersey.spi.container.servlet.ServletContainer;

public class JettyServer {

	private void start() throws Exception {
		int port = 8080;
		Server server = new Server(port);
		ServletContextHandler context = new ServletContextHandler(
				ServletContextHandler.SESSIONS);
		context.setContextPath("/");
		server.setHandler(context);
		ServletHolder sh = new ServletHolder(ServletContainer.class);
		sh.setInitParameter(
				"com.sun.jersey.config.property.resourceConfigClass",
				"com.sun.jersey.api.core.PackagesResourceConfig");
		sh.setInitParameter("com.sun.jersey.config.property.packages",
				"com.demo.rest");
		context.addServlet(sh, "/*");
		server.start();
	}

	public void stop() throws Exception {

	}

	public static void main(String[] args) throws Exception {
		JettyServer server = new JettyServer();
		server.start();
	}
}

写一个java resource类

package com.demo.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/welcome")
public class WelcomeResource {
	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String sayHello() {
		return "Welcome to Jersey world";
	}
} 

启动JettyServer,浏览器输入http://localhost:8080/welcome,结果如下图:

Jetty + Jersey简单RESTful例子_第1张图片


你可能感兴趣的:(Java)