SpringMVC+Mybatis整合实例及功能分析

来源:互联网 发布:软件编程技术 编辑:程序博客网 时间:2024/05/22 13:41

SpringMVC:Java B/S项目的MVC框架,替换JavaWeb开发的servlet,filter,listener。
Mybatis:Java ORM关系框架亦可理解为数据库框架,替换JDBC完成数据库交互,将数据库和程序连接起来。
传统JavaWeb端开发servlet写后台,每个servlet都得单独配置,且常用的功能均无封装,项目结构不易控制,开发效率低,无统一标准,项目更新维护很困难。
Java访问数据库底层是用JDBC,但完成一次数据读取,需要connection打开数据库,datareader数据库读取,command数据库操作,提交,释放资源,非常繁琐。
所有程序的框架都是依赖于该语言所制定的标准发展出来的,目的是为了提升程序的开发效率,而不是执行效率。
该项目是maven项目,maven可以理解为控制项目结构的脚步语言,通过它可以很方便的对项目结构进行扩展更改。
项目结构图
controller 控制器,mapper 数据库访问层,entity 实体层,service 中间控制层

web.xml  JavaWeb项目核心配置文件,配置项目的整体结构及规则。该文件中配置请求规则,错误界面,项目主页等。

<?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" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <!-- 静态资源不需要编译解析将其交给服务器默认处理,SpringMVC也可处理静态资源,相关缓存设置,但服务器容器(Tomcat或其他)已有相关功能,无需画蛇添足。 -->  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.jpg</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.pdf</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.docx</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.xlsx</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.png</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.gif</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.html</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.psd</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.js</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.css</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.swf</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.otf</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.eot</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.svg</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.ttf</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.woff</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>default</servlet-name>    <url-pattern>*.woff2</url-pattern>  </servlet-mapping>  <!-- 当程序异常时会根据错误类型直接跳到已配置好的错误界面 -->  <!-- 404错误界面 -->  <error-page>    <error-code>404</error-code>    <location>/404.html</location>  </error-page>  <!-- 500错误界面 -->  <error-page>    <error-code>500</error-code>    <location>/500.html</location>  </error-page>  <!-- 项目名称 -->  <display-name>springmvc</display-name>  <!-- 项目主页  对应webAPP根目录 -->  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <!-- SpringMVC配置  项目的servlet,listener均改为SpringMVC控制 -->  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!-- 加载配置文件  resources目录下所有已xml结尾的文件 -->  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:*.xml</param-value>  </context-param>  <servlet>    <servlet-name>spring</servlet-name>    <servlet-class>            org.springframework.web.servlet.DispatcherServlet    </servlet-class>    <!-- SpringMVC配置文件 -->       <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:spring-mvc.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>spring</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping></web-app>

jdbc-context.xml 数据库配置文件(SpringMVC已对Mybatis进行了封装,简单的几行代码就能完成对数据库的配置)

<?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:tx="http://www.springframework.org/schema/tx"     xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop"    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/context            http://www.springframework.org/schema/context/spring-context-3.0.xsd            http://www.springframework.org/schema/aop            http://www.springframework.org/schema/aop/spring-aop.xsd             ">    <context:property-placeholder location="classpath:jdbc.properties" />    <!-- Enable annotation style of managing transactions -->    <tx:annotation-driven transaction-manager="transactionManager" />    <!-- Declare a datasource that has pooling capabilities -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"        destroy-method="close" p:driverClass="${app.jdbc.driverClassName}"        p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}"        p:acquireIncrement="10" p:idleConnectionTestPeriod="60" p:maxPoolSize="100"        p:maxStatements="100" />    <!-- Declare a transaction manager -->    <bean id="transactionManager"        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"        p:dataSource-ref="dataSource" />    <!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <!-- mybatisORM关系映射更多配置,若有需求在自行配置 <property name="configLocation" value="classpath:sqlmap-config.xml" /> -->    </bean>    <!-- scan for mappers and let them be autowired -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="basePackage" value="mapper" />    </bean>    <!-- mapper,多表插入事务回滚,一般与service配合    -->     <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="query*" read-only="true" propagation="REQUIRED" />            <tx:method name="quert*" read-only="true" propagation="REQUIRED" />            <tx:method name="page*" read-only="true" propagation="REQUIRED" />            <tx:method name="get*" read-only="true" propagation="REQUIRED" />            <tx:method name="save*" propagation="REQUIRED" isolation="READ_COMMITTED" />            <tx:method name="set*" propagation="REQUIRED" isolation="READ_COMMITTED" />            <tx:method name="insert*" propagation="REQUIRED" isolation="READ_COMMITTED" />            <tx:method name="update*" propagation="REQUIRED" isolation="READ_COMMITTED" />            <tx:method name="delete*" propagation="REQUIRED" isolation="READ_COMMITTED" />        </tx:attributes>    </tx:advice>    <aop:config>          <aop:pointcut id="allManagerMethod"              expression="execution(* service.*.*(..))" />          <aop:advisor advice-ref="txAdvice"              pointcut-ref="allManagerMethod" />      </aop:config> </beans>

spring-mvc.xml  SpringMVC配置文件

<?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:tx="http://www.springframework.org/schema/tx"      xmlns:websocket="http://www.springframework.org/schema/websocket"    xmlns:context="http://www.springframework.org/schema/context"        xmlns:mvc="http://www.springframework.org/schema/mvc"        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/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/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd    ">     <!-- 自动扫描的包名 -->     <context:component-scan base-package="controller" />    <!-- 视图解释类 -->      <bean id="viewResolver"        class="org.springframework.web.servlet.view.UrlBasedViewResolver">        <property name="viewClass"            value="org.springframework.web.servlet.view.JstlView" />        <property name="prefix" value="/WEB-INF/jsp/" />        <property name="suffix" value=".jsp" />    </bean>    <!-- 开启注解 -->    <mvc:annotation-driven />    <context:annotation-config />      <!--  SpringMVC 静态资源处理,不推荐如此配置。静态资源不需要编译解析,交给服务器自动解析就好,Tomcat服务器自带缓存结构,会自动缓存静态资源文件    <mvc:resources mapping="/html/**" location="/html/" cache-period="31556926"/>      <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>      <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>      <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>    -->    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->      <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          <property name="defaultEncoding" value="UTF-8"/>          <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->          <property name="maxUploadSize" value="200000"/>      </bean>      <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->      <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->      <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">          <property name="exceptionMappings">              <props>                  <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->                  <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>              </props>          </property>      </bean>  </beans>

Spring.xml  @Service配置文件

<?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-4.1.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-4.1.xsd">    <!--自动扫描含有@Service将其注入为bean -->    <context:component-scan base-package="service" /></beans>

sqlmap-config.xml  MybatisORM实体配置(Mybatis单独配置文件,本项目中有没有此文件不影响项目运行)

<?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>        <!-- changes from the defaults -->        <setting name="lazyLoadingEnabled" value="false" />    </settings>    <typeAliases>        <typeAlias type="entity.User" alias="user"/>    </typeAliases></configuration>

UserContoller:

package controller;import java.util.List;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;import entity.User;import mapper.UserMapper;@Controller@RequestMapping(value = "/user")public class UserController {    private UserMapper userMapper;    @Autowired    public void setMapper(UserMapper userMapper) {        this.userMapper = userMapper;    }    @RequestMapping(method = RequestMethod.GET)    public String showForm(ModelMap model) {        List<User> users = userMapper.getAllUser();        model.addAttribute("users", users);        return "list";    }    @RequestMapping(value = "/add")    public String add(HttpServletRequest request,HttpServletResponse response,Model model) {        String userName = request.getParameter("userName");        String password = request.getParameter("password");        User user = new User();        user.setId(UUID.randomUUID().toString());        user.setUserName(userName);        user.setPassword(password);        userMapper.addUser(user);        List<User> list = userMapper.getAllUser();        model.addAttribute("users",list);        return "list";    }    @RequestMapping(value = "/detail")    public String detail(Model model, HttpServletRequest request,HttpServletResponse response) {        String id = request.getParameter("id");        User user = userMapper.getUserById(id);        model.addAttribute("user", user);        return "detail";    }    @RequestMapping(value = "/delete")    public String delete(Model model, HttpServletRequest request,HttpServletResponse response) {        String id = request.getParameter("id");        userMapper.deleteById(id);        List<User> list = userMapper.getAllUser();        model.addAttribute("users", list);        return "list";    }    @RequestMapping(value = "/toupdate")    public String toUpdate(Model model, HttpServletRequest request,HttpServletResponse response) {        String id = request.getParameter("id");        User user = userMapper.getUserById(id);        model.addAttribute("user", user);        return "update";    }    @RequestMapping(value = "/update")    public ModelAndView update(HttpServletRequest request,HttpServletResponse response) {        String id = request.getParameter("sid");        String userName = request.getParameter("userName");        String password = request.getParameter("password");        User user = new User();        user.setId(id);        user.setUserName(userName);        user.setPassword(password);        userMapper.update(user);        ModelAndView mv = new ModelAndView("list");        List<User> list = userMapper.getAllUser();        mv.addObject("users", list);        return mv;    }}

UserServiceImp

package service;import java.util.List;import mapper.UserMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import entity.User;@Service("hotelService")public class UserServiceImp implements UserService{    @Autowired    private UserMapper userMapper;    public List<User> list(){        return userMapper.getAllUser();    }    //批量操作,多表操作等复杂逻辑可以封装到此层中,再配合数据库配置,可完成数据异常回滚等操作    public int update(User user) {        user.setUserName("1");        userMapper.update(user);        //password超长错误   若配置了回滚,上行代码对数据库的操作便不生效,username仍是原来的值而不是1        user.setPassword("1111111111111111111111111111111111111111111111111111");        userMapper.update(user);        return 0;    }}

service层可根据项目需求是否添加,若某些业务逻辑涉及到多表的联动,为保证数据的准确性,可以在该层封装,在配合Mybatis配置文件即可完成数据库的事务回滚

<!-- mapper,多表插入事务回滚,一般与service配合    -->     <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="query*" read-only="true" propagation="REQUIRED" />            <tx:method name="quert*" read-only="true" propagation="REQUIRED" />            <tx:method name="page*" read-only="true" propagation="REQUIRED" />            <tx:method name="get*" read-only="true" propagation="REQUIRED" />            <tx:method name="save*" propagation="REQUIRED" isolation="READ_COMMITTED" />            <tx:method name="set*" propagation="REQUIRED" isolation="READ_COMMITTED" />            <tx:method name="insert*" propagation="REQUIRED" isolation="READ_COMMITTED" />            <tx:method name="update*" propagation="REQUIRED" isolation="READ_COMMITTED" />            <tx:method name="delete*" propagation="REQUIRED" isolation="READ_COMMITTED" />        </tx:attributes>    </tx:advice>    <aop:config>          <aop:pointcut id="allManagerMethod"              expression="execution(* service.*.*(..))" />          <aop:advisor advice-ref="txAdvice"              pointcut-ref="allManagerMethod" />      </aop:config> 

其他的代码就不贴了,实例中有也有MySQL的配置。
项目中ojdbc14这个包因为版权问题,无法从maven官网直接下载,需另行下载放到lib文件夹下或通过maven命令加载到本地仓储中

mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0.3.0 -Dpackaging=jar -Dfile=d:\ojdbc14-10.2.0.3.0.jar  

项目下载地址:
http://download.csdn.net/detail/lishengko/9759013

0 0