玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

一、创建 SSMVCAnnoDemo 项目

点击菜单,选择“File -> New Project” 创建新项目。选择使用 archetype 中的 maven-webapp 模版创建。

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

输入对应的项目坐标GroupId 和 ArtifactId

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

之后在项目名称中填入项目名称,这里我填的 ProjectName 和上文的 ArtifactId 相同,都是 SSMVCAnnoDemo。

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

点击确定后,等待 Maven 帮我们构建好项目的目录结构。当控制台显示 BUILD SUCCESS 就表示初始化完成了。

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

初始化完成后的目录结构是这样的:

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

在 main 目录下创建 java 目录并将其设置为源码目录:

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

之后创建 com.chanshuyi.action 等包,创建完成后的目录结构如下:

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

二、导入依赖的包和插件

设置 POM.XML 配置文件中的全局属性:

<!-- 声明全局属性 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<struts.version>2.3.24</struts.version>
<springframework.version>4.1.6.RELEASE</springframework.version>
<junit.version>3.8.1</junit.version>
<commonsLogging.version>1.2</commonsLogging.version>
</properties>

依次引入 MyBatis、Spring、SpringMVC、MySQL、Druid、JUnit、Log4J 等的依赖 Jar 包:

<!-- ********************** MyBatis ********************** -->
<!-- MyBatis 核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<!-- 添加mybatis与Spring整合的核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency> <!-- ********************** Spring ********************** -->
<!-- Spring MVC 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- 添加Spring-core包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- 添加spring-tx包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring ORM 相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- 添加spring-jdbc包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!--添加spring-web包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- 添加spring-context包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commonsLogging.version}</version>
</dependency>
<!--添加aspectjweaver包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency> <!-- ********************** Spring MVC 依赖的jar包 **********************-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Servelt API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency> <!-- ********************** DB Connection ********************** -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.6</version>
</dependency> <!-- ********************** 其他 ********************** -->
<!-- 单元测试 JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- 日志记录 Log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.6</version>
</dependency>

之后导入 Tomcat 启动插件,我们将通过 Maven 方式启动 Tomcat,这样就不必在本地配置一个 Tomcat 服务器。

<!--  Maven的Tomcat插件(支持Maven以"tomcat7:run"方式启动web项目)  -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>5050</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
<finalName>mgr</finalName>
<server>tomcat7</server>
</configuration>
</plugin>

配置完成后的 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.chanshuyi.SSMVCAnnoDemo</groupId>
<artifactId>SSMVCAnnoDemo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SSMVCAnnoDemo Maven Webapp</name>
<url>http://maven.apache.org</url> <!-- 声明全局属性 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<struts.version>2.3.24</struts.version>
<springframework.version>4.1.6.RELEASE</springframework.version>
<junit.version>3.8.1</junit.version>
<commonsLogging.version>1.2</commonsLogging.version>
</properties> <dependencies>
<!-- ********************** MyBatis ********************** -->
<!-- MyBatis 核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<!-- 添加mybatis与Spring整合的核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency> <!-- ********************** Spring ********************** -->
<!-- Spring MVC 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- 添加Spring-core包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- 添加spring-tx包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring ORM 相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- 添加spring-jdbc包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!--添加spring-web包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- 添加spring-context包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commonsLogging.version}</version>
</dependency>
<!--添加aspectjweaver包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency> <!-- ********************** Spring MVC 依赖的jar包 **********************-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Servelt API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency> <!-- ********************** DB Connection ********************** -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.6</version>
</dependency> <!-- ********************** 其他 ********************** -->
<!-- 单元测试 JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- 日志记录 Log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.6</version>
</dependency>
</dependencies> <build>
<finalName>SSMVCAnnoDemo</finalName>
<plugins>
<!-- Maven的Tomcat插件(支持Maven以"tomcat7:run"方式启动web项目) -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>5050</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
<finalName>mgr</finalName>
<server>tomcat7</server>
</configuration>
</plugin>
</plugins>
</build>
</project>

pom.xml

三、开发模型层(MyBatis)

创建 SpringMVC 配置文件 resources/spring-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true"> <!-- 添加注解驱动 -->
<mvc:annotation-driven />
<!-- 默认扫描的包路径 -->
<context:component-scan base-package="com.chanshuyi.controller, com.chanshuyi.service.impl, com.chanshuyi.dao.impl" /> <!-- mvc:view-controller可以在不需要Controller处理request的情况,转向到设置的View -->
<!-- 像下面这样设置,如果请求为/,则不通过controller,而直接解析为/index.jsp -->
<!--<mvc:view-controller path="/" view-name="index" />-->
<!-- 配置 SpringMVC Controller 转发JSP页面的路径 -->
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<!-- 配置jsp路径前缀 -->
<property name="prefix" value="/"></property>
<!-- 配置URl后缀 -->
<property name="suffix" value=".jsp"></property>
</bean> <!-- ================================== import sub-config file ================================== -->
<import resource="spring-mybatis.xml" />
<!-- ================================== /import sub-config file ================================== -->
</beans>

创建 spring-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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 引入外部properties文件 -->
<context:property-placeholder location="classpath:jdbc.properties" /> <!-- ====================================================== Add MyBatis Support Start ====================================================== -->
<!-- 配置写数据源 -->
<bean id="dataSourceWrite" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.master.url}" />
<property name="username" value="${jdbc.master.username}" />
<property name="password" value="${jdbc.master.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${jdbc.master.initialSize}" />
<property name="minIdle" value="${jdbc.master.minIdle}" />
<property name="maxActive" value="${jdbc.master.maxActive}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT '1'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 mysql false -->
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="config,stat,log4j,wall" />
<property name="connectionProperties" value="config.decrypt=false" />
</bean>
<!-- 配置读数据源 -->
<bean id="dataSourceRead" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.slave.url}" />
<property name="username" value="${jdbc.slave.username}" />
<property name="password" value="${jdbc.slave.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${jdbc.slave.initialSize}" />
<property name="minIdle" value="${jdbc.slave.minIdle}" />
<property name="maxActive" value="${jdbc.slave.maxActive}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT '1'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 mysql false -->
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="config,stat,log4j,wall" />
<property name="connectionProperties" value="config.decrypt=false" />
</bean> <!-- 可写的SessionFactory -->
<bean id="sqlWriteSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" scope="singleton">
<property name="dataSource" ref="dataSourceWrite" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<!-- 只读的SessionFactory -->
<bean id="sqlReadOnlySessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" scope="singleton">
<property name="dataSource" ref="dataSourceRead" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean> <!-- 可写的Session -->
<bean id="writableSQLSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlWriteSessionFactory" />
</bean>
<!-- 只读的Session -->
<bean id="readonlySQLSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlReadOnlySessionFactory" />
</bean>
<!-- ====================================================== Add MyBatis Support End ====================================================== -->
</beans>

创建 jdbc.properties 配置文件

############################  MySQL/Oracle/SQLServer Database Configuratioin Info ###############################
# MySQL Master DB Info
jdbc.master.dialet=org.hibernate.dialect.MySQLDialect
jdbc.master.driverClassName=com.mysql.jdbc.Driver
jdbc.master.url=jdbc:mysql://127.0.0.1:3306/SSMDemo
jdbc.master.username=root
jdbc.master.password=sa # MySQL Slave DB Info
jdbc.slave.dialet=org.hibernate.dialect.MySQLDialect
jdbc.slave.driverClassName=com.mysql.jdbc.Driver
jdbc.slave.url=jdbc:mysql://localhost:3306/SSMDemo
jdbc.slave.username=root
jdbc.slave.password=sa ############################## Connection Pool Configuration Info ##############################################
# MySQL Master DB Setting
jdbc.master.initialSize = 10
jdbc.master.minIdle = 0
jdbc.master.maxActive = 30 # MySQL Slave DB Setting
jdbc.slave.initialSize = 10
jdbc.slave.minIdle = 0
jdbc.slave.maxActive = 30

在本地 MySQL 数据库创建一个 SSMDemo 数据库,执行下面的语句创建 user 表并插入一条测试数据。

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'admin', 'password');

创建 mybatis-config.xml 文件,并配置需要扫描包路径

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<!-- 配置扫描的Mapper类 -->
<package name="com.chanshuyi.dao.mapper"/>
</mappers>
</configuration>

下载 MBGGenerator(密码:c1dy),这是MyBatis 官方的 MyBatis Generator,我们使用它将数据库表转化成 model、mapper 以及 SqlProvider 文件。

下载文件解压放到 resources 目录下。进入 resources/mbg 目录,双击运行 generate.bat,程序自动将配置文件 resources/mbgconfig.xml 中配置的表格映射成相对应的文件。

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

四、开发视图层(Spring)

创建 resources/log4j.properties 文件,提供日志记录。

#Console Log
log4j.rootLogger=info, console, file # Write to Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=INFO
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%5p %d{MM-dd HH:mm:ss}(%F:%L): %m%n # Write to File
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=${catalina.home}app/log/log.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%5p %d{MM-dd HH:mm:ss}(%F:%L): %m%n

在 com.chanshuyi.dao.mapper.UserMapper 类中增加 getUserListByMapSql 接口:

/**
* 根据参数构造SQL进行查询
* @param param
* @return
*/
@SelectProvider(type = UserSqlProvider.class, method = "getUserListByMapSql")
List<User> getUserListByMapSql(@Param("param") Map<String, String> param);

在 UserSqlProvider 类增加对上面接口 SQL 的实现:

/**
* 获取查询SQL
* @param param
* @return
*/
public String getUserListByMapSql(Map<String, Object> param) {
StringBuilder builder = new StringBuilder();
Map<String, String> realParam = (Map<String, String>)param.get("param"); //add select part
builder.append(" select * from user where 1 = 1 "); //add condition part
String conditionStr = "";
if(!StringUtil.isNullOrEmpty(realParam)){
conditionStr = getQueryCondition(realParam);
if(!StringUtil.isNullOrEmpty(conditionStr)){
builder.append(conditionStr);
}
} return new String(builder);
} public String getQueryCondition(Map<String, String> param){
StringBuilder builder = new StringBuilder(); //if param is null or empty, return empty String
if(param == null || param.size() < 1){
return "";
} for(String key : param.keySet()){
String value = param.get(key);
if(value != null && !value.isEmpty()){
builder.append(" and " + key + " = '" + value + "'");
}
} return new String(builder);
}

上面用到了 StringUtil.java,我们在 com.chanshuyi.util 中导入它:

package com.mszz.util;

import java.util.Collection;
import java.util.Map; /**
* 字符串工具类
* @author chenxinquan
*
*/
public class StringUtil {
/**
* 判断对象或对象数组中每一个对象是否为空: 对象为null,字符序列长度为0,集合类、Map为empty
* @author zl
* @param obj
* @return
*/
public static boolean isNullOrEmpty(Object obj) {
if (obj == null)
return true; if (obj instanceof CharSequence)
return ((CharSequence) obj).length() == 0; if (obj instanceof Collection)
return ((Collection) obj).isEmpty(); if (obj instanceof Map)
return ((Map) obj).isEmpty(); if (obj instanceof Object[]) {
Object[] object = (Object[]) obj;
if (object.length == 0) {
return true;
}
boolean empty = true;
for (int i = 0; i < object.length; i++) {
if (!isNullOrEmpty(object[i])) {
empty = false;
break;
}
}
return empty;
}
return false;
}
} StringUtil.java

创建 com.chanshuyi.dao.impl.BaseDao.java 类,提供基本的数据库读写对象,并用注解方式将 SqlSession 注入。

package com.chanshuyi.dao.impl;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired; /**
* 所有Service的基类,用来注入sqlSession
*/
public class BaseDao {
/**
* 可写的sqlSession
*/
@Autowired
protected SqlSession writableSQLSession; /**
* 只读的sqlSession
*/
@Autowired
protected SqlSession readonlySQLSession;
}

创建DAO层接口 IUserDao.java:

package com.chanshuyi.dao;

import com.chanshuyi.model.User;

import java.util.List;
import java.util.Map; /**
* Created by chanshuyi on 2015/12/26.
*/
public interface IUserDao {
User getUserById(int userId); /**
*
* @param param Map中的key要与数据库表中的字段名相同
* @return
*/
User getUserByMapSql(Map<String, String> param); List<User> getUserListByMapSql(Map<String, String> param);
}

创建 UserDaoImpl.java 继承 BaseDao.java、实现 IUserDao 接口,并用 @Repository 创建名称为 userDao 的对象。

package com.chanshuyi.dao.impl;

import com.chanshuyi.dao.IUserDao;
import com.chanshuyi.dao.mapper.UserMapper;
import com.chanshuyi.model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository; import java.util.List;
import java.util.Map; /**
* Created by Administrator on 2015/12/26.
*/
@Repository("userDao")
public class UserDaoImpl extends BaseDao implements IUserDao { private static Log logger = LogFactory.getLog(UserDaoImpl.class); @Override
public User getUserById(int userId) {
UserMapper mapper = readonlySQLSession.getMapper(UserMapper.class);
return mapper.selectByPrimaryKey(userId);
} /**
*
* @param param
* @return
*/
@Override
public User getUserByMapSql(Map<String, String> param) {
logger.info("getUserByMapSql 根据动态参数查询用户对象");
return getUserListByMapSql(param).size() > 0 ? getUserListByMapSql(param).get(0) : null;
} /**
* get**MapSql()类的方法只能用于各参数的等于查询
* 例如:select * from user where username = 1 and password = 3 (正确)
* select * from user where username in (1,2,3) (错误,无法实现)
* @param param
* @return
*/
@Override
public List<User> getUserListByMapSql(Map<String, String> param) {
logger.info("getUserListByMapSql 根据动态参数查询用户对象列表");
UserMapper mapper = readonlySQLSession.getMapper(UserMapper.class);
return mapper.getUserListByMapSql(param);
}
}

创建 IUserService.java 和 UserServiceImpl.java。在 UserServiceImpl 中添加 @Service 注解创建名称为 userService 的对象,并将 userDao 对象注入。

package com.mszz.service;

import com.mszz.model.User;

import java.util.List;
import java.util.Map; /**
* Created by chanshuyi on 2015/12/26.
*/
public interface IUserService {
User getUserById(int userId); /**
*
* @param param Map中的key要与数据库表中的字段名相同
* @return
*/
User getUserByMapSql(Map<String, String> param); List<User> getUserListByMapSql(Map<String, String> param);
}
package com.chanshuyi.service.impl;

import com.chanshuyi.dao.IUserDao;
import com.chanshuyi.model.User;
import com.chanshuyi.service.IUserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List;
import java.util.Map; /**
* Created by Administrator on 2015/6/18.
*/
@Service("userService")
public class UserServiceImpl implements IUserService { private static Log logger = LogFactory.getLog(UserServiceImpl.class); @Autowired
IUserDao userDao; @Override
public User getUserById(int userId) {
return userDao.getUserById(userId);
} @Override
public User getUserByMapSql(Map<String, String> param) {
return userDao.getUserByMapSql(param);
} @Override
public List<User> getUserListByMapSql(Map<String, String> param) {
return userDao.getUserListByMapSql(param);
}
}

五、开发控制层(Struts)

创建 com.chanshuyi.action.UserController 类

package com.chanshuyi.controller;

import com.chanshuyi.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map; /**
* Created by Administrator on 2015/6/18.
*/
@Controller("userAction")
@RequestMapping(value="/login")
public class UserController{ private static Logger logger = LoggerFactory.getLogger(UserController.class); private String message; private String username; private String password; @Autowired
private IUserService userService; @Autowired
private HttpServletRequest request; @RequestMapping("")
public String login(@RequestParam(value = "username", required = false) String username,
@RequestParam(value = "password", required = false) String password){
try{
Map<String, String> param = new HashMap<String, String>();
param.put("username", username);
param.put("password", password);
if(userService.getUserByMapSql(param) != null){
message = "登录成功!";
logger.info(message);
}else{
message = "登录失败!";
logger.info(message);
}
}catch(Exception e){
logger.warn(e.getMessage());
e.printStackTrace();
}
request.setAttribute("message", message);
return "index"; // 转到webapp/index.jsp页面
} /******** set/get ********/
public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}

创建 webapp/index.jsp 文件

<%@page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=utf-8" %>
<%@ page isELIgnored="false"%>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Hello World!</h2>
<%-- 通过Struts传递参数,数据传递方式必须选择post,否则编码错误! --%>
<form action="login" method="post" >
<p id="message">${message}</p>
<b>Username:</b><input type="text" id="name" name="username" /><br>
<b>Password:</b><input type="password" id="password" name="password"/><br>
<input type="submit" value="Login"/>
</form>
</body>
</html>

修改 web.xml 文件,加载 SpringMVC 处理器

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name> <!-- 字符集过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- spring MVC的核心就是DispatcherServlet,使用springMVC的第一步就是将下面的servlet放入web.xml
servlet-name属性非常重要,默认情况下,DispatchServlet会加载这个名字-servlet.xml的文件,如下,就会加载
dispather-servlet.xml,也是在WEN-INF目录下。-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 设置dispatchservlet的匹配模式,通过把dispatchservlet映射到/,默认servlet会处理所有的请求,包括静态资源 -->
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

六、启动项目测试

为工程配置 Maven 命令 “tomcat7:run”

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

点击启动项目

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

打开浏览器输入:http://localhost:5050/index.jsp

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

输入 admin/password,点击 Login 按钮

玩转 SSH(六):SpringMVC + MyBatis 架构搭建(注解版)

提示登录成功,说明项目已经成功部署好。

与 Spring 框架项目对比

因为我们一般用 SpringMVC 的时候都是用注解的形式,所以SpringMVC 框架的项目都是注解形式,没有 XML 配置文件方式。下面我们来对比一下用 SpringMVC 和用 Spring + Struts 的实现区别。

1、使用 SpringMVC 框架时需要配置与 Spring 不同的 web.xml 配置,并且读取的根配置文件不再是 applicationContext.xml,而是 servletName-servlet.xml(servletName 表示的是配置在 web.xml 中的servlet 名称)。

2、因为使用了 SpringMVC,所以不再需要 Struts 来接收用户请求,而是直接通过 @RequestMapping 注解的方式在 Controller 类上进行注解映射,也就少了 struts.xml 这个配置文件。而一般情况下用 SpringMVC 的项目更习惯于将 Action 写成 Controller。

链接:http://pan.baidu.com/s/1gdZgyqf 密码:vrm5

上一篇:Aspects 源码学习


下一篇:JQuery+ajax+jsonp 跨域访问