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

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B