jersey和spring集成配置使用

2024-05-26 12:32

本文主要是介绍jersey和spring集成配置使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

jersey 是基于Java的一个轻量级RESTful风格的Web Services框架。

官网

使用maven,在pom.xml中加入:

<!-- Jersey -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId><artifactId>jersey-client</artifactId><version>${jersey.version}</version>
</dependency>
<dependency><groupId>org.glassfish.jersey.containers</groupId><artifactId>jersey-container-servlet</artifactId><version>${jersey.version}</version>
</dependency>
<dependency><groupId>org.glassfish.jersey.media</groupId><artifactId>jersey-media-moxy</artifactId><version>${jersey.version}</version>
</dependency>
<dependency><groupId>org.glassfish.jersey.media</groupId><artifactId>jersey-media-multipart</artifactId><version>${jersey.version}</version>
</dependency>

当然必不可少的,也需要使用Java EE的支持:

<!-- JAVA EE -->
<dependency><groupId>javax</groupId><artifactId>javaee-api</artifactId><version>7.0</version><scope>provided</scope>
</dependency>

Jar包详解:

jersey-client 是jersey提供的客户端包,封装了一些客户端操作的类
jersey-container-servlet 是jersey的核心,服务端必备包
jersey-media-moxy 是定义了jersry支持的常用的数据格式,json,xml都包括其中
jersey-media-multipart 是jersey的上传文件的支持

配置

jersey 的使用,必须要有一个全局的配置类,这个类需满足以下条件:

  • @ApplicationPath 注解该类,并且在参数中指定相对路径
  • 继承 org.glassfish.jersey.server.ResourceConfig
  • 该类构造方法中设置jersey的配置,比如指定接口的包路径

如下:

@ApplicationPath("/")
public class RESTServiceConfig extends ResourceConfig {public RESTServiceConfig() {packages("web.rest");register(MultiPartFeature.class);}
}

GET

GET例子:

@GET
@Path("/thing")
public String get() {return "thing";
}

POST

POST例子:

@POST
@Path("/add")
public Boolean add(@FormParam("name") String name) {// TODO savereturn true;
}

Param

jersey中有几种常用的接收参数的注解:

  • @PathParam 接收链接中参数,如"/xxx/{name}/",@PathParm("name")
  • @QueryParam 接收链接中的普通参数,如"/xxx?name=ttt",@QueryParam("name")
  • @FormParm 接收post提交中的表单参数
  • @FormDataParm 上传文件接收文件参数

json

开发中,json已经常用到无处不在了,jersey对json的支持很好。接收json,需要使用@Consumes,注解指定解压方式:

@Consumes(MediaType.APPLICATION_JSON)

返回json需要使用@Produces注解,指定压缩方式:

@Produces(MediaType.APPLICATION_JSON)

文件上传

示例:

  @POST@Path("import-excel")@Consumes(MediaType.MULTIPART_FORM_DATA)@Produces(MediaType.APPLICATION_JSON)public ImportResultBean importForExcel(@FormDataParam("file") String fileString,@FormDataParam("file") InputStream fis,@FormDataParam("file") FormDataContentDisposition fileDisposition) {// TODOreturn ;}

文件下载

文件下载需要将Response对象的压缩方式,指定为:

@Produces(MediaType.APPLICATION_OCTET_STREAM)
原文链接:http://www.jianshu.com/p/15c32cb52da1
下面是使用案例:
<!-- jersey-spring: 包含了jersey-servlet/jersey-server/jersey-core等,同时还包含了spring相关依赖。 --><dependency>  <groupId>com.sun.jersey</groupId>  <artifactId>jersey-core</artifactId>  <version>${jersey.version}</version>  </dependency>  <dependency>  <groupId>com.sun.jersey</groupId>  <artifactId>jersey-server</artifactId>  <version>${jersey.version}</version>  </dependency>  <dependency>  <groupId>com.sun.jersey</groupId>  <artifactId>jersey-json</artifactId>  <version>${jersey.version}</version>  </dependency>  <dependency>  <groupId>com.sun.jersey</groupId>  <artifactId>jersey-servlet</artifactId>  <version>${jersey.version}</version>  </dependency>  <dependency>  <groupId>com.sun.jersey.contribs</groupId>  <artifactId>jersey-spring</artifactId>  <version>${jersey.version}</version>  <exclusions>  <exclusion>  <artifactId>spring-aop</artifactId>  <groupId>org.springframework</groupId>  </exclusion>  <exclusion>  <artifactId>spring-context</artifactId>  <groupId>org.springframework</groupId>  </exclusion>  <exclusion>  <artifactId>spring-beans</artifactId>  <groupId>org.springframework</groupId>  </exclusion>  <exclusion>  <artifactId>spring-web</artifactId>  <groupId>org.springframework</groupId>  </exclusion>  <exclusion>  <artifactId>spring-core</artifactId>  <groupId>org.springframework</groupId>  </exclusion>  </exclusions>  </dependency>  
web.xml文件配置:
<!-- restful webservices配置 --><servlet><servlet-name>jerseySpring</servlet-name><servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class><init-param><param-name>com.sun.jersey.config.property.packages</param-name><param-value>com.innotek.webservice</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>jerseySpring</servlet-name><url-pattern>/*</url-pattern></servlet-mapping>
实现类如下:
/*** Acestek.com.cn Inc.* Copyright (c) 2004-2016 All Rights Reserved.*/
package com.innotek.webservice;import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;import com.innotek.common.core.enums.ErrorCode;
import com.innotek.core.support.mq.QueueSender;
import com.innotek.model.parking.generator.ExtralBerthData;
import com.innotek.model.parking.generator.RequestData;
import com.innotek.model.parking.generator.ResponseData;
import com.innotek.util.DataAnalysisUtil;/*** 基于http协议的webservice接口**/
@Component
@Path("/parkingData")
public class ParkingDataService {private final Logger log = LogManager.getLogger(ParkingDataService.class);@Autowiredprivate QueueSender queueSender;/*** 泊位状态接收接口*/@Path("berthStatus")@POST@Produces(MediaType.TEXT_PLAIN)public String receiveBerthStatus(String message) {ResponseData response = null;try {RequestData requestData = DataAnalysisUtil.getRequest(message);//参数不正确if (null == requestData) {response = new ResponseData(ErrorCode.PARAM_ERROR.code, ErrorCode.PARAM_ERROR.msg,"0");return response.toString();}//验证接口名称、厂家id、接入idif (!DataAnalysisUtil.verifyParam(requestData)) {response = new ResponseData(ErrorCode.PARAM_ERROR.code, ErrorCode.PARAM_ERROR.msg,"0");return response.toString();}//签名不正确if (!DataAnalysisUtil.verifySign(requestData)) {response = new ResponseData(ErrorCode.SIGN_FAULT.code, ErrorCode.SIGN_FAULT.msg,"0");return response.toString();}//泊位信息数据ExtralBerthData extralBerthData = DataAnalysisUtil.getExtralBerthData(requestData.getData());//数据参数不正确if (extralBerthData == null) {response = new ResponseData(ErrorCode.PARAM_ERROR.code, ErrorCode.PARAM_ERROR.msg,"0");return response.toString();}//将数据加入消息队列中 queueSender.send("Lily.parking.queue", extralBerthData);response = new ResponseData(ErrorCode.SUCCESS.code, ErrorCode.SUCCESS.msg,String.valueOf(extralBerthData.getSequence()));} catch (Exception e) {log.error("接口异常", e);response = new ResponseData(ErrorCode.UNKNOW_ERROR.code, ErrorCode.UNKNOW_ERROR.msg,"0");}return response.toString();}
}

其中有一个activemq的发送消息类:
package com.innotek.core.support.mq;import java.io.Serializable;import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
/*** 队列消息发送类* @author ShenHuaJie* @version 2016年5月20日 下午3:19:19*/
@Component
public class QueueSender {@Autowired@Qualifier("jmsQueueTemplate")private JmsTemplate jmsTemplate;/*** 发送一条消息到指定的队列(目标)* * @param queueName 队列名称* @param message 消息内容*/public void send(String queueName, final Serializable message) {jmsTemplate.send(queueName, new MessageCreator() {public Message createMessage(Session session) throws JMSException {return session.createObjectMessage(message);}});}
}

activemq接受消息队列的类:
package com.innotek.service.mq.queue;import java.sql.Timestamp;
import java.util.Date;import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.innotek.core.Constants;
import com.innotek.core.util.DateUtil;
import com.innotek.dao.parking.expand.BerthExpandMapper;
import com.innotek.model.busi.generator.Berth;
import com.innotek.model.parking.generator.ExtralBerthData;
import com.innotek.provider.leave.AutoArriveService;
import com.innotek.provider.leave.AutoLeaveServiceImpl;@Service
public class QueueMessageListener implements MessageListener {private final Logger logger = LogManager.getLogger();@Autowiredprivate BerthExpandMapper berthExpandMapper;@Autowiredprivate AutoLeaveServiceImpl autoLeaveServiceImpl;@Autowiredprivate AutoArriveService autoArriveService;public void onMessage(Message message) {try {ExtralBerthData extralBerthData = (ExtralBerthData) ((ObjectMessage) message).getObject();Berth berth = berthExpandMapper.queryByBerthCood(extralBerthData.getBerthCode());Date date = DateUtil.string2Date(extralBerthData.getSendTime(), "YYYY-MM-DD HH:mm:ss");Timestamp sendTime = new Timestamp(date.getTime());if (extralBerthData.getStatus() == Constants.PARK_YES) {//驶入接口autoArriveService.autoParkRecord(extralBerthData.getCityCode(), berth, sendTime);} else if (extralBerthData.getStatus() == Constants.PARK_NO) {//驶离接口autoLeaveServiceImpl.leave(extralBerthData.getCityCode(), berth, sendTime, null);}} catch (Exception e) {logger.error(e);}}
}

其他内容可以参考:http://blog.csdn.net/jbgtwang/article/details/43939037


这篇关于jersey和spring集成配置使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1004476

相关文章

Spring Boot循环依赖原理、解决方案与最佳实践(全解析)

《SpringBoot循环依赖原理、解决方案与最佳实践(全解析)》循环依赖指两个或多个Bean相互直接或间接引用,形成闭环依赖关系,:本文主要介绍SpringBoot循环依赖原理、解决方案与最... 目录一、循环依赖的本质与危害1.1 什么是循环依赖?1.2 核心危害二、Spring的三级缓存机制2.1 三

如何在Mac上安装并配置JDK环境变量详细步骤

《如何在Mac上安装并配置JDK环境变量详细步骤》:本文主要介绍如何在Mac上安装并配置JDK环境变量详细步骤,包括下载JDK、安装JDK、配置环境变量、验证JDK配置以及可选地设置PowerSh... 目录步骤 1:下载JDK步骤 2:安装JDK步骤 3:配置环境变量1. 编辑~/.zshrc(对于zsh

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

在Spring Boot中浅尝内存泄漏的实战记录

《在SpringBoot中浅尝内存泄漏的实战记录》本文给大家分享在SpringBoot中浅尝内存泄漏的实战记录,结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录使用静态集合持有对象引用,阻止GC回收关键点:可执行代码:验证:1,运行程序(启动时添加JVM参数限制堆大小):2,访问 htt

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

浅析Java中如何优雅地处理null值

《浅析Java中如何优雅地处理null值》这篇文章主要为大家详细介绍了如何结合Lambda表达式和Optional,让Java更优雅地处理null值,感兴趣的小伙伴可以跟随小编一起学习一下... 目录场景 1:不为 null 则执行场景 2:不为 null 则返回,为 null 则返回特定值或抛出异常场景

售价599元起! 华为路由器X1/Pro发布 配置与区别一览

《售价599元起!华为路由器X1/Pro发布配置与区别一览》华为路由器X1/Pro发布,有朋友留言问华为路由X1和X1Pro怎么选择,关于这个问题,本期图文将对这二款路由器做了期参数对比,大家看... 华为路由 X1 系列已经正式发布并开启预售,将在 4 月 25 日 10:08 正式开售,两款产品分别为华

SQL server配置管理器找不到如何打开它

《SQLserver配置管理器找不到如何打开它》最近遇到了SQLserver配置管理器打不开的问题,尝试在开始菜单栏搜SQLServerManager无果,于是将自己找到的方法总结分享给大家,对SQ... 目录方法一:桌面图标进入方法二:运行窗口进入方法三:查找文件路径方法四:检查 SQL Server 安

SpringMVC获取请求参数的方法

《SpringMVC获取请求参数的方法》:本文主要介绍SpringMVC获取请求参数的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 目录1、通过ServletAPI获取2、通过控制器方法的形参获取请求参数3、@RequestParam4、@

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的