@Path("user")
public class UserAction {
@Autowired
private UserService userService;
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public User getGreeting(@PathParam("id") Integer id) throws Exception {
return userService.getUserById(id);
}
}
public class User {
private Integer id;
private String name;
private Integer age;
private String password;
//省去getter setter 方法
}
对应数据库表脚本如下:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'zhaochao', '20', 'zhaochao');
INSERT INTO `user` VALUES ('2', '赵云', '50', 'zhaoyun');
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
packages("com.zhaochao.action");
register(JacksonFeature.class);
property(ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
}
}
主要指明Jersey 的资源存放在com.zhaochao.action包下,以及将返回对象直接转换成JSON
@Component
@Configuration
@ComponentScan(basePackages = {"com"})
public class SpringJavaConfiguration {
@Bean(autowire = Autowire.BY_TYPE)
public DataSource dataSource() {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setDriverClassName("com.mysql.jdbc.Driver");
poolProperties.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10");
poolProperties.setUsername("root");
poolProperties.setPassword("root");
poolProperties.setJmxEnabled(true);
poolProperties.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
poolProperties.setRemoveAbandonedTimeout(60);
poolProperties.setRemoveAbandoned(true);
poolProperties.setLogAbandoned(false);
poolProperties.setMinIdle(10);
poolProperties.setMinEvictableIdleTimeMillis(30000);
poolProperties.setMaxWait(10);
poolProperties.setInitialSize(2);
poolProperties.setMaxActive(10);
poolProperties.setTimeBetweenEvictionRunsMillis(30000);
poolProperties.setValidationQuery("SELECT 1");
poolProperties.setValidationInterval(30000);
poolProperties.setTestOnReturn(false);
poolProperties.setTestOnBorrow(true);
poolProperties.setTestWhileIdle(true);
poolProperties.setJmxEnabled(true);
DataSource dataSource = new DataSource();
dataSource.setPoolProperties(poolProperties);
return dataSource;
}
@Bean(name="sqlSessionFactory" )
public SqlSessionFactoryBean getSqlSesssionFactoryBean(){
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setDataSource(dataSource());
Resource re =new ClassPathResource("mybatis-config.xml");
bean.setConfigLocation(re);
return bean;
}
@Bean(name="mapper",autowire=Autowire.BY_NAME)
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer conf=new MapperScannerConfigurer();
conf.setBasePackage("com.zhaochao.mapper");
conf.setSqlSessionFactoryBeanName("sqlSessionFactory");
return conf;
}
public class Main {
public static void main(String[] args) throws Exception {
ApplicationConfig applicationConfig = new ApplicationConfig();
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(applicationConfig));
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(jerseyServlet, "/rest/*");
context.addEventListener(new ContextLoaderListener());
context.addEventListener(new RequestContextListener());
context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
context.setInitParameter("contextConfigLocation", SpringJavaConfiguration.class.getName());
int port=8080;
if(args.length==1){
port=Integer.parseInt(args[0]);
}
Server server = new Server(port);
server.setHandler(context);
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public interface UserMapper {
@Select("select * from user where id=#{id}")
public User getUserById(@Param("id") Integer id);
public User queryById(Integer id);
}
@Service("userService")
public class UserService {
@Autowired
private UserMapper mapper;
public UserMapper getMapper() {
return mapper;
}
public User getUserById(Integer userId){
//return mapper.getUserById(userId);
return mapper.queryById(userId);
}
}
<mapper namespace="com.zhaochao.mapper.UserMapper">
<cache readOnly="true" eviction="FIFO" flushInterval="60000" />
<resultMap id="BaseResultMap" type="com.zhaochao.bean.User">
<result column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
<result column="password" property="password" />
resultMap>
<sql id="Base_Column_List">
id,name,age,password
sql>
<select id="queryById" resultMap="BaseResultMap" parameterType="Object" useCache="true">
select
<include refid="Base_Column_List" />
from user where id = #{id}
select>
mapper>
<configuration>
<settings>
<setting name="cacheEnabled" value="true" />
settings>
<mappers>
<mapper resource="mybatis/user/UserMapper.xml" />
mappers>
configuration>
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="LOG.CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d - %c -%-4r [%t] %-5p %x - %m%n" />
layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMax" value="ERROR" />
<param name="LevelMin" value="TRACE" />
filter>
appender>
<appender name="LOG.DEBUG" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/zhaochao/jersey/debug.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="DEBUG" />
filter>
appender>
<appender name="LOG.INFO" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="/zhaochao/jersey/info.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
filter>
appender>
<appender name="LOG.WARN" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/zhaochao/jersey/warn.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="WARN" />
filter>
appender>
<appender name="LOG.ERROR" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/zhaochao/jersey/error.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="ERROR" />
filter>
appender>
<appender name="LOG.FATAL" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/zhaochao/jersey/fatal.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="FATAL" />
<param name="LevelMax" value="FATAL" />
filter>
appender>
<root>
<priority value="INFO" />
<appender-ref ref="LOG.DEBUG" />
<appender-ref ref="LOG.INFO" />
<appender-ref ref="LOG.WARN" />
<appender-ref ref="LOG.ERROR" />
<appender-ref ref="LOG.FATAL" />
<appender-ref ref="LOG.CONSOLE" />
root>
log4j:configuration>
<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.0modelVersion>
<groupId>com.underdog.jerseygroupId>
<artifactId>jersey-spring-jettyartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containersgroupId>
<artifactId>jersey-container-servletartifactId>
<version>2.17version>
dependency>
<dependency>
<groupId>org.glassfish.jersey.extgroupId>
<artifactId>jersey-spring3artifactId>
<version>2.17version>
<exclusions>
<exclusion>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
exclusion>
<exclusion>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
exclusion>
<exclusion>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
exclusion>
<exclusion>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.eclipse.jettygroupId>
<artifactId>jetty-servletsartifactId>
<version>9.2.6.v20141205version>
dependency>
<dependency>
<groupId>org.eclipse.jettygroupId>
<artifactId>jetty-servletartifactId>
<version>9.2.6.v20141205version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.1.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>4.1.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.1.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.glassfish.jersey.mediagroupId>
<artifactId>jersey-media-json-jacksonartifactId>
<version>2.17version>
dependency>
<dependency>
<groupId>org.apache.tomcatgroupId>
<artifactId>tomcat-jdbcartifactId>
<version>8.0.28version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.1.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.21version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.7version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.14version>
dependency>
dependencies>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-shade-pluginartifactId>
<version>2.4.2version>
<configuration>
<createDependencyReducedPom>truecreateDependencyReducedPom>
<filters>
<filter>
<artifact>*:*artifact>
<excludes>
<exclude>META-INF/*.SFexclude>
<exclude>META-INF/*.DSAexclude>
<exclude>META-INF/*.RSAexclude>
excludes>
filter>
filters>
configuration>
<executions>
<execution>
<phase>packagephase>
<goals>
<goal>shadegoal>
goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.zhaochao.main.MainmainClass>
transformer>
transformers>
configuration>
execution>
executions>
plugin>
<plugin>
<groupId>org.codehaus.mojogroupId>
<artifactId>exec-maven-pluginartifactId>
<version>1.2.1version>
<executions>
<execution>
<goals>
<goal>javagoal>
goals>
execution>
executions>
<configuration>
<mainClass>com.zhaochao.main.MainmainClass>
configuration>
plugin>
plugins>
build>
project>
java -jar jersey-spring-jetty-1.0-SNAPSHOT.jar
打开浏览器输入http://localhost:8080/rest/user/1
完整项目地址:https://github.com/whzhaochao/spring-jetty-jersey-mybatis