1

RESTEasy是JBoss的开源项目之一,是一个RESTful Web Services框架。

趁今天有空,学习一下RESTEasy。看了两篇博客后,自己写了一个demo。

1. 新建一个maven的web项目。

clipboard.png

  • 依赖如下:

    <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.fengyuan</groupId>
    <artifactId>RESTEasyDemo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>RESTEasyDemo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.14.4</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.3.GA</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson-provider</artifactId>
            <version>2.2.3.GA</version>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    </project>
    

2. 接着创建两个服务,messageservice和userservice:

  • UserService.java:

    package com.fengyuan.restapi;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    
    import com.fengyuan.domain.User;
    
    @Path("userservice") // 服务路径
    public class UserService {
        /**
         * 初始化三个用户数据,存入map中,key为用户id,value为用户对象
         */
        static Map<Integer, User> userMap = new HashMap<>();
        static {
            User user1 = new User("Lee", 24, "138***");
            userMap.put(1, user1);
            User user2 = new User("Cathy", 25, "188***");
            userMap.put(2, user2);
            User user3 = new User("Aaron", 26, "186***");
            userMap.put(3, user3);
        }
    
        /**
         * 获取指定id的用户
         * 
         * @param id
         * @return
         */
        @GET
        @Path("user/{id}") // 具体服务的路径, id是入参
        @Produces("application/json") // 返回的格式
        public User getById(@PathParam("id") Integer id) {
            return (User) userMap.get(id);
        }
    
        /**
         * 以json格式返回所有用户
         * 
         * @return
         */
        @GET
        @Path("users")
        @Produces("application/json")
        public List<User> getUsers() {
            List<User> userList = new ArrayList<User>();
            for (Entry<Integer, User> user : userMap.entrySet()) {
                userList.add(user.getValue());
            }
            return userList;
        }
    }
  • MessageService.java:

    package com.fengyuan.restapi;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;  
    import javax.ws.rs.PathParam;  
    import javax.ws.rs.core.Response;  
       
    @Path("/messageservice")  
    public class MessageService {  
       public MessageService(){} 
        @GET 
        @Path("/{param}")  
        public Response printMessage(@PathParam("param") String msg) {  
            String result = "Hello : " + msg;  
       
            return Response.status(200).entity(result).build();  
        }  
    } 

    User.java:

    package com.fengyuan.domain;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    
    public @Data @AllArgsConstructor class User {
        private String name;
        private int age;
        private String tel;
    }
    

3. 配置web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Restful Web Application</display-name>
  <context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>true</param-value>
  </context-param>
  <!-- <context-param>
    <param-name>resteasy.resources</param-name>
    <param-value>com.fengyuan.restapi.MessageService, com.fengyuan.restapi.UserService</param-value>
  </context-param> -->
  <context-param>
    <param-name>resteasy.servlet.mapping.prefix</param-name>
    <param-value>/rest</param-value>
  </context-param>
  <listener>
    <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
  </listener>
  <servlet>
    <servlet-name>resteasy-servlet</servlet-name>
    <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>resteasy-servlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

配置resteasy.scan为true表示自动扫描服务。如果不配置,也可以手动指定resteasy.resources,见注释掉的部分。

4. 启动tomcat,在浏览器输入服务的url:

clipboard.png

clipboard.png

clipboard.png

5. 除了可以在浏览器直接访问之外,也可以用代码调用:

package com.fengyuan.test;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import junit.framework.TestCase;  
  
public class TestUserAPI extends TestCase {  
    public static final String USER_API =   
        "http://127.0.0.1:8080/resteasy-demo/rest/userservice/users";  
  
    public void testCreateUserAndGetUser() throws IOException {  
        URL url =   
            new URL(USER_API);  
        HttpURLConnection connection =   
            (HttpURLConnection) url.openConnection();  
        connection.setRequestMethod("GET");  
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
        connection.setConnectTimeout(1000);  
  
        byte[] bytes = new byte[1024];
        //读取请求返回值
        InputStream inStream=connection.getInputStream();
        inStream.read(bytes, 0, inStream.available());
        System.out.println(new String(bytes, "utf-8"));
        
        connection.disconnect();  
    }  
} 
  • 控制台输出:

    [{"name":"Lee","tel":"138***","age":24},{"name":"Cathy","tel":"188***","age":25},{"name":"Aaron","tel":"186***","age":26}]

当然,这里只是简单了测试了GET类型的服务,还有POST等类型的服务等有空了再补充。

另外,我在写这个demo项目的时候,发现如果使用了2.1.多版本的resteasy-jackson-provider和resteasy-jaxrs包,并且在web.xml中配置了resteasy.scan为true的话,会出一些问题,这边提醒一下,让看这篇博文的同学不用再踩进这个坑~。


风鸢
182 声望15 粉丝

biu biu biu