【jersey】 spring 整合jersey 实现RESTful webservice

时间:2022-11-02 19:32:33
     Jersey是一个RESTFUL请求服务JAVA框架,与常规的JAVA编程使用的struts框架类似,它主要用于处理业务逻辑层。与Struts类似,它同样可以和hibernate,spring框架整合。
由于Struts2+hibernate+spring整合在市场的占有率太高,所以很少一部分人去关注Jersey。所以网上有关于Jersey的介绍很少。但是它确实是一个非常不错的框架。对于请求式服务,对于GET,DELETE请求,你甚至只需要给出一个URI即可完成操。
 
jar 文件依赖:
<properties>

    <jersey.version>2.22.1</jersey.version>
    <spring.version>4.1.6.RELEASE</spring.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.glassfish.jersey.ext</groupId>
      <artifactId>jersey-spring3</artifactId>
      <version>${jersey.version}</version>
      <!-- <exclusions>
          <exclusion>
              <groupId>org.springframework</groupId>
              <artifactId>spring-core</artifactId>
          </exclusion>
          <exclusion>
              <groupId>org.springframework</groupId>
              <artifactId>spring-web</artifactId>
          </exclusion>
          <exclusion>
              <groupId>org.springframework</groupId>
              <artifactId>spring-beans</artifactId>
          </exclusion>
            <exclusion>
              <groupId>org.springframework</groupId>
              <artifactId>spring-tx</artifactId>
          </exclusion>

            <exclusion>
              <groupId>org.springframework</groupId>
              <artifactId>spring-context</artifactId>
          </exclusion>
           <exclusion>
              <groupId>org.springframework</groupId>
              <artifactId>spring-context-support</artifactId>
          </exclusion>
      </exclusions>             -->
    </dependency>
    <dependency>
      <groupId>org.glassfish.jersey.media</groupId>
      <artifactId>jersey-media-json-jackson</artifactId>
      <version>${jersey.version}</version>
    </dependency>

    <dependency>
      <groupId>org.glassfish.jersey.ext</groupId>
      <artifactId>jersey-mvc</artifactId>
      <version>${jersey.version}</version>
    </dependency>

    <dependency>
      <groupId>org.glassfish.jersey.core</groupId>
      <artifactId>jersey-client</artifactId>
      <version>${jersey.version}</version>
    </dependency>
    <!--servlet-->


    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.7</version>
    </dependency>

    <!-- Druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.13</version>
    </dependency>

    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- MySQL Driver -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>

    <!-- MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>
  </dependencies>

web.xml:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
    <filter-name>jersey</filter-name>
    <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.xwolf.jersey</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>org.glassfish.jersey.server.mvc.jsp.JspMvcFeature</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.mvc.templateBasePath.jsp</param-name>
        <param-value>/</param-value>
    </init-param>
    <init-param>
       <param-name>jersey.config.servlet.filter.staticContentRegex</param-name>
       <param-value>/.*jsp</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>jersey</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd   
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
    
    <!-- 激活annotation功能 -->
     <context:component-scan base-package="com.xwolf" />
    
 
 <!-- 实例化占位符对象,加载数据库配置信息 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath*:db.properties</value>
              </list>
        </property>
    </bean>

    <!-- 配置数据源,并设置连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 设置数据库连接参数 -->
        <property name="url" value="${url}" />
        <property name="driverClassName" value="${driverClassName}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 设置连接池参数 -->
        <property name="initialSize" value="${initSize}" />
        <property name="maxActive" value="${maxSize}" />
        <property name="filters" value="stat" />
    </bean>
    
    
    
    <!-- 整合Mybatis框架 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:spring-mybatis.xml" />
        <property name="dataSource" ref="dataSource" />
         <property name="mapperLocations">
         <list>
         <value>classpath:com/xwolf/jersey/mapper/*.xml</value>
         </list>
         </property>
    </bean>
  
    <!-- 配置扫描dao接口 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xwolf.jersey.dao"></property>
    </bean>
    
 <!-- 注入dataSource -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource"></property>
     </bean>
    
    <!-- 启用事务 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager" >
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="query*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="load*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!-- AOP代理设置 -->
    <aop:config proxy-target-class="true">
        <aop:advisor pointcut="execution(* com.xwolf.jersey.service..*.*(..))" advice-ref="txAdvice" />
    </aop:config>
 
</beans>

User.java:

package com.xwolf.jersey.bean;

import java.util.Date;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {
    
    private Long uid;
    private String name ;
    private String pwd;
    
    
    private Date birth;
    
    @XmlElement
    public Long getUid() {
        return uid;
    }
    public void setUid(Long uid) {
        this.uid = uid;
    }
    
    @XmlElement
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    
    @XmlElement
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    
    @XmlElement
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    @Override
    public String toString() {
        return "User [uid=" + uid + ", name=" + name + ", pwd=" + pwd
                + ", birth=" + birth + "]";
    }
    

}

userController.java;

package com.xwolf.jersey.controller;

import java.io.IOException;
import java.util.Date;

import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.xwolf.jersey.bean.User;
import com.xwolf.jersey.service.UserService;

@Controller
@Singleton
@Path("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    /**
     * 返回字符串
     * @return
     */
    @GET
    @Path("/str")
    @Produces(MediaType.TEXT_PLAIN)
    public String str(){
        return "Hello,Jersey !";
    }
    
    /**
     * 返回xml
     * @return
     */
    @GET
    @Path("/getXml")
    @Produces(MediaType.APPLICATION_XML)
    public User getUserXml(){
        User user =new User();
        user.setUid(234234l);
        user.setName("隔壁老王");
        user.setPwd("rwerwe");
        user.setBirth(new Date());
        return user;
    }
    
    @GET
    @Path("/getJson")
    @Produces(MediaType.APPLICATION_JSON)
    public User getUserJson(){
        User user =new User();
        user.setUid(234234l);
        user.setName("隔壁老王");
        user.setPwd("rwerwe");
        user.setBirth(new Date());
        return user;
    }
    
    
    /**
     * 用户注册
     * @param uname
     * @param pwd
     * @return
     */
    @POST
    @Path("/register")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public String register(@FormParam(value = "uname") String uname,
            @FormParam(value="pwd")String pwd){
        User user = new User();
        user.setName(uname);
        user.setPwd(pwd);
        user.setBirth(new Date());
        JSONObject object = new JSONObject();
        try {
            userService.add(user);
            object.put("success", true);
            object.put("msg", "注册成功!");
        } catch (Exception e) {
            object.put("success", false);
            object.put("msg", "注册失败了!");
            e.printStackTrace();
        }
        return object.toJSONString();
    }
    

    
    
   

}

form.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册</title>
</head>
<body>


  <form action="${pageContext.request.contextPath}/user/register" method="POST" >
  
  <table>
  <tr>
  <td>用户名:</td>
  <td><input name="uname"></td>
  </tr>
  
  <tr>
  <td>密码:</td>
  <td><input name="pwd"></td>
  </tr>
  
  
  <tr>
  <td><input type="submit" value="注册"></td>
  </tr>
  
  </table>
  
  </form>

</body>
</html>

附录:

jersey常用注解解释
Annotation 作用 说明
@GET 查询请求 相当于数据库的查询数据操作
@POST 插入请求 相当于数据库的插入数据操作
@PUT 更新请求 相当于数据库的更新数据操作
@DELETE 删除请求 相当于数据的删除数据操作
@Path uri路径 定义资源的访问路径,client通过这个路径访问资源。比如:@Path("user")
@Produces 指定返回MIME格式 资源按照那种数据格式返回,可取的值有:MediaType.APPLICATION_XXX。比如:@Produces(MediaType.APPLICATION_XML)。即将要返回给client端的数据标识类型(MIME)。@Produces可以作为class注释,也可以作为方法注释,方法的@Produces注释将会覆盖class的注释。
@Consumes 接受指定的MIME格式 只有符合这个参数设置的请求才能访问到这个资源。比如@Consumes("application/x-www-form-urlencoded")。即用来指定可以接受client发送过来的MIME类型,同样可以用于class或者method,也可以指定多个MIME类型,一般用于@PUT@POST 
@PathParam uri路径参数 可以获取URI中指定规则的参数。写在方法的参数中,获得请求路径参数。比如:@PathParam("username")  String userName。
@QueryParam uri路径请求参数 用于获取GET请求中的查询参数。写在方法的参数中,获得请求路径附带的参数。比如:@QueryParam("desc")  String desc
@DefaultValue 设置@QueryParam参数的默认值 如果@QueryParam没有接收到值,就使用默认值。比如:@DefaultValue("description") @QueryParam("desc") String desc
@FormParam form传递的参数 接受form传递过来的参数。比如:@FormParam("name")  String userName
@BeanParam 通过Bena的形式传递参数 接受client传递的bean类型的参数,同时这个bean可以在属性上配置@FormParam用以解决client的属性名称和bean的属性名称不一致的问题。比如:@BeanParam  User user
@Context 获得一些系统环境信息 通过@Context可以获得以下信息:UriInfo、ServletConfig、ServletContext、HttpServletRequest、HttpServletResponse和HttpHeaders等
@XmlRootElement 将bean转换为xml 如果要讲bean以xml或json的格式返回,必须要这个注解。比如:

@XmlRootElement

public class User{...}

@XmlElements
 
 
@XmlElement
 
 
HTTP Methods
  GET 请求
读取/列出/检索单个或资源集合。使用 WebResource 类的 get() 方法来提交一个 HTTP GET请求到 Web 资源,String s = webResource.get(String.class); 这表示如果 WebResource 对象的 URL 是 http://localhost:8000/restful/services/restresource/getUser,那么一个 HTTP GET 请求将会发送到地址为  http://localhost:8000/restful/services/restresource/getUser 的资源
PUT 请求

更新现有资源或资源集合。 使用 WebResource 类的 put() 方法来提交一个 HTTP PUT 请求到 Web 资源。例如下面的代码展示了请求发送一个文本实体 foo:bar 到指定的 Web 资源:

ClientResponse response = webResource.type("text/plain").put(ClientResponse.class, "foo:bar");      

同样,你也可以在使用 put() 方法发送请求时指定查询参数,方法与使用 get() 方法时指定查询参数一样

  POST 请求
新建资源.一个 POST 请求相当于一个 GET 请求和一个 PUT 请求的综合,也就意味着,你可以使用 POST 请求来发送一个实体到指定的 Web 资源并且接收另一个实体。使用 WebResource 类的 post() 方法来发送一个 HTTP POST 请求到指定的 Web 资源。
 DELETE 请求
删除资源或资源集合。使用 WebResource 类的 delete() 方法来发送一个 HTTP DELETE 请求到指定的 Web 资源。

 

 

参考资料:

Jersey 2.22.1 User Guide

使用 Jersey 和 Apache Tomcat 构建 RESTful Web 服务

 Jersey+Spring:解决Jersey单实例问题 

jersey+spring+maven入门