最近研究maven,故而用maven搭建了springmvc+mybatis框架来实践一下,如有不足之处,望指正。
下面开始讲解,本人视读者已经掌握maven的使用或者队maven有一定的了解,如果不了解maven,请查看小菜鸟的博客---maven详解。
本文用的spring是 4.0.5.RELEASE版,日志框架用的是logback 1.1.2,数据库连接池用的是c3p0 0.9.1.2,mybatis 用的是 3.2.7。所用技术基本都是最新版本。多说一句,本文 mybatis-spring桥用的是mybatis提供的mybatis-spring,当然你也可以用spring orm配合mybatis使用,但是没有用mybatis提供的简单,这里不再赘述。
首先创建一个maven project,编写pom文件,将对应的jar包引用进来。编辑后的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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qijian</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 构件的版本 -->
<properties>
<junit.version>3.8.1</junit.version>
<logback.version>1.1.2</logback.version>
<jackson.version>1.9.9</jackson.version>
<common.fileupload.version>1.3.1</common.fileupload.version>
<spring.version>4.0.5.RELEASE</spring.version>
<aspectj.version>1.8.1</aspectj.version>
<jstl.version>1.2</jstl.version>
<mybatis-spring.version>1.2.2</mybatis-spring.version>
<mybatis.version>3.2.7</mybatis.version>
<c3p0.version>0.9.1.2</c3p0.version>
<mysql.version>5.1.31</mysql.version>
</properties>
<!-- 项目依赖 -->
<dependencies>
<!-- junit测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- logback日志工具 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- 避免IE执行AJAX时,返回JSON出现下载文件(属于springmvc) -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
<!--spring mvc的文件上传依赖 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${common.fileupload.version}</version>
</dependency>
<!-- jstl表达式依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- srping security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.4.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- spring mvc依赖开始 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring mvc依赖结束 -->
<!-- spring 切面依赖开始 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- spring 切面依赖结束 -->
<!-- 运行mybatis所需依赖开始 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis,spring桥(当然你也可以用spring orm配合mybatis使用,但是没有用mybatis提供的简单这里不再赘述)-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- 用c3p0连接池去管理数据库连接 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 运行mybatis所需依赖结束 -->
</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>
下面开始配置springmvc ,首先编辑web.xml文件,配置springmvc,将请求转给spring mvc处理(注:springmvc在web.xml中是以servlet的形式
配置的,这里要和struts2的filter区分开)
springmvc 的servlet配置代码如下:
Xml代码
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:spring*.xml
</param-value>
</init-param>
</servlet>
其中contextConfigLocation是可选配置参数,在此配置它的原因是因为本人将spring的配置文件放到了classpath下(即maven中的src/main/resources目录),
如果你不想配置此参数,则要配置另外一个listener(org.springframework.web.context.ContextLoaderListener),然后再将spring的配置文件(spring配置文件还有springmvc的配置文件,其中springmvc的配置文件名称为*-servlet.xml格式)放到web-inf目录下,你可以自己亲身实验一下,这里不再赘述,如果不清楚的可以找本人讲解。,其整个web.xml配置完如下:
Xml代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:spring*.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 设置spring mvc的编码集 -->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
接着说spring的配置。spring 的配置比较简单,主要是开启spring注解以及引入数据库配置的properties文件,这里不再详细扩展,如有不明白的
地方可以给本人留言,本人将耐心讲解,spring.xml代码如下:
Xml代码
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 引入数据库属性文件 -->
<context:property-placeholder location="classpath*:config.properties" />
<!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<context:component-scan base-package="com.qijian" />
</beans>
接下来是springmvc的配置,主要是配置处理springmvc请求的适配器以及模型视图适配器,由于前面spring用的是注解,这里和上面保持同步,spring-servlet.xml的代码如下:
Xml代码
<?xml version="1.0" encoding="UTF-8"?>
<!-- Bean头部 -->
<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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
</list>
</property>
</bean>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp" />
</beans>
其中org.springframework.http.converter.ByteArrayHttpMessageConverter是将二进制字节流转换器,因本人项目中用到了验证码,故需配置此项,
如果你没哟这方面需求的话可以不配置。要想使用springmvc上传功能的话还应配置org.springframework.web.multipart.commons.CommonsMultipartResolver
来支持上传功能,这里不再赘述。
最后是mybatis的配置,主要是配置了数据源(连接池)、mybatis接口以及xml文件的映射位置、事务管理(这里使用的是spring jdbc的事务管理,
好处是通用,你也可以用其他来管理mybatis的事务),这里主要是使用的声明式事务(你也可以用注解式事务,如果你不嫌麻烦的话还可以用代码的形式),编辑完
的mybatis配置文件如下:
Xml代码
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!--c3p0数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${driverClassName}" />
<property name="jdbcUrl" value="${jdbc_url}" />
<property name="user" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<property name="initialPoolSize" value="1" />
<property name="minPoolSize" value="0" />
<property name="maxPoolSize" value="50" />
<property name="acquireIncrement" value="5" />
<property name="maxIdleTime" value="10" />
<property name="maxStatements" value="0" />
</bean>
<!-- myBatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="mapperLocations" value="classpath*:com/qijian/dao/impl/*.xml" />
</bean>
<!--dao接口的位置-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qijian.dao.inter" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 注解方式配置事务 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
<!-- 拦截器方式配置事务 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="repair" propagation="REQUIRED" />
<tx:method name="delAndRepair" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut"
expression="execution(* com.qijian.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut"
advice-ref="transactionAdvice" />
</aop:config>
</beans>
最后再给出logback.xml代码,这个比较简单,如果不愿改变输出格式的话直接默认的xml格式就可以了,这里给出我的日志输出格式
logback.xml
Xml代码
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5p [%c{0}] %m%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
以上基本将springmvc+mybatis的框架配置代码配置完了,然后编写代码就可以运行了。下面是示例代码:
controller
Java代码
package com.qijian.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.qijian.po.User;
import com.qijian.service.inter.IUserService;
import com.qijian.util.DataGrid;
@RequestMapping("/test")
public class TestController {
private static Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
@Qualifier("userService")
private IUserService userService;
@RequestMapping("/json")
public @ResponseBody DataGrid<User> getAllUser(int page,int rows) {
DataGrid<User> dg = new DataGrid<User>();
List<User> userList = userService.getAllUser(page,rows);
dg.setRows(userList);
dg.setTotal(userService.userCount());
logger.debug("------query------");
return dg;
}
}
service接口:
Java代码
package com.qijian.service.inter;
import java.util.List;
import com.qijian.po.User;
public interface IUserService {
public List<User> getAllUser(int page,int rows);
public int userCount() ;
}
service实现
Java代码
package com.qijian.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qijian.dao.inter.UserMapper;
import com.qijian.po.User;
import com.qijian.service.inter.IUserService;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getAllUser(int page,int rows){
page = page<0?1:page;
int start = (page-1) *rows;
int end = page*rows;
return userMapper.getAllUser(start,end);
}
@Override
public int userCount() {
return userMapper.userCount();
}
}
dao接口:
UserMapper.java
Java代码
package com.qijian.dao.inter;
import java.util.List;
import com.qijian.po.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
public List<User> getAllUser(int start,int end);
public int userCount();
}
dao实现(mybatis的xml文件):
UserMapper.xml
Xml代码
<?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="com.qijian.dao.inter.UserMapper" >
<resultMap id="BaseResultMap" type="com.qijian.po.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, username, password
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from qijian_user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from qijian_user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.qijian.po.User" >
insert into qijian_user (id, username, password
)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.qijian.po.User" >
insert into qijian_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="username != null" >
username,
</if>
<if test="password != null" >
password,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="username != null" >
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.qijian.po.User" >
update qijian_user
<set >
<if test="username != null" >
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.qijian.po.User" >
update qijian_user
set username = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="getAllUser" resultType="com.qijian.po.User">
select * from qijian_user limit #{0},#{1}
</select>
<select id="userCount" resultType="int">
select count(id) from qijian_user
</select>
</mapper>
来源:oschina
链接:https://my.oschina.net/u/2347897/blog/602138