首页 > 代码库 > SpringMVC和MyBatis整合
SpringMVC和MyBatis整合
目前主流的Web MVC框架,除了Struts这个主力 外,还有Spring MVC,主要是由于Spring MVC配置比较简单,使用起来也十分明了,非常灵活,与Spring 集成较好,对RESTful API的支持也比struts要好。
MyBatis是ibatis的升级版,作为hibernate的老对手,它 是一个可以自定义SQL、存储过程和高级映射的持久层框架。
与hibernate的主要区别就是mybatis是半自动化的,而hibernate是全自动的,所以当应用需求越来越复杂的时候,自动化的sql显得比较笨拙。
由于前段时间接了个项目要用springmvc做,所以我抱着练手的态度,又玩起了整合框架的游戏。经常搭框架的人应该都清楚,框架搭建的核心就是配置文件。所以我主要贴下几个配置文件的代码。还是那句话,我都是写好配置文件之后,运行报错再加jar。这里列一下我用的jar包(应该是最少的):
备注:上图有一些额外的jar,比如我用的数据库连接池是阿里巴巴的druid、日志框架式logback,所以引入了相关jar。关于这两个框架的使用和配置都是非常简单的,所以这里就不细说。
1.整合SpringMVC
springMybatis-servlet.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 7 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 8 9 <!-- 启用spring mvc 注解--> 10 <mvc:annotation-driven> 11 </mvc:annotation-driven> 12 13 <!-- 自动扫描的包名 ,使Spring支持自动检测组件,如注解的Controller--> 14 <context:component-scan base-package="com.alibaba.controller" /> 15 <context:component-scan base-package="com.alibaba.service"/> 16 17 18 <!-- 视图解析器:定义跳转的文件的前后缀 --> 19 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 20 <property name="prefix" value="http://www.mamicode.com/WEB-INF/jsp/" /> 21 <property name="suffix" value="http://www.mamicode.com/.jsp" /> <!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 --> 22 </bean> 23 24 <!--配置拦截器, 多个拦截器,顺序执行 --> 25 <mvc:interceptors> 26 <mvc:interceptor> 27 <!-- 匹配的是url路径 --> 28 <mvc:mapping path="/" /> 29 <mvc:mapping path="/user/**" /> 30 <mvc:mapping path="/test/**" /> 31 32 <bean class="com.alibaba.interceptor.CommonInterceptor"></bean> 33 </mvc:interceptor> 34 <!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 --> 35 </mvc:interceptors> 36 37 </beans>
2.整合Mybatis
spring-dao.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 8 9 <!-- 该包下的类支持注解,表示会被当作{@code mybatis mapper}处理 配置了之后表示可以自动引入mapper类--> 10 <mybatis:scan base-package="com.alibaba.dao"/> 11 <!--引入属性文件 --> 12 <context:property-placeholder location="classpath:configuration.properties"/> 13 14 <!--数据库连接--> 15 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 16 <property name="url" value="http://www.mamicode.com/${jdbc.url}" /> 17 <property name="username" value="http://www.mamicode.com/${jdbc.username}"/> 18 <property name="password" value="http://www.mamicode.com/${jdbc.password}"/> 19 <!-- 配置初始化大小、最小、最大 --> 20 <property name="initialSize"><value>1</value></property> 21 <property name="maxActive"><value>5</value></property> 22 <property name="minIdle"><value>1</value></property> 23 <!-- 配置获取连接等待超时的时间 --> 24 <property name="maxWait"><value>60000</value></property> 25 <!-- 配置监控统计拦截的filters --> 26 <property name="filters"><value>stat</value></property> 27 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> 28 <property name="timeBetweenEvictionRunsMillis"><value>60000</value></property> 29 <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> 30 <property name="minEvictableIdleTimeMillis"><value>300000</value></property> 31 <!-- 32 <property name="validationQuery"><value>SELECT ‘x‘</value></property> 33 <property name="testWhileIdle"><value>true</value></property> 34 <property name="testOnBorrow"><value>false</value></property> 35 <property name="testOnReturn"><value>false</value></property> 36 <property name="poolPreparedStatements"><value>true</value></property> 37 <property name="maxOpenPreparedStatements"><value>20</value></property> 38 --> 39 </bean> 40 41 <!-- mybatis配置 --> 42 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 43 <property name="dataSource" ref="dataSource" /> 44 </bean> 45 </beans>
3.web.xml整合SpringMVC和Mybatis
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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"> 3 <!-- 该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问 http://localhost/foo.css ,现在http://localhost/static/foo.css --> 4 <!-- 不拦截静态文件 --> 5 <servlet-mapping> 6 <servlet-name>default</servlet-name> 7 <url-pattern>/js/*</url-pattern> 8 <url-pattern>/css/*</url-pattern> 9 <url-pattern>/images/*</url-pattern> 10 <url-pattern>/fonts/*</url-pattern> 11 </servlet-mapping> 12 13 <!-- 配置字符集 --> 14 <filter> 15 <filter-name>encodingFilter</filter-name> 16 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 17 <init-param> 18 <param-name>encoding</param-name> 19 <param-value>UTF-8</param-value> 20 </init-param> 21 <init-param> 22 <param-name>forceEncoding</param-name> 23 <param-value>true</param-value> 24 </init-param> 25 </filter> 26 <filter-mapping> 27 <filter-name>encodingFilter</filter-name> 28 <url-pattern>/*</url-pattern> 29 </filter-mapping> 30 31 <!-- 初始化 DispatcherServlet时,该框架在 web应用程序WEB-INF目录中寻找一个名为[servlet-名称]-servlet.xml的文件, 32 并在那里定义相关的Beans,重写在全局中定义的任何Beans --> 33 <servlet> 34 <servlet-name>springMybatis</servlet-name> 35 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 36 <load-on-startup>1</load-on-startup> 37 </servlet> 38 <servlet-mapping> 39 <servlet-name>springMybatis</servlet-name> 40 <!-- 所有的的请求,都会被DispatcherServlet处理 --> 41 <url-pattern>/</url-pattern> 42 </servlet-mapping> 43 44 <context-param> 45 <param-name>contextConfigLocation</param-name> 46 <param-value>/WEB-INF/config/spring-*.xml</param-value> 47 </context-param> 48 <listener> 49 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 50 </listener> 51 <!-- druid web 监控 --> 52 <servlet> 53 <servlet-name>DruidStatView</servlet-name> 54 <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> 55 </servlet> 56 <servlet-mapping> 57 <servlet-name>DruidStatView</servlet-name> 58 <url-pattern>/druid/*</url-pattern> 59 </servlet-mapping> 60 61 <error-page> 62 <error-code>404</error-code> 63 <location>/error/404.jsp</location> 64 </error-page> 65 <error-page> 66 <error-code>500</error-code> 67 <location>/error/500.jsp</location> 68 </error-page> 69 </web-app>
4.logback.xml日志配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <configuration> 3 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 4 <encoder> 5 <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> 6 </encoder> 7 </appender> 8 <logger name="test.LogbackTest" level="TRACE"/> 9 <logger name="com.alibaba.controller.TestController" level="TRACE"/> 10 <logger name="org.springframework.web.servlet.DispatcherServlet" level="DEBUG" /> 11 <logger name="druid.sql" level="INFO" /><!-- 如果spring-config里面没有配置slf4j,就不会显示sql日志,logback只是slf4j的一个实现 --> 12 <root level="debug"> 13 <appender-ref ref="STDOUT" /> 14 </root> 15 </configuration>
5.configuration.properties配置
1 jdbc.url=jdbc\:mysql\://localhost\:3306/druid?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNull 2 jdbc.username=root 3 jdbc.password=123456
6.测试搭建是否成功,后台代码
首先是登录,用了加密,可以去掉
1 package com.alibaba.controller; 2 3 4 import javax.annotation.Resource; 5 import javax.servlet.http.HttpServletRequest; 6 7 import org.apache.commons.codec.digest.DigestUtils; 8 import org.slf4j.Logger; 9 import org.slf4j.LoggerFactory; 10 import org.springframework.stereotype.Controller; 11 import org.springframework.web.bind.annotation.RequestMapping; 12 import org.springframework.web.bind.annotation.RequestMethod; 13 import org.springframework.web.bind.annotation.RequestParam; 14 15 import com.alibaba.model.User; 16 import com.alibaba.service.UserService; 17 import com.alibaba.util.RequestUtil; 18 19 /** 20 * @author tfj 21 * 2014-7-26 22 */ 23 @Controller 24 public class SystemController { 25 private final Logger log = LoggerFactory.getLogger(SystemController.class); 26 @Resource 27 private UserService userService; 28 29 @RequestMapping(value = "http://www.mamicode.com/",method = RequestMethod.GET) 30 public String home() { 31 log.info("返回首页!"); 32 return "index"; 33 } 34 35 @RequestMapping(value = "http://www.mamicode.com/test/hello",method = RequestMethod.GET) 36 public String testHello() { 37 log.info("执行了testHello方法!"); 38 return "testHello"; 39 } 40 41 @RequestMapping(value = "http://www.mamicode.com/login",method = RequestMethod.POST) 42 public String testLogin(HttpServletRequest request,@RequestParam String username, @RequestParam String password) { 43 log.info("执行了testLogin方法!"); 44 User user = userService.findUserByName(username); 45 if(user!=null){ 46 if(user.getPassword().equals(DigestUtils.md5Hex(password))){ 47 request.getSession().setAttribute("userId", user.getId()); 48 request.getSession().setAttribute("user", username); 49 return "redirect:" + RequestUtil.retrieveSavedRequest();//跳转至访问页面 50 }else{ 51 log.info("密码错误"); 52 request.getSession().setAttribute("message", "用户名密码错误,请重新登录"); 53 return "login"; 54 } 55 }else{ 56 log.info("用户名不存在"); 57 request.getSession().setAttribute("message", "用户名不存在,请重新登录"); 58 return "login"; 59 } 60 } 61 }
关于service和model就不写了,写一下mybatis的mapper类映射
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <mapper namespace="com.alibaba.dao.UserMapper"> 4 <select id="findUserByName" resultType="com.alibaba.model.User"> 5 select id, username , password from sysuser where username = #{username} 6 </select> 7 </mapper>
7.前台jsp主要是登录和登录成功的页面,就不写了
贴一下截图:
到此,springmvc+mybatis整合成功。后续复杂的功能待添加
注意事项
1.框架中关于druid和logback的配置都是从官网上copy下来的,所以都是最基本的,读者可以忽略,也可以换成读者熟悉的数据库组件和日志框架,如c3p0和log4j。
2.代码里加入了权限管理,即访问前需登录,登录后跳转至待访问页面。
3.本文是从我的测试代码里剥离出来的最简单的也是最基本的代码,有些没剥离干净的地方还请见谅。
SpringMVC和MyBatis整合