博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用jersey + spring 实现rest服务及单元测试
阅读量:7260 次
发布时间:2019-06-29

本文共 5847 字,大约阅读时间需要 19 分钟。

jersey提供了强大的rest功能,可以通过简洁的标注和编码实现业务的需求,架构会透明的把你的pojo对象转化为客户端可以接受的json/xml文件模式,当然也可以用它做一些基于ajax的表单提交和下载功能,这里简单说下他在spirng中的设置

在pom中引入

 

com.sun.jersey
jersey-json
1.17.1
com.sun.jersey
jersey-core
1.17.1
org.codehaus.jackson
jackson-core-asl
1.9.13
com.sun.jersey.contribs
jersey-spring
1.17.1

 

在 web.xml里面配置,其中com.sun.jersey.config.property.packages属性设置我们的rest对外的业务类所在的包,本事例对外输出json为主,所以设置POJOMappingFeature 为true。url-parttern 和 org.codehaus.enunciate.modules.jersey.config.ServletPath 设置rest的url的前缀,例如下面的为127.0.0.1/rest/xxxxx

com.sun.jersey.spi.spring.container.servlet.SpringServlet 这个为jersey 在spring中的路由统一处理模块

 

jersey
com.sun.jersey.spi.spring.container.servlet.SpringServlet
com.sun.jersey.config.property.packages
mypackage.jersey.resource
com.sun.jersey.api.json.POJOMappingFeature
true
com.sun.jersey.spi.container.ContainerRequestFilters
com.sun.jersey.api.container.filter.PostReplaceFilter
org.codehaus.enunciate.modules.jersey.config.ServletPath
/rest
1
jersey
/rest/*

 

咱们在刚才定义的 com.sun.jersey.config.property.packages 里面写一个 rest服务类

 

import java.awt.PageAttributes.MediaType;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.core.Context;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.stereotype.Service;@Component@Path("/demo")@Produces({ "application/json" })public class DemoRest {        @GET    public DemoResult getDemo(@Context HttpServletRequest req) {        DemoResult dr = new DemoResult("test", 19);        return dr;    }    @GET    @Path("name/{name}")    public DemoResult getDemo1(@PathParam("name") String name) {        DemoResult dr = new DemoResult(name, 19);        return dr;    }}

其中 DemoResult 为:

public class DemoResult {    private String name;    private int age;    public DemoResult(String name, int age) {        this.name = name;        this.age = age;    }    }

 

启动服务后,运行 127.0.0.1/rest/demo  (对应getDemo)或者 127.0.0.1/rest/demo/name/hello (对应 getDemo1)就可以得到我们需要的json结果了

 

单元测试:

配置pom:

com.sun.jersey.jersey-test-framework
jersey-test-framework-core
1.17.1
com.sun.jersey.jersey-test-framework
jersey-test-framework-grizzly2
1.17.1

 

我们写一个测试基类,其中 mypackage.jersey.resource 为提供rest服务的类所在的包,例如上面的DemoRest所在的包。其他的配置和web.xml中jersey的配置参数一一对应

import javax.ws.rs.core.Application;import junit.framework.TestCase;import org.junit.BeforeClass;import org.junit.runner.RunWith;import org.springframework.web.context.ContextLoaderListener;import org.springframework.web.context.request.RequestContextListener;import org.unitils.database.annotations.Transactional;import org.unitils.spring.annotation.SpringApplicationContext;import org.unitils.UnitilsJUnit4TestClassRunner;import org.unitils.database.util.TransactionMode;import com.sun.jersey.spi.spring.container.servlet.SpringServlet;import com.sun.jersey.test.framework.WebAppDescriptor;public abstract class BaseJerseyServiceTest extends com.sun.jersey.test.framework.JerseyTest {    @Override    protected WebAppDescriptor configure() {        return  new WebAppDescriptor.Builder("mypackage.jersey.resource")        .contextParam( "contextConfigLocation", "classpath:JApplicationContext.xml")        .servletClass(SpringServlet.class)        .initParam("com.sun.jersey.api.json.POJOMappingFeature", "true")        .initParam("com.sun.jersey.spi.container.ContainerRequestFilters", "com.sun.jersey.api.container.filter.PostReplaceFilter")        .contextListenerClass(ContextLoaderListener.class)        .requestListenerClass(RequestContextListener.class)        .build();    }}

 

我们用这个测试类写一个测试用例的半成品,其中params是模拟的get/post参数.运行即可。例子中测试的是 /shopInfo/trend?type=pv 这个rest请求

 

public class ShopInfoTest extends BaseJerseyServiceTest {        private final static Logger logger = LoggerFactory            .getLogger(ShopInfoTest.class);    @Test    public void test() {        WebResource webResource = resource();        webResource.accept("application/json");        MultivaluedMap
params = new MultivaluedMapImpl(); params.add("type", "pv"); String response = webResource .path("/shopInfo/trend") .queryParams(params) .get(String.class); System.out.println(response.toString()); }}

 

 

转载于:https://www.cnblogs.com/wully/p/3337170.html

你可能感兴趣的文章
Nginx
查看>>
cf1056B. Divide Candies(数论 剩余系)
查看>>
手把手教你通过Ambari新建Hadoop集群图解案例
查看>>
关于flink的时间处理不正确的现象复现&原因分析
查看>>
探究 CSS 混合模式\滤镜导致 CSS 3D 失效问题
查看>>
99种用Racket说I love you的方式
查看>>
Combine Pixie Into Houdini
查看>>
ActiveX脚本宿主
查看>>
(原創) Verilog testbench建議的coding style (SOC) (Verilog)
查看>>
常见的英文面试问题
查看>>
信息系统开发平台OpenExpressApp:OpenTest 之 运行环境准备
查看>>
派生类的构造函数
查看>>
怎样玩转千万级别的数据
查看>>
jquery tmpl 详解
查看>>
【转】fatal error C1189: #error : missing -D__STDC_CONSTANT_MACROS / #define __STDC_CONSTANT_MACROS...
查看>>
linux达人养成计划学习笔记(六)—— 挂载命令
查看>>
分享一个实用的String的工具类
查看>>
QTP的那些事---时间格式转换函数
查看>>
Hibernate:1对1关系总结。
查看>>
hdu 1059 Dividing
查看>>