码迷,mamicode.com
首页 > 其他好文 > 详细

利用Jersey构建REST之入门实例

时间:2016-03-20 19:34:21      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:

 

一、依赖包

  1、目录结构如下:

  技术分享

       2.对了,还需要引入junit.jar

二、服务端代码

package com.haha.manager;

import java.util.concurrent.atomic.AtomicLong;

public class User {
    
    private static AtomicLong seq = new AtomicLong(0);
    
    private Long id;

    private String name;
    
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
    
    User(){        
    }

    public User(String name, String sex) {
        this.id = seq.incrementAndGet();
        this.name = name;
        this.sex = sex;
    }

    public Long getId() {
        return id;
    }

    public void setId() {
        this.id = seq.incrementAndGet();
    }

    
    

}

 

package com.haha.jersey;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.haha.manager.User;
import com.jery.util.JsonMapper;

@Path("user")
public class UserResource {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("world")
    public String say(){
        return "helloWorld!";
    }
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("hook")
    public String hook(){
        return "hook!";
    }
    
    private static Map<Long,User> userMap=new HashMap<Long,User>();    
    
    
    @POST
    @Path("add")
    @Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public void creatUser(@FormParam("name") String name,
            @FormParam("sex") String sex){        
        try {
            
            User user=new User(name,sex);
            userMap.put(user.getId(), user);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }        
    }
    
    @DELETE
    @Path("{id}")
    public void deleteUser(@PathParam("id")Long id){
        userMap.remove(id);
    }
    
    @PUT
    @Path("update")
    @Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public void updateUser(@FormParam("id") String id,
            @FormParam("name") String name){
        User user=userMap.get(Long.valueOf(id));
        user.setName(name);
        userMap.put(Long.valueOf(id), user);
    }
    
    @GET
    @Path("{id}")
    @Produces({MediaType.APPLICATION_XML,MediaType.TEXT_PLAIN,MediaType.APPLICATION_JSON})
    public String findUserById(@PathParam("id") Long id){
        User user=userMap.get(id);
        String str="";
        try {
            str=JsonMapper.buildNormal().toJson(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
    
    @GET
    @Produces({MediaType.APPLICATION_XML,MediaType.TEXT_PLAIN,MediaType.APPLICATION_JSON})
    public String getUsers(){
        List<User> userList=new ArrayList<User>();
        userList.addAll(userMap.values());
        String str="";
        try {
            str=JsonMapper.buildNormal().toJson(userList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }


}

三、客户端代码

package com.haha.client;

import javax.swing.text.html.parser.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.junit.Test;

import com.jery.util.JsonMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class UserClient {
    private static String uri="http://127.0.0.1:8080/haha/rest";
    
    @Test
    public void addUser(){
        try {
            MultivaluedMap form=new MultivaluedMapImpl();
            form.add("name", "鲁智深");
            form.add("sex", "male");
            System.out.println(JsonMapper.buildNormal().toJson(form));
            WebResource resource=new Client().resource(uri+"/user/add");
            ClientResponse response = resource.type(MediaType.APPLICATION_FORM_URLENCODED).
                    post(ClientResponse.class, form);
            System.out.println(response.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }
    
    @Test
    public void delete(){
        try {
            WebResource resource=new Client().resource(uri).path("user/1");
            ClientResponse response=resource
                    .delete(ClientResponse.class);
            System.out.println(response.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void update(){
        try {            
            MultivaluedMap form=new MultivaluedMapImpl();
            form.add("id","2");
            form.add("name", "戴(●‘?‘●)鑫");
            form.add("sex", "male");            
            System.out.println(JsonMapper.buildNormal().toJson(form));
            WebResource resource=new Client().resource(uri+"/user/update");
            ClientResponse response = resource.type(MediaType.APPLICATION_FORM_URLENCODED)
                    .put(ClientResponse.class,form);
            System.out.println(response.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void findUser(){
        WebResource resource=new Client().resource(uri).path("user/1");
        ClientResponse response=resource.accept(MediaType.TEXT_PLAIN)
                .get(ClientResponse.class);
        System.out.println(response.getStatus());
        System.out.println(response.getEntity(String.class));
    }
    
    @Test
    public void getUsers(){
        WebResource resource=new Client().resource(uri).path("user");
        ClientResponse response=resource.accept(MediaType.TEXT_PLAIN)
                .get(ClientResponse.class);
        System.out.println(response.getStatus());
        System.out.println(response.getEntity(String.class));
    }

}

 

利用Jersey构建REST之入门实例

标签:

原文地址:http://www.cnblogs.com/shoubianxingchen/p/5299202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!