美文网首页java
Jersey 实现rest api笔记

Jersey 实现rest api笔记

作者: yaoshiyou | 来源:发表于2017-01-21 23:09 被阅读207次

    搭建项目

    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<User> getUserList() {
            ArrayList<User>  list=new ArrayList<User>();
            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<Role> getRoleListByUserId(@QueryParam("userId") String userId) {
            ArrayList<Role>  list=new ArrayList<Role>();
            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

    
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- This web.xml file is not required when using Servlet 3.0 container,
         see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <servlet>
            <init-param>
                <!--
                <param-name>jersey.config.server.provider.packages</param-name>
                <param-value>com.example</param-value>
                -->
    
                <param-name>javax.ws.rs.Application</param-name>
                <param-value>com.example.app_start.WebApiConfig</param-value>
    
            </init-param>
            <servlet-name>Jersey Web Application</servlet-name>
            <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
            <load-on-startup>0</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Jersey Web Application</servlet-name>
            <url-pattern>/rest/*</url-pattern>
        </servlet-mapping>
    </web-app>
    
    

    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" 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">
    
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.example</groupId>
        <artifactId>simple-service-webapp</artifactId>
        <packaging>war</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>simple-service-webapp</name>
    
        <build>
            <finalName>simple-service-webapp</finalName>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.5.1</version>
                    <inherited>true</inherited>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.glassfish.jersey</groupId>
                    <artifactId>jersey-bom</artifactId>
                    <version>${jersey.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey.containers</groupId>
                <artifactId>jersey-container-servlet-core</artifactId>
                <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
                <!-- artifactId>jersey-container-servlet</artifactId -->
            </dependency>
            <!--json输出支持-->
            <dependency>
                <groupId>org.glassfish.jersey.media</groupId>
                <artifactId>jersey-media-moxy</artifactId>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
        </dependencies>
        <properties>
            <jersey.version>2.25.1</jersey.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    </project>
    
    

    simple-service-webapp.iml

    <?xml version="1.0" encoding="UTF-8"?>
    <module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
      <component name="FacetManager">
        <facet type="web" name="Web">
          <configuration>
            <descriptors>
              <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/src/main/webapp/WEB-INF/web.xml" />
            </descriptors>
            <webroots>
              <root url="file://$MODULE_DIR$/src/main/webapp" relative="/" />
            </webroots>
          </configuration>
        </facet>
      </component>
      <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
        <output url="file://$MODULE_DIR$/target/classes" />
        <output-test url="file://$MODULE_DIR$/target/test-classes" />
        <content url="file://$MODULE_DIR$">
          <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
          <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
          <excludeFolder url="file://$MODULE_DIR$/target" />
        </content>
        <orderEntry type="inheritedJdk" />
        <orderEntry type="sourceFolder" forTests="false" />
        <orderEntry type="library" name="Maven: org.glassfish.jersey.containers:jersey-container-servlet-core:2.25.1" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.hk2.external:javax.inject:2.5.0-b32" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-common:2.25.1" level="project" />
        <orderEntry type="library" name="Maven: javax.annotation:javax.annotation-api:1.2" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.jersey.bundles.repackaged:jersey-guava:2.25.1" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-api:2.5.0-b32" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-utils:2.5.0-b32" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.hk2.external:aopalliance-repackaged:2.5.0-b32" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-locator:2.5.0-b32" level="project" />
        <orderEntry type="library" name="Maven: org.javassist:javassist:3.20.0-GA" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.hk2:osgi-resource-locator:1.0.1" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-server:2.25.1" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-client:2.25.1" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-jaxb:2.25.1" level="project" />
        <orderEntry type="library" name="Maven: javax.validation:validation-api:1.1.0.Final" level="project" />
        <orderEntry type="library" name="Maven: javax.ws.rs:javax.ws.rs-api:2.0.1" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-moxy:2.25.1" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish.jersey.ext:jersey-entity-filtering:2.25.1" level="project" />
        <orderEntry type="library" name="Maven: org.eclipse.persistence:org.eclipse.persistence.moxy:2.6.0" level="project" />
        <orderEntry type="library" name="Maven: org.eclipse.persistence:org.eclipse.persistence.core:2.6.0" level="project" />
        <orderEntry type="library" name="Maven: org.eclipse.persistence:org.eclipse.persistence.asm:2.6.0" level="project" />
        <orderEntry type="library" name="Maven: org.glassfish:javax.json:1.0.4" level="project" />
        <orderEntry type="library" name="Maven: javax.servlet:servlet-api:2.5" level="project" />
      </component>
    </module>
    

    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<String> 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<String, Object> 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

    <html>
    <body>
    <h2>Jersey RESTful Web Application!</h2>
    
    <p><a href="rest/user/list?page=10&rows=10">rest/user/list?page=10&rows=10</a>
    <p><a href="rest/user/get?id=1">rest/user/get?id=1</a>
    <p><a href="rest/user/role?userId=100">user/role?userId=100</a>
    
    
    
    </body>
    </html>
    

    相关文章

      网友评论

        本文标题:Jersey 实现rest api笔记

        本文链接:https://www.haomeiwen.com/subject/wppnbttx.html