此篇文章涉及的知识点: 1、jersey开发restful服务
2、jersey的restful服务接口返回对象,引入第三方provider ,同时能被json化
3、jersey与spring的集成,在web.xml中使用集成的入口类
4、使用java rest规范的扩展包中的ExceptionMapper统一管理异常
4、spring国际化资源管理
5、spring整合c3p0数据源
6、spring扫包注入
7、mybatis与spring的集成
8、mybatis扫包,配置orm与dao接口类,自动生成dao对象
文件结构
主要的文件如下:
/src/main/java/de/tao/jsm/dao/UserDao.java dao接口
/src/main/java/de/tao/jsm/exception/BaseException.java 自定义异常类
/src/main/java/de/tao/jsm/exception/ExceptionKeys.java 异常代号定义
/src/main/java/de/tao/jsm/exception/ExceptionMappingResource.java ExceptionMapper<Exception>的实现类
/src/main/java/de/tao/jsm/exception/ExceptionResponse.java response返回的exception实体bean
/src/main/java/de/tao/jsm/exception/MessageUtil.java property处理类(在本示例中未启用)
/src/main/java/de/tao/jsm/i18n/messages_en_US.properties 异常提示信息(英文版)
/src/main/java/de/tao/jsm/i18n/messages_zh_CN.properties 异常提示信息(中文版)
/src/main/java/de/tao/jsm/pojo/User.java 业务bean
/src/main/java/de/tao/jsm/rest/UserRest.java 业务restful接口实现类
/src/main/resources/dao_config/UserDao.xml orm配置,配置dao的接口的实现,不需要其它代码
/src/main/resources/jdbc.properties 数据源配置信息
/src/main/resources/spring-mybatis.xml spring的主配置文件,主要配置bean/message resource/data resource/spring与mybatis的整合
配置文件
配置maven依赖pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.tao</groupId>
<artifactId>jersey_spring_mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey.contribs/jersey-spring -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>1.19.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
</dependencies>
</project>
web配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>jersey_spring_mybatis</display-name>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>ComicJaxServlet</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>de.tao.jsm</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ComicJaxServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="de.tao.jsm" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
abstract="false" lazy-init="default" autowire="default"
>
<property name="basenames">
<list>
<value>de.tao.jsm.i18n.messages</value>
</list>
</property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:dao_config/*.xml"></property>
<property name="typeAliasesPackage" value="de.tao.jsm.pojo"/>
</bean>
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="de.tao.jsm.dao.UserDao"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> -->
<!-- <property name="basePackage" value="de.tao.jsm.*" /> -->
<!-- 无需指定引用SqlSessionFactory?因为MapperScannerConfigurer在创建映射器时会通过自动装配的方式来引用。 -->
<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> -->
<!-- </bean> -->
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 引入配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>${jdbc.driverClassName}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize">
<value>5</value>
</property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize">
<value>30</value>
</property>
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize">
<value>10</value>
</property>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime">
<value>60</value>
</property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement">
<value>5</value>
</property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements">
<value>0</value>
</property>
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod">
<value>60</value>
</property>
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts">
<value>30</value>
</property>
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->
<property name="breakAfterAcquireFailure">
<value>true</value>
</property>
<!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的
时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
等方法来提升连接测试的性能。Default: false -->
<property name="testConnectionOnCheckout">
<value>false</value>
</property>
</bean>
</beans>
orm配置,不需要dao的接口实现类
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="de.tao.jsm.dao.UserDao" >
<!--结果集的定义,这里从数据库字段到对象属性可以建立对应关系-->
<resultMap type="User" id="UserResult">
<id property="id" column="id" />
<result property="name" column="uname" />
<result property="address" column="address" />
</resultMap>
<!-- getUsers要与类方法相同,resultType表示结果封装成对象,parameterType表示查询时的参数类型 -->
<select id="getUsers" resultType="User" resultMap="UserResult">
select id, uname, address from users
</select>
</mapper>
实现
dao接口
package de.tao.jsm.dao;
import java.util.List;
import de.tao.jsm.pojo.User;
public interface UserDao {
List<User> getUsers();
}
统一的exception处理(注意使用@Provider标签)
package de.tao.jsm.exception;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.springframework.web.context.WebApplicationContext;
//必须被com.sun.jersey.spi.spring.container.servlet.SpringServlet扫描到
@Provider
public class ExceptionMappingResource implements ExceptionMapper<Exception> {
private static final String CONTEXT_ATTRIBUTE = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
@Context
private HttpServletRequest request;
@Context
private ServletContext servletContext;
@Override
public Response toResponse(Exception exception) {
ResponseBuilder responseBuilder = null;
ExceptionResponse error = new ExceptionResponse();
// 用户自定义的运行时异常处理
if (exception instanceof BaseException) {
//根据异常key获取对应的中文异常信息
BaseException baseEx = (BaseException) exception;
String code = baseEx.getCode();
//第一种方法:自建properties处理工具类
//String message = MessageUtil.getInstance().getMessage(baseEx);
//第二种方法:用spring的方式
WebApplicationContext context = (WebApplicationContext) servletContext
.getAttribute(CONTEXT_ATTRIBUTE);
String message = context.getMessage(code, baseEx.getValues(), request.getLocale());
Throwable cause = exception.getCause();
if (cause != null) {
String realReason = cause.getMessage();
message += " 可能的原因是:" + realReason + "";
}
//自定义异常返回实体bean类
error.setCode(code);
error.setMessage(message);
error.setStatus("error");
}
// 其他异常
else {
error.setCode("E000000");
error.setMessage(exception.getMessage());
error.setStatus("error");
}
responseBuilder = Response.ok(error).status(Status.INTERNAL_SERVER_ERROR);
return responseBuilder.build();
}
}
message properties
value_not_allow=paramenter [{0}] not allow as [{1}]
undefined=undefined
rest接口实现:
package de.tao.jsm.rest;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.sun.jersey.api.spring.Autowire;
import de.tao.jsm.dao.UserDao;
import de.tao.jsm.exception.BaseException;
import de.tao.jsm.exception.ExceptionKeys;
import de.tao.jsm.pojo.User;
//使用spring的component标签,同时在成员变量上使用@Resource标签,才能被注入,类上没使用标签,成员变量注入不成功
//或者使用jersey的@Autowire标签,然后提供注解属性的setter方法,否则注解失败
@Path("/user")
@Autowire
public class UserRest {
//@Resource(name="userDao")
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers() {
return userDao.getUsers();
}
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public Response test(@QueryParam("p") String val) {
if ("err".equals(val)) {
//将被统一处理,返回对象JSON化字符串
throw new BaseException(ExceptionKeys.value_not_allow, "", new String[]{"val", val});
} else {
//返回参数内容
ResponseBuilder rb = Response.ok(val).status(200);
return rb.build();
}
}
}
运行效果
- http://localhost:8080/jsm/rest/user/test?p=err
{"code":"value_not_allow","message":"参数val值不允许为err","status":"error"}
- http://localhost:8080/jsm/rest/user/list
[{"address":"sz","id":"1","name":"t"},{"address":"cs","id":"2","name":"y"}]