web.xml 配置
<servlet> <servlet-name>jerseyRestService</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.webservice.resfull</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>
实体类
package com.webservice.resfull; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("hello") public class HelloResource { @GET @Produces(MediaType.TEXT_PLAIN) public String sayHello() { return "hello,jersey"; } @GET @Path("hi") public String sayHiTo(@QueryParam("name") String name) { return "hello To " + name; } }
maven配置
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.17.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.17.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId> <version>1.17.1</version> </dependency>
测试:
浏览器输入
http://localhost:8080/xxx/rest/hello (其中xxx是你的项目名)
结果页面输出:hello,jersey
浏览器输入:
http://localhost:8080/xxx/rest/hello/hi?name=tom
结果页面输出:hello To tom
注意事项:
web.xml中com.webservice.resfull 是指你的java类的包路径