jersey使用

Jersey使用

一、            环境

1.         Tomcat6

2.         Jdk1.7

3.         Jersey  https://jersey.java.net/download.html  下载jaxrs-ri-2.22.1.zip

二、            过程

1.         创建myeclipse创建web项目

2.         解压jaxrs-ri-2.22.1.zip,将加压包中apiextlib目录下的jar包添加到类路径

3.         创建HelloResource.class 位于com.jersey.test包中

package com.jersey.test;

 

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import javax.ws.rs.GET;

import javax.ws.rs.POST;

import javax.ws.rs.Path;

import javax.ws.rs.PathParam;

import javax.ws.rs.Produces;

import javax.ws.rs.core.Context;

import javax.ws.rs.core.MediaType;

@Path("/hello"

publicclass HelloResource { 

    @GET 

    @Produces(MediaType.TEXT_PLAIN

   public String sayHello() { 

        return"Hello World!"

   

    @GET 

    @Path("/{param}")   

    @Produces("text/plain;charset=UTF-8"

    public String sayHelloToUTF8(@PathParam("param") String username) { 

        return"Hello " + username; 

    }

}

4.         修改web.xml,添加基于Servlet-的部署

<servlet>    

    <servlet-name>Way REST Service</servlet-name>  

 <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>  

      <init-param>    

    <param-name>jersey.config.server.provider.packages</param-name>  

        <param-value>com.jersey.test</param-value>  

       </init-param>  

   <load-on-startup>1</load-on-startup>  

 </servlet>  

   

 <servlet-mapping>  

   <servlet-name>Way REST Service</servlet-name>  

   <url-pattern>/rest/*</url-pattern>  

 </servlet-mapping>

5.         将项目部署到tomcat

6.         访问http://localhost:8080/TestJersey/rest/hello  浏览器输出Hello World!

三、            Xml对象的输出

1.         创建User对象getset方法省略

package com.jersey.dto;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement 

publicclass User {

  private String userId;

  private String name;

  private String age;

  public User() {

     super();

  }

  public User(String userId, String name, String age) {

      super();

      this.userId = userId;

      this.name = name;

      this.age = age;

  }

}

该类上面增加了一个注解“@XmlRootElement”,在将该类转化成XML时,说明这个是XML的根节点

2.         创建UserResource 

              package com.jersey.test;

               import com.jersey.dto.User;

              @Path("/users"

              publicclass UserResource {

      privatestatic Map<String,User> userMap  = new         HashMap<String,User>();

   @GET 

   @Path("/getUserXml"

   @Produces(MediaType.APPLICATION_XML

    public User getUserXml() { 

       User user  = new User(); 

       user.setAge("21"); 

       user.setUserId("004"); 

       user.setName("Amand"); 

       return user; 

  }

}

3.         访问

            访问http://localhost:8080/TestJersey/rest/users/getUserXml 返回
               <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
               <user><age>21</age><name>Amand</name>
               <userId>004</userId></user>

四、            json对象的输出

1.         在项目com.jersey.test.UserResource类中添加如下代码

    @GET   

    @Path("/getUserJson")   

    @Produces(MediaType.APPLICATION_JSON)   

    public User getUserJson() {   

     User user  = new User();   

     user.setAge("27");   

     user.setUserId("005");   

     user.setName("Fmand");   

     return user;   

    }

2.         添加json支持

 

访问http://localhost:8080/TestJersey/rest/users/getUserJson

此时期望获取到json的数据,但是项目报错

此时,需要获取json转换包的支持

可以由多种方式实现:MOXyJSON-PJacksonJettison等,本例为Jackson

 jackson-all-1.9.11.jar 下载地址http://wiki.fasterxml.com/JacksonDownload

 项目中引入jackson-all-1.9.11.jar

“com.jersey.test.util”目录下创建RestApplication.java

package com.jersey.test.util;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

import org.glassfish.jersey.server.ResourceConfig;

publicclass RestApplication extends ResourceConfig { 

    public RestApplication() { 

     //服务类所在的包路径  

     packages("com.jersey.test"); 

     //注册JSON转换器  

     register(JacksonJsonProvider.class); 

   

}

修改 web.xml

<?xml version="1.0" encoding="UTF-8"?>

<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">

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

 

  <servlet>   

    <servlet-name>Way REST Service</servlet-name> 

 <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 

<!--      <init-param>    -->

<!--        <param-name>jersey.config.server.provider.packages</param-name>  -->

<!--        <param-value>com.jersey.test</param-value>  -->

<!--       </init-param>  -->

 

      <init-param> 

           <param-name>javax.ws.rs.Application</param-name> 

           <param-value>

              com.jersey.test.util.RestApplication

           </param-value> 

       </init-param>

   <load-on-startup>1</load-on-startup> 

 </servlet> 

  

 <servlet-mapping> 

   <servlet-name>Way REST Service</servlet-name> 

   <url-pattern>/rest/*</url-pattern> 

 </servlet-mapping>

</web-app>

3.         访问

http://localhost:8080/TestJersey/rest/users/getUserJson

返回{"userId":"005","name":"Fmand","age":"27"}

五、            Jersey客户端使用

1.         创建客户端

新建java项目命名为JerseyClient,和服务端一样将压缩包中apiextlib目录下的jar包添加到类路径,将服务端的User对象添加到客户端项目中(报名,类名一致)

package com.jersey.client;

import javax.ws.rs.client.Client;

import javax.ws.rs.client.ClientBuilder;

import javax.ws.rs.client.Entity;

import javax.ws.rs.client.WebTarget;

import javax.ws.rs.core.MediaType;

import javax.ws.rs.core.Response;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

import com.jersey.dto.User;

publicclass TestClient {

     privatestatic String serverUri = "http://localhost:8080/TestJersey/rest"

        publicstaticvoid main(String[] args) { 

            addUser(); 

            getAllUsers(); 

            updateUser(); 

            getUserById(); 

            getAllUsers(); 

            delUser(); 

            getAllUsers(); 

     

        } 

        /**

         * 添加用户

         */ 

         privatestaticvoid addUser() { 

             System.out.println("****增加用户addUser****"); 

             User user = new User("006","Susan","21");   

             Client client = ClientBuilder.newClient();

             WebTarget target = client.target(serverUri + "/users"); 

             Response response = target.request().buildPost

           (Entity.entity(user, MediaType.APPLICATION_XML))

           .invoke(); 

             response.close(); 

        } 

          

        /**

         * 删除用户

         */ 

         privatestaticvoid delUser() { 

             System.out.println("****删除用户****"); 

             Client client = ClientBuilder.newClient(); 

             WebTarget target = client.target(serverUri + "/users/006"); 

             Response response = target.request().delete(); 

             response.close(); 

        } 

          

          

        /**

         * 修改用户

         */ 

         privatestaticvoid updateUser() { 

             System.out.println("****修改用户updateUser****"); 

             User user = new User("006","Susan","33");   

             Client client = ClientBuilder.newClient(); 

             WebTarget target = client.target(serverUri + "/users"); 

             Response response = target.request().

           buildPut( Entity.entity(user,

           MediaType.APPLICATION_XML)).invoke(); 

             response.close(); 

        } 

        /**

         * 根据id查询用户

         */ 

         privatestaticvoid getUserById() { 

             System.out.println("****根据id查询用户****"); 

             Client client = ClientBuilder.newClient().

           register(JacksonJsonProvider.class);// 注册json支持  

             WebTarget target = client.target(serverUri + "/users/006"); 

             Response response = target.request().get(); 

             User user = response.readEntity(User.class); 

             System.out.println(user.getUserId() +

           user.getName()  +  user.getAge()); 

             response.close(); 

        } 

        /**

         * 查询所有用户

         */ 

         privatestaticvoid getAllUsers() { 

             System.out.println("****查询所有getAllUsers****"); 

             Client client = ClientBuilder.newClient(); 

             WebTarget target = client.target(serverUri + "/users"); 

             Response response = target.request().get(); 

             String value = response.readEntity(String.class); 

            System.out.println(value); 

            response.close();  //关闭连接  

         } 

          

   

2.         总结

客户端如果需要进行JSON转换,需要进行JSON注册

Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);  

Client client = ClientBuilder.newClient().register

(JacksonJsonProvider.class);

WebTarget 指明了要请求的资源的地址

target.request(). 后面跟的是请求的方法:POSTGETPUTDELETE

 

六、            jersey文件上传

 

1.         页面文件上传

jsp中添加如下代码

<form action="http://localhost:8080/TestJersey/rest/hello/upload" method="post" enctype="multipart/form-data">

       名字:<input type="text" name="name"/><br/>

       文件:<input type="file" name="file"/><br/>

       <input type="submit" name="subBtn" value="发送">

    </form>

必须设置enctype="multipart/form-data",会将内容以二进制传输,否则作为字符串传输

后端调用方法

@Path("/upload")

    @POST

    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML,

       MediaType.TEXT_PLAIN })

    public String traceUserAction1(@Context HttpServletRequest request) {

       InputStream input = null;

       FileOutputStream output=null;

       String channel = request.getParameter("channel");

       System.out.println("channel = " + channel);

       try {

           input = request.getInputStream();

           output=new FileOutputStream("e://test.xls");//可替换为任何路径何和文件名

 

           int in=input.read();

           while(in!=-1){

           output.write(in);

           in=input.read();

           }

 

           String result=WebUtil.getBody(request);

           System.out.println(result);

       } catch (IOException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }finally{

          

              try {

                  if(null!=output){

                  output.flush();

                  output.close();

              }

              }catch (IOException e) {

                  System.out.println("关闭流异常" );

             

           }

       }

      

       return"";

    }

2.         使用工具上传

例如restclient-ui.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值