搭建项目
https://jersey.java.net/documentation/latest/getting-started.html#new-webapp
Creating a JavaEE Web Application
mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-webapp \
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \
-DgroupId=com.example -DartifactId=simple-service-webapp -Dpackage=com.example \
-DarchetypeVersion=2.25.1
controlers
package com.example.controlers;
import com.example.model.Role;
import com.example.model.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.ArrayList;
/**
* Root resource (exposed at "myresource" path)
*/
@Path("user")
public class UserControler {
@Context UriInfo uriInfo;
@Context HttpHeaders httpHeaders;
@Context SecurityContext sc;
@Context Request req;
@Context Response resp;
@Context HttpServletRequest request;
@Context HttpServletResponse response;
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList getUserList() {
ArrayList list=new ArrayList();
response.addHeader("aa","bb");
User user = new User("userid","username",20);
list.add(user);
if(user==null){
throw new NotFoundException("No such User.");
}
return list;
}
@GET
@Path("get")
@Produces(MediaType.APPLICATION_JSON)
public User getUser(String id) {
User user = new User("userid","username",20);
if(user==null){
throw new NotFoundException("No such User.");
}
return user;
}
@POST
@Path("save")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public User saveUser(@QueryParam("id") String id, @BeanParam User user) {
user.setUserAge(Integer.parseInt(id));
return user;
}
@POST
@Path("delete")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void deleteUser(@QueryParam("id") String id, @BeanParam User user) {
}
@GET
@Path("role")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList getRoleListByUserId(@QueryParam("userId") String userId) {
ArrayList list=new ArrayList();
response.addHeader("aa","bb");
Role role = new Role();
role.setRole_name("车队");
list.add(role);
Role role2 = new Role();
role2.setRole_name("管理员");
list.add(role2);
return list;
}
}
web.xml
javax.ws.rs.Application
com.example.app_start.WebApiConfig
Jersey Web Application
org.glassfish.jersey.servlet.ServletContainer
0
Jersey Web Application
/rest/*
pom.xml
4.0.0
com.example
simple-service-webapp
war
1.0-SNAPSHOT
simple-service-webapp
simple-service-webapp
org.apache.maven.plugins
maven-compiler-plugin
2.5.1
true
1.7
org.glassfish.jersey
jersey-bom
${jersey.version}
pom
import
org.glassfish.jersey.containers
jersey-container-servlet-core
org.glassfish.jersey.media
jersey-media-moxy
javax.servlet
servlet-api
2.5
2.25.1
UTF-8
simple-service-webapp.iml
WebApiConfig.java
package com.example.app_start;
import com.example.controlers.UserControler;
import org.glassfish.jersey.server.ResourceConfig;
import purple.web.webapi.filter.*;
import purple.web.webapi.interceptor.*;
public class WebApiConfig extends ResourceConfig {
public WebApiConfig() {
//想让jersey托管的部分需要加入扫描,或者使用register指定托管类也可以
//packages("com.example","ccom.example");
//加载Resource
register(UserControler.class);
//注册数据转换器
//register(JacksonJsonProvider.class);
// 注册过滤器.
register(RequestFilter.class);
//注册拦截器
register(GzipInterceptor.class);
}
}
RequestFilter
package purple.web.webapi.filter;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
//import com.lgy.bean.Result;
//import com.lgy.utils.JsonUtils;
public class RequestFilter implements ContainerRequestFilter {
@Context HttpServletRequest request;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Result result = new Result<>();
System.out.println("aaaaaaa test");
System.err.println(requestContext);
//.....
// result.success("aaaaaaaa");
// requestContext.abortWith(Response.status(Response.Status.OK).entity(JsonUtils.modelToJson(result)).build());
}
}
GzipInterceptor
package purple.web.webapi.interceptor;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
public class GzipInterceptor implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context)
throws IOException, WebApplicationException {
MultivaluedMap headers = context.getHeaders();
headers.add("Content-Encoding", "gzip");
String ContentType = context.getMediaType().toString();
headers.add("Content-Type",ContentType+";charset=utf-8");//解决乱码问题
final OutputStream outputStream = context.getOutputStream();
context.setOutputStream(new GZIPOutputStream(outputStream));
context.proceed();
System.out.println("GZIP拦截器压缩");
}
}
model
package com.example.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Role {
private String role_name;
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
}
package com.example.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
private String userId;
private String userName;
private int userAge;
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public User(){
}
public User(String userId, String userName, int userAge) {
this.userId = userId;
this.userName = userName;
this.userAge = userAge;
}
//getter&setter
}
index.jsp
Jersey RESTful Web Application!