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通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式

《Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式》本文详细介绍如何使用Java通过JDBC连接MySQL数据库,包括下载驱动、配置Eclipse环境、检测数据库连接等关键步骤,... 目录一、下载驱动包二、放jar包三、检测数据库连接JavaJava 如何使用 JDBC 连接 mys

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Ubuntu如何分配​​未使用的空间

《Ubuntu如何分配​​未使用的空间》Ubuntu磁盘空间不足,实际未分配空间8.2G因LVM卷组名称格式差异(双破折号误写)导致无法扩展,确认正确卷组名后,使用lvextend和resize2fs... 目录1:原因2:操作3:报错5:解决问题:确认卷组名称​6:再次操作7:验证扩展是否成功8:问题已解

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Java操作Word文档的全面指南

《Java操作Word文档的全面指南》在Java开发中,操作Word文档是常见的业务需求,广泛应用于合同生成、报表输出、通知发布、法律文书生成、病历模板填写等场景,本文将全面介绍Java操作Word文... 目录简介段落页头与页脚页码表格图片批注文本框目录图表简介Word编程最重要的类是org.apach

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核