简介
目前jersey已经不流行,但一些老的项目还在使用,jersey和目前流行的spring boot还是有少许不同,特此记录。
搭建服务
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
配置类
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
packages("com.example.devp.web");
}
}
资源类(controller层)
@Component
public class UserResource {
private static Map<String, User> cache = new HashMap<>();
//原始方式
@POST
@Path("/simpleParam1")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Object simpleParam(@Context HttpServletRequest request) {
// http://localhost:8080/simpleParam?name=Tom&age=10
// 请求参数: name=Tom&age=10 (有2个请求参数)
// 第1个请求参数: name=Tom 参数名:name,参数值:Tom
// 第2个请求参数: age=10 参数名:age , 参数值:10
String id = request.getParameter("id");
String name = request.getParameter("name");//name就是请求参数名
User user = new User(id, name);
cache.put(id, user);
System.out.println("/simpleParam1 " + user);
return "OK";
}
参数映射
@QueryParam
接口
@POST
@Path("/simpleParam2")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Object simpleParam(@QueryParam("id") String id, @QueryParam("name") String name) {
User user = new User(id, name);
cache.put(id, user);
System.out.println("/simpleParam2 " + user);
return "OK";
}