最近研究maven,故而用maven搭建了springmvc+mybatis框架來實踐一下,若有不足之處,望指正。javascript
下面開始講解,本人視讀者已經掌握maven的使用或者隊maven有必定的瞭解,若是不瞭解maven,請查看小菜鳥的博客---maven詳解。java
本文用的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提供的簡單,這裏再也不贅述。mysql
首先建立一個maven project,編寫pom文件,將對應的jar包引用進來。編輯後的pom以下:web
Xml代碼
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" sql
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 數據庫
<modelVersion>4.0.0</modelVersion> express
<groupId>com.qijian</groupId> apache
<artifactId>SpringMVC</artifactId> json
<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>