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

相关文章

Java实现字符串大小写转换的常用方法

《Java实现字符串大小写转换的常用方法》在Java中,字符串大小写转换是文本处理的核心操作之一,Java提供了多种灵活的方式来实现大小写转换,适用于不同场景和需求,本文将全面解析大小写转换的各种方法... 目录前言核心转换方法1.String类的基础方法2. 考虑区域设置的转换3. 字符级别的转换高级转换

使用Python将PDF表格自动提取并写入Word文档表格

《使用Python将PDF表格自动提取并写入Word文档表格》在实际办公与数据处理场景中,PDF文件里的表格往往无法直接复制到Word中,本文将介绍如何使用Python从PDF文件中提取表格数据,并将... 目录引言1. 加载 PDF 文件并准备 Word 文档2. 提取 PDF 表格并创建 Word 表格

使用Python实现局域网远程监控电脑屏幕的方法

《使用Python实现局域网远程监控电脑屏幕的方法》文章介绍了两种使用Python在局域网内实现远程监控电脑屏幕的方法,方法一使用mss和socket,方法二使用PyAutoGUI和Flask,每种方... 目录方法一:使用mss和socket实现屏幕共享服务端(被监控端)客户端(监控端)方法二:使用PyA

Python使用Matplotlib和Seaborn绘制常用图表的技巧

《Python使用Matplotlib和Seaborn绘制常用图表的技巧》Python作为数据科学领域的明星语言,拥有强大且丰富的可视化库,其中最著名的莫过于Matplotlib和Seaborn,本篇... 目录1. 引言:数据可视化的力量2. 前置知识与环境准备2.1. 必备知识2.2. 安装所需库2.3

SpringBoot简单整合ElasticSearch实践

《SpringBoot简单整合ElasticSearch实践》Elasticsearch支持结构化和非结构化数据检索,通过索引创建和倒排索引文档,提高搜索效率,它基于Lucene封装,分为索引库、类型... 目录一:ElasticSearch支持对结构化和非结构化的数据进行检索二:ES的核心概念Index:

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

Linux内核定时器使用及说明

《Linux内核定时器使用及说明》文章详细介绍了Linux内核定时器的特性、核心数据结构、时间相关转换函数以及操作API,通过示例展示了如何编写和使用定时器,包括按键消抖的应用... 目录1.linux内核定时器特征2.Linux内核定时器核心数据结构3.Linux内核时间相关转换函数4.Linux内核定时

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav