搭建基于Spring+MyBatis+Jersey的Maven-Web系统
版本: Spring(4.1.0.RELEASE) + MyBatis(3.2.7)+ Jersey(1.18.1)
工具: IntelliJ + Maven
详细步骤如下:
- 创建一个基于maven-archetype-webapp的项目
- 打开pom文件,添加spring,jersey,jersey-spring依赖的库
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.1.0.RELEASE</spring.version> <jersey.version>1.18.1</jersey.version> </properties>
<dependencies> <!--Jersey dependencies --> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>${jersey.version}</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>${jersey.version}</version> </dependency> <!-- Spring dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-spring</artifactId> <version>${jersey.version}</version> <!-- 去除自带的spring版本 --> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> </dependencies>
5. 创建文件:src/main/java/applicationContex.xml,添加如下代码即可(根据情况修改包路径)
<context:component-scan base-package="com.steven.study"/>
6. web.xml配置如下:
如果项目中没有web.xml文件,右击项目->Add Framework Support->勾选Web Application->OK即可
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <servlet> <servlet-name>JerseyServlet</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.steven.study.rest</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JerseyServlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping>
7. 添加Rest类
@Component @Path("user") public class UserRest { @GET @Path("/test") @Produces(MediaType.TEXT_PLAIN) public String userTest() { return "OK"; } }
8. 访问:http://localhost:8080/项目名称/rest/user/test
如果返回OK,则表示Rest环境已经run起来了!
9. 继续...
打开pom文件添加 1)MyBatis依赖 2)dbcp依赖(后面会配置连接池) 3)MySql数据库连接jar
<dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.7</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency>
10. applicationContex.xml添加连接池配置、mybatisSqlSessionFactoryBean、SqlSessionTemplate等配置
<!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy- method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydb"/> <property name="username" value="root"/> <property name="password" value="123456"/> <!--连接池启动时的初始值 --> <property name="initialSize" value="10"/> <!--连接池的最大值 --> <property name="maxActive" value="100"/> <!--最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部 分,一直减少到maxIdle为止 --> <property name="maxIdle" value="50"/> <!--最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时 来不及申请 --> <property name="minIdle" value="10"/> <!--给出一条简单的sql语句进行验证 --> <property name="validationQuery" value="select 1 from dual"/> <!--在取出连接时进行有效验证 --> <property name="testOnBorrow" value="true"/> <property name="removeAbandonedTimeout" value="120"/> <property name="removeAbandoned" value="true"/> <!--#运行判断连接超时任务的时间间隔,单位为毫秒,默认为-1,即不执行任务.--> <property name="timeBetweenEvictionRunsMillis" value="3600000"/> <!--#连接的超时时间,默认为半小时。 --> <property name="minEvictableIdleTimeMillis" value="3600000"/> </bean> <!-- 配置mybatisSqlSessionFactoryBean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.steven.study.entity" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.steven.study.mapper" /> </bean> <!-- 配置SqlSessionTemplate --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="pr ototype"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <!-- 事务配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 使用annotation注解方式配置事务 --> <!--<tx:annotation-driven transaction-manager="transactionManager" />--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean>
11. MySQL数据库中创建一张简单的用户表
CREATE TABLE `tb_user` ( `USERID` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT ‘用户编码‘, `USERNAME` varchar(50) NOT NULL COMMENT ‘用户名‘, `PASSWORD` varchar(50) NOT NULL COMMENT ‘密码‘, `AGE` int(10) NOT NULL COMMENT ‘年龄‘, `DELETEFLAG` varchar(1) NOT NULL DEFAULT ‘0‘ COMMENT ‘删除标识‘, PRIMARY KEY (`USERID`), KEY `列 1` (`USERID`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT=‘用户表‘;
12. 添加MyBatis相关的UserMapper和UserMapper.xml
public interface UserMapper { //Create a new user int addUser(); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dt d/mybatis-3-mapper.dtd" > <mapper namespace="com.steven.study.mapper.UserMapper"> <!-- Create a new User --> <insert id="addUser"> INSERT INTO TB_USER(USERNAME,PASSWORD,AGE,DELETEFLAG) VALUES("Hello","11111 1",10,0) </insert> </mapper>
(TB_USER表的主键我设置为Auto Increment,所以这里没有插入该字段)
13. 添加service接口
public interface UserService { public int addUser(); }
14. 添加service接口实现类
@Service public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Override public int addUser() { return userMapper.addUser(); } }
15. UserRest类中添加测试方法
@GET @Path("/add") @Produces(MediaType.TEXT_PLAIN) public String addUser() { int result = userService.addUser(); System.out.println("Create user result = " + result); return result==1?"OK":"ERROR"; }
(UserRest中别忘记了注入service)
16. 测试一下!
总结: 可能会出现的问题:
1. jar包冲突
2. 接口没有添加@Component注解
3. service实现类没有添加@Service注解
4. xxxmapper.xml中的namespace没对应到xxxmapper.java
5. 有时候pom.xml文件加入了依赖但是仍然提示找不到类,可以手动Maven->Reimport
6.
搭建环境的时候还碰到了其它一些问题,想不起来了,先到这吧。