pom.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.what21.demo
jersey
war
0.0.1-SNAPSHOT
jersey Maven Webapp
http://maven.apache.org
1.19
4.1.4.RELEASE
junit
junit
4.4
test
com.sun.jersey
jersey-core
${jersey.version}
com.sun.jersey
jersey-server
${jersey.version}
com.sun.jersey
jersey-json
${jersey.version}
com.sun.jersey.contribs
jersey-spring
${jersey.version}
org.springframework
spring-core
org.springframework
spring-context
org.springframework
spring-web
org.springframework
spring-beans
org.springframework
spring-aop
org.springframework
spring-core
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-beans
${spring.version}
jersey
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
1.8
web.xmlweb-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
Archetype Created Web Application
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
JerseySpringServlet
com.sun.jersey.spi.spring.container.servlet.SpringServlet
com.sun.jersey.config.property.packages
com.what21.demo.jersey.rest
com.sun.jersey.api.json.POJOMappingFeature
true
1
JerseySpringServlet
/rest/*
User.javapackage com.what21.demo.jersey.domain;
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserServiceRest.javapackage com.what21.demo.jersey.rest;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Component;
import com.what21.demo.jersey.domain.User;
@Component //定义此类为spring组件,即bean类
@Path("/user")
public class UserServiceRest {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public User getUserById(@PathParam("id") int id) {
User user = new User(id, "张三");
return user;
}
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public List getUserList() {
List userList = new ArrayList();
userList.add(new User(1, "张三"));
userList.add(new User(2, "李四"));
userList.add(new User(2, "王五"));
return userList;
}
}
访问测试
http://127.0.0.1:8080/jersey-helloworld/rest/user/1
http://127.0.0.1:8080/jersey-helloworld/rest/user/list