君临-行者无界

导航

spring、springmvc和mybatis整合(xml方式)

  今天搭建一个基于xml的ssm整合demo。话不多说,直接上代码。

  我的开发环境如下:

  web服务器:tomcat8

  开发工具:STS

  JDK版本:1.8

  项目构建工具:maven

  1、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>io.powerx</groupId>
  <artifactId>springmvcxml</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springmvcxml Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
        <!-- spring相关 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- springmvc相关 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <!-- 使用aspectj做切面 -->
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.5.3</version>
        </dependency>
        
        <!-- servlet配置,不配置也不影响,但是jsp会报错 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        
        <!-- 加载jackson包 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.7.3</version>
        </dependency>
        <!-- druid数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.16</version>
        </dependency>
        <!-- spring和mybatis整合 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!-- MySQL数据库连接驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.43</version>
        </dependency>
        <!-- MyBatis框架 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- 添加logback日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
        
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

  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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/jsp/404.jsp</location>
    </error-page>
    <welcome-file-list>
        <welcome-file>user/index</welcome-file>
    </welcome-file-list>
    <!-- 指定spring配置文件的路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-*.xml</param-value>
    </context-param>
    <!-- spring监听器 ,在服务器启动阶段,该监听器实例会被创建,解析spring的配置文件;该监听器实现了ServletContextListener接口
        在创建或者销毁ServletContext对象,监听器中的方法会被执行-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--配置自己的监听器,用于初始化工作  -->
    <listener>
        <listener-class>powerx.io.config.SystemInitListener</listener-class>
    </listener>
    <!-- 解决post请求中文乱码的过滤器 -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- springMVC中央调度器 :接收客户端发送的请求,交给对应的处理器处理,将处理器返回的结果相应给浏览器客户端-->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置初始化参数:指定springMVC配置文件的路径 ;如果不指定该参数,默认会去WEB-INF目录下,寻找[servlet-name]-servlet.xml文件,
            但是一般情况下,我们都会指定springMVC配置文件的路径,而且该路径的形式和spring其它配置文件的形式相同-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!-- 在服务器启动阶段  实例化该servlet -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/user/index</url-pattern>
    </servlet-mapping>
</web-app>

  3、spring配置:spring-base.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: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.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <!-- 配置组件扫描器 -->
    <context:component-scan base-package="powerx.io.service"/>
            
    <!-- 引入外部的配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 数据源Druid 连接池  -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${spring.datasource.driverClassName}"/>
        <property name="url" value="${spring.datasource.url}"/>
        <property name="username" value="${spring.datasource.username}"/>
        <property name="password" value="${spring.datasource.password}"/>
        <property name="initialSize" value="${spring.datasource.initialSize}"/>
        <property name="minIdle" value="${spring.datasource.minIdle}"/>
        <property name="maxActive" value="${spring.datasource.maxActive}"/>
        <property name="maxWait" value="${spring.datasource.maxWait}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${spring.datasource.timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${spring.datasource.minEvictableIdleTimeMillis}"/>
        <property name="validationQuery" value="${spring.datasource.validationQuery}"/>
        <property name="testWhileIdle" value="${spring.datasource.testWhileIdle}"/>
        <property name="testOnBorrow" value="${spring.datasource.testOnBorrow}"/>
        <property name="testOnReturn" value="${spring.datasource.testOnReturn}"/>
        <property name="poolPreparedStatements" value="${spring.datasource.poolPreparedStatements}"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${spring.datasource.maxPoolPreparedStatementPerConnectionSize}"/>
        <property name="filters" value="${spring.datasource.filters}"/>
        <property name="connectionProperties" value="${spring.datasource.connectionProperties}"/>
    </bean>
    
    <!-- sessionFactory -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 指定mybatis映射文件的地址 -->
        <property name="mapperLocations">
            <list>
                <value>classpath:mappers/*.xml</value>
            </list>
        </property>
    </bean>
    
    <!-- 映射扫描器  会通过代理的方式创建dao接口对应的实现类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="powerx.io.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
    </bean>
    
    <!-- 事务管理器 transactionManager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 事务通知Advice -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 切入 -->
    <aop:config>
        <aop:advisor advice-ref="transactionAdvice" pointcut="execution(* powerx.io.service.*.*(..))" />
    </aop:config>
</beans>

  4、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>
    <settings>
        <!-- 主要解决插入数据存在空值的情况 -->
        <setting name="jdbcTypeForNull" value="NULL"/>
    </settings>
    <!-- 别名 -->
    <typeAliases>
        <package name="powerx.io.model"/>        
    </typeAliases>
</configuration>

  5、spring-mvc.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:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    
    <!-- 注册组件扫描器 -->
    <context:component-scan base-package="powerx.io.controller"/>
    
    <!-- 注册springMVC注解驱动 ,开启消息转换器-->
    <mvc:annotation-driven/>
    
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 注册拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*/*.do"/>
            <mvc:exclude-mapping path="/user/login.do"/>
            <bean class="powerx.io.config.AuthInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

  6、jdbc.properties

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/testssm
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

  7、其它的一些demo类和配置

  UserDao.java

package powerx.io.dao;

import powerx.io.model.User;

public interface UserDao {

    User findByName(String userName);
    
    int insertUser(User user);
}

  UserMapper.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="powerx.io.dao.UserDao">
    <resultMap type="User" id="UserResult">
        <!-- 数据库字段和实体类属性映射关系,名称一样的字段可以无需映射。column对应数据库的实际字段,property对应实体类的属性 -->
        <result column="USER_NAME" property="userName" />
        <result column="USER_PWD" property="userPwd" />
    </resultMap>
    
    <select id="findByName" parameterType="String" resultMap="UserResult">
        SELECT USER_NAME,USER_PWD FROM USER WHERE USER_NAME=#{userName} 
    </select>
    
    <insert id="insertUser" parameterType="powerx.io.model.User">
    INSERT INTO USER(USER_NAME,USER_PWD) VALUES(#{userName},#{userPwd})
  </insert>
    
</mapper>

  User.java

package powerx.io.model;

public class User {

    private String userName;
    private String userPwd;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPwd() {
        return userPwd;
    }
    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
    
}

  UserService.java,这里省去了service层的接口

package powerx.io.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import powerx.io.dao.UserDao;
import powerx.io.model.User;

@Service
public class UserService {
    
    @Autowired
    private UserDao userDao;
    public User findByName(String userName) {
        return userDao.findByName(userName);
     }
    
    public int insertUser(User user) {
        //测试事务是否起作用
        return userDao.insertUser(user);
     }

}

  UserContoller.java

package powerx.io.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.ResponseBody;

import powerx.io.model.User;
import powerx.io.service.UserService;
@RequestMapping("/user")
@Controller
public class UserContoller {

    public static Logger logger = LoggerFactory.getLogger("monitor");
    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/login.do")
    public Object getData(String userName, String password, HttpServletRequest request) {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        User user = userService.findByName(userName);
        if (user != null) {
            if (user.getUserPwd().equals(password)) {
                // 用户登录成功之后,将用户信息放到session中
                request.getSession().setAttribute("user", user);
                request.getSession().setAttribute("url", "user/insert.do");
                jsonMap.put("success", true);
                jsonMap.put("message", userName+"登录成功");
            }else {
                jsonMap.put("success", false);
                jsonMap.put("message", "密码错误");
            }
        }else {
            jsonMap.put("success", false);
            jsonMap.put("success", userName+"不存在");
        }
        
        return jsonMap;

    }

    @ResponseBody
    @RequestMapping("/insert.do")
    public Object insert(User user) {
        logger.info("添加用户");
        return userService.insertUser(user);
    }
    @ResponseBody
    @RequestMapping("/userInfo.do")
    public Object userInfo(String userName) {
        logger.info("用户信息");
        return userService.findByName(userName);
    }
    @RequestMapping("/index")
    public String loginPage() {
        logger.info("首页");
        return "login";
    }
}

  AuthInterceptor.java

package powerx.io.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import powerx.io.model.User;

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        //从session中获取用户
        User user = (User)request.getSession().getAttribute("user");
        if(user==null){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return false;
        }
        //从session中获取当前用户能够操作的所有url
        String urls =  (String) request.getSession().getAttribute("url");
        String uri = request.getRequestURI();
        String contextPath =request.getContextPath();
        uri = uri.substring(contextPath.length()+1);
        if(!urls.equals(uri)){
            request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request, response);
            return false;
        }
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

}

  SystemInitListener.java,在容器启动后做一些初始化工作

package powerx.io.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class SystemInitListener implements ServletContextListener{

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("---系统初始化开始---");
        ServletContext application =  sce.getServletContext();
        application.setAttribute("root", "1234567");
        System.out.println("---系统初始化结束---");
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        
    }
    
}

  至此,基于xml的ssm框架整合完毕,项目结构图如下:

  源码地址:https://gitee.com/hehang_com/ssm-xml

posted on 2018-09-24 21:28  请叫我西毒  阅读(2919)  评论(0编辑  收藏  举报