首页 > 代码库 > spring mvc+mybatis整合 (二)

spring mvc+mybatis整合 (二)

转:http://lifeneveralone.diandian.com/post/2012-11-02/40042292065

本文介绍使用spring mvc结合Mybatis搭建一个应用程序框架.

demo源码下载:springMVC-Mybatis


1.准备工作:

spring的jar包:

spring-beans-3.1.0.RELEASE.jar

spring-core-3.1.0.RELEASE.jar

spring-web-3.1.0.RELEASE.jar

spring-webmvc-3.1.0.RELEASE.jar

spring-context-3.1.0.RELEASE.jar

spring-expression-3.1.0.RELEASE.jar

spring-aop-3.1.0.RELEASE.jar

spring-asm-3.1.0.RELEASE.jar

spring-context-support-3.1.0.RELEASE.jar

 

mybatis与Spring的整合所需的包:

mysql-connector-java-5.1.21-bin.jar

mybatis-spring-1.1.1.jar

mybatis-3.1.1.jar

 

JDBC驱动:

mysql-connector-java-3.1.6-bin.jar

 

公共jar包:

commons-dbcp-1.4.jar

commons-io-2.0.1.jar

commons-logging-1.1.1.jar

commons-pool-1.6.jar

hibernate-validator-4.1.0.Final.jar

slf4j-api-1.6.1.jar

slf4j-log4j12-1.6.1.jar

log4j-1.2.16.jar

 

2.web.xml配置

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

 <display-name>shop</display-name>

   

 <!-- log4j配置初始化 -->

 <context-param>

   <param-name>log4jConfigLocation</param-name>

   <param-value>WEB-INF/log4j/log4j.properties</param-value>

 </context-param>

 <!-- log4j的配置每分钟刷新一次,这样在后续定位问题是修改日志配置后不需要重启系统 -->

 <context-param>

   <param-name>log4jRefreshInterval</param-name>

   <param-value>60000</param-value>

 </context-param>

 <listener>

   <listener-class>  

           org.springframework.web.util.Log4jConfigListener  

       </listener-class>

 </listener>

   

 <!-- spring配置初始化 -->

 <context-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>/WEB-INF/spring/*-context.xml</param-value>

 </context-param>

 <listener>

   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

 </listener>

   

 <!-- Spring MVC配置,配置分发器 -->

 <servlet>

   <servlet-name>appServlet</servlet-name>

   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

   <init-param>

     <param-name>contextConfigLocation</param-name>

     <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>

   </init-param>

   <load-on-startup>1</load-on-startup>

 </servlet>

 <servlet-mapping>

   <servlet-name>appServlet</servlet-name>

   <url-pattern>/</url-pattern>

 </servlet-mapping>

   

 <!-- 配置欢迎界面 -->

 <welcome-file-list>

   <welcome-file>index.jsp</welcome-file>

 </welcome-file-list>

   

</web-app>

 

3.spring mvc的配置servlet-context.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/mvc"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xmlns:beans="http://www.springframework.org/schema/beans"

   xmlns:context="http://www.springframework.org/schema/context"

   xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

       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">

       <!-- DispatcherServlet Context: defines this servlet‘s request-processing infrastructure -->

   

   <!-- Enables the Spring MVC @Controller programming model -->

   <annotation-driven />

   

   <context:annotation-config />

 

   <context:component-scan base-package="com.huawei.shop.controller" />

 

   <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->

   <resources mapping="/js/**" location="/js/" />

   <resources mapping="/css/**" location="/css/" />

   <resources mapping="/images/**" location="/images/" />

   

   <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->

   <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

       <beans:property name="prefix" value="/jsp/" />

       <beans:property name="suffix" value=".jsp" />

   </beans:bean>

   

   

   <!-- Imports user-defined @Controller beans that process client requests -->

   <!--

   <beans:import resource="controllers.xml" />

    -->

</beans:beans>

 

4.Mybatis-spring的配置:mybatis-context.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:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:context="http://www.springframework.org/schema/context"

    xmlns:jdbc="http://www.springframework.org/schema/jdbc"

    xsi:schemaLocation="

    http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-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/jdbc

     http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd

    http://www.springframework.org/schema/aop

    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

    http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd"

>

 

<!-- enable autowire -->

   <context:annotation-config />

<context:component-scan base-package="com.huawei.shop.*" />

 

   <!--配置jdbc.properties文件的位置信息,路径还是区分大小写 -->

   <bean  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

   <property name="locations" value="http://www.mamicode.com/WEB-INF/jdbc/jdbc.properties" />  

   </bean>  

   

   <!-- 读取jdbc.properties文件,配置数据源 -->  

   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"   destroy-method="close">   

   <property name="driverClassName" value="http://www.mamicode.com/${jdbc.driver}" />   

   <property name="url" value="http://www.mamicode.com/${jdbc.url}" />

   <property name="username" value="http://www.mamicode.com/${jdbc.user}" />   

   <property name="password" value="http://www.mamicode.com/${jdbc.password}" />   

   <!-- 数据库连接池配置 -->   

   <property name="initialSize" value="http://www.mamicode.com/${jdbc.initialPoolSize}" />

   <!-- 初始化连接数量 -->   

   <property name="maxActive" value="http://www.mamicode.com/${jdbc.maxPoolSize}" />

   <!-- 最大连接数量 -->   

   <property name="maxIdle" value="http://www.mamicode.com/${jdbc.maxIdlePollSize}" />

   <!-- 最大空闲连接数量 -->   

   <property name="minIdle" value="http://www.mamicode.com/${jdbc.mixIdlePollSize}" />

   <!-- 最小空闲连接数量 -->  

   </bean>

 

<!-- sqlSessionFactory --><!-- MyBatis在spring中Bean的配置,都是固定的 -->  

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">   

<property name="configLocation" value="http://www.mamicode.com/WEB-INF/mybatis/Mybatis-Configuration.xml" />   

<property name="dataSource" ref="dataSource" />

<property name="mapperLocations">

<list>

<value>WEB-INF/mybatis/*Mapper.xml</value>

</list>

</property>  

<property name="typeAliasesPackage" value="http://www.mamicode.com/com.huawei.shop.model" />

</bean>  

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">   

<constructor-arg index="0" ref="sqlSessionFactory" />  

</bean>

<!--

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

       <property name="basePackage" value="http://www.mamicode.com/com.huawei.shop.repository" />

   </bean>

     -->

     

     <!-- scan for mappers and let them be autowired -->

   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

       <property name="basePackage" value="http://www.mamicode.com/com.huawei.shop.repository" />

   </bean>

 

</beans>

 

5.Mybatis的配置:Mybatis-Configuration.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>

<settings>

   

    <!-- 全局的映射器启用或禁用缓存。 -->

<setting name="cacheEnabled" value="http://www.mamicode.com/true" />

<!-- 全局启用或禁用延迟加载 -->

        <setting name="lazyLoadingEnabled" value="http://www.mamicode.com/true" />

         

        <!-- 允许或不允许多种结果集从一个单独的语句中返回 -->

        <setting name="multipleResultSetsEnabled" value="http://www.mamicode.com/true" />

        

        <!-- 设置超时时间 -->

        <setting name="defaultStatementTimeout" value="http://www.mamicode.com/25000" />

        

</settings>

<!--

<typeAliases>  

       <typeAlias alias="AdminTable" type="com.huawei.shop.model.AdminTable"/>

   </typeAliases>  

   -->

 <!-- 对应vo类的DAO接口 所对应的xml配置文件的路径信息    -->

 <!--

 <mappers>

 <mapper resource="AdminTable.xml" />  

 </mappers>

   -->

</configuration>

 

6.jdbc的配置:jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://127.0.0.1:3306/cop?useUnicode=true&characterEncoding=UTF-8

jdbc.user=root

jdbc.password=root

 

jdbc.initialPoolSize=10

jdbc.maxPoolSize=50

jdbc.maxIdlePollSize=50

jdbc.mixIdlePollSize=10

 

log4j的配置就不贴了,到目前为止,我们大致完成了spring mvc + mybatis的框架的所有配置文件。为了有效减少配置文件,我们使用了spring的annotation。实践证明,基于annotation的spring mvc + mybatis的框架是可以做到后续的开发零配置,但是个人觉得,为了有效管理Mybatis的sql语句(这些是在我们开发过程中可能会不停的修改的。而spring的配置一般是一次配置,后续就会很少修改),我们将sql语句使用了映射文件,而不是以注释方式写在代码里面。

下面,我们来看具体的代码实践。本demo实现了从页面输入一个用户名和密码,到数据库校验密码是否正确的功能,一个简单的登录流程。

1.login.jsp,主要实现了一个表单提交的功能:

<div>

<form id="login" name="login" action="login" method="post">

<table>

<tr>

<td>用户名</td>

<td><input id="name" name="name" type="text" /></td>

</tr>

<tr>

<td>密码</td>

<td><input id="password" name="password" type="password" /></td>

</tr>

<tr>

<td><input value="http://www.mamicode.com/登录" type="submit" onclick="disp_alert()"/></td>

</tr>

</table>

</form>

</div>

 

2.LoginController.java

package com.huawei.shop.controller;

 

import java.util.List;

 

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

 

import com.huawei.shop.model.AdminTable;

import com.huawei.shop.model.ConfigTable;

import com.huawei.shop.service.AdminService;

import com.huawei.shop.service.ConfigService;

 

 

@Controller

public class LoginController

{

private static final Logger logger = Logger.getLogger("DEBUG");

@Autowired

private AdminService adminService;

@Autowired

private ConfigService configService;

@RequestMapping(value = "http://www.mamicode.com/login", method = RequestMethod.POST)

public String login(String name, String password, Model model)

{

logger.error("name = "+name);

AdminTable admin = adminService.getUserPassword(name);

List<ConfigTable> configs = configService.getAllConfig();

       String passwd = admin.getPassword();

       model.addAttribute("admin", admin);

       model.addAttribute("name", name);

       model.addAttribute("password", password);

       model.addAttribute("configs", configs);

   

if (passwd.equals(password))

{

return "home";

}

return "error";

}

}

 

3.AdminService.java

package com.huawei.shop.service;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.huawei.shop.model.AdminTable;

import com.huawei.shop.repository.AdminMapper;

 

@Service

public class AdminService

{

@Autowired

private AdminMapper adminMapper;

public AdminTable getUserPassword(String name) {

   return adminMapper.getUserPassword(name);

 }

}

 

4.AdminMapper.java

 

package com.huawei.shop.service;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.huawei.shop.model.AdminTable;

import com.huawei.shop.repository.AdminMapper;

 

@Service

public class AdminService

{

@Autowired

private AdminMapper adminMapper;

public AdminTable getUserPassword(String name) {

   return adminMapper.getUserPassword(name);

 }

}

 

5.AdminTable.java

package com.huawei.shop.model;

 

 

public class AdminTable

{

private String name;

private String password;

 

public String getName()

{

return name;

}

 

public void setName(String name)

{

this.name = name;

}

 

public String getPassword()

{

return password;

}

 

public void setPassword(String password)

{

this.password = password;

}

 

}

 

6.AdminTable-Mapper.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.huawei.shop.repository.AdminMapper">

<resultMap id="AdminMap" type="AdminTable" >

<id property="name" column="AD_NAME"></id>

<id property="password" column="AD_PASSWORD"></id>

</resultMap>

<select id="getUserPassword" parameterType="String" resultMap="AdminMap"> select

AD_NAME, AD_PASSWORD from ADMIN where AD_NAME=#{name}  </select>

</mapper>