Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)

项目结构:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)_第1张图片

 

 (代码里面都有注释)

一、在pom文件中依赖jar包

因为我这里分了模块,所以有父子级的共两个pom文件

父级:

xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>edu.nfgroupId>
    <artifactId>conformityartifactId>
    <version>1.0-SNAPSHOTversion>
    <modules>
        <module>ch01module>
        <module>ch02module>
        <module>ch03module>
        <module>ch04module>
        <module>ch05module>
    modules>
    <packaging>pompackaging>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <java.version>1.8java.version>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
        <maven.compiler.compilerVersion>1.8maven.compiler.compilerVersion>
        
        <spring.version>5.1.1.RELEASEspring.version>
        <junit.version>4.12junit.version>
        <druid.version>1.1.10druid.version>
        <mysql.version>5.1.47mysql.version>
        <mybatis.version>3.4.6mybatis.version>
        <mybatis.spring.version>1.3.2mybatis.spring.version>
        <pagehelper.version>5.1.2pagehelper.version>
        <aspect.version>1.9.1aspect.version>
        <servlet.version>4.0.1servlet.version>
        <jackson.version>2.9.6jackson.version>
        <slf4j.version>1.7.25slf4j.version>
    properties>

    
    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>javax.servlet-apiartifactId>
                <version>${servlet.version}version>
                <scope>providedscope>
            dependency>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webartifactId>
                <version>${spring.version}version>
            dependency>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webmvcartifactId>
                <version>${spring.version}version>
            dependency>
            
            <dependency>
                <groupId>com.fasterxml.jackson.coregroupId>
                <artifactId>jackson-databindartifactId>
                <version>${jackson.version}version>
            dependency>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-jdbcartifactId>
                <version>${spring.version}version>
            dependency>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-txartifactId>
                <version>${spring.version}version>
            dependency>
            
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatisartifactId>
                <version>${mybatis.version}version>
            dependency>
            
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatis-springartifactId>
                <version>${mybatis.spring.version}version>
            dependency>
            
            <dependency>
                <groupId>com.github.pagehelpergroupId>
                <artifactId>pagehelperartifactId>
                <version>${pagehelper.version}version>
            dependency>
            
            <dependency>
                <groupId>org.aspectjgroupId>
                <artifactId>aspectjweaverartifactId>
                <version>${aspect.version}version>
            dependency>
        dependencies>
    dependencyManagement>

    
    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>${slf4j.version}version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>${junit.version}version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>${druid.version}version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>${mysql.version}version>
        dependency>
    dependencies>
project>
View Code

子级:

xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>conformityartifactId>
        <groupId>edu.nfgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>
    <artifactId>ch04artifactId>
    <packaging>warpackaging>

    <dependencies>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
        dependency>
        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
        dependency>
        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelperartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
        dependency>
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
        dependency>
    dependencies>

    
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-war-pluginartifactId>
                <version>2.2version>
                <configuration>
                    <warSourceDirectory>webwarSourceDirectory>
                    
                    <webXml>web\WEB-INF\web.xmlwebXml>
                configuration>
            plugin>
        plugins>
    build>
project>
View Code

ssm所需jar包:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)_第2张图片

 

二、配置web.xml文件

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>
    
    
    <filter>
        <filter-name>EncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>EncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <filter>
        <filter-name>DruidWebStatFilterfilter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilterfilter-class>
        <init-param>
            <param-name>exclusionsparam-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>DruidWebStatFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <servlet>
        <servlet-name>DruidStatViewservlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServletservlet-class>
        <init-param>
            
            <param-name>loginUsernameparam-name>
            <param-value>rootparam-value>
        init-param>
        <init-param>
            
            <param-name>loginPasswordparam-name>
            <param-value>rootparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>DruidStatViewservlet-name>
        <url-pattern>/druid/*url-pattern>
    servlet-mapping>

    
    <servlet>
        <servlet-name>dispatcherservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:dispatcher-servlet.xmlparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>dispatcherservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>
View Code

 

三、配置dispatcher-servlet.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: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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <context:component-scan base-package="edu.nf.ch04.controller"/>

    
    <mvc:annotation-driven/>

    
    <mvc:default-servlet-handler/>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>

beans>
View Code

 

四、配置applicationContext.xml

创建Spring核心配置文件

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:mybatis="http://mybatis.org/schema/mybatis-spring"
       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://mybatis.org/schema/mybatis-spring
       http://mybatis.org/schema/mybatis-spring.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="edu.nf.ch04">
        
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        
        <property name="url" value="jdbc:mysql://localhost:3306/homework?useSSL=true&useUnicode=true&characterEncoding=utf-8"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        
        <property name="filters" value="stat"/>
        
        <property name="maxActive" value="200"/>
        
        <property name="initialSize" value="5"/>
        
        <property name="minIdle" value="5"/>
        
        <property name="maxWait" value="60000"/>
        
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        
        <property name="minEvictableIdleTimeMillis" value="300000"/>
        
        <property name="testWhileIdle" value="true"/>
        
        <property name="testOnBorrow" value="false"/>
        
        <property name="testOnReturn" value="false"/>
        
        <property name="poolPreparedStatements" value="false"/>
        
        <property name="validationQuery" value="select 1"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="typeAliasesPackage" value="edu.nf.ch04.entity"/>
        
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        
        <property name="plugins">
            
            <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                    
                    <props>
                        
                        <prop key="helperDialect">mysqlprop>
                        
                        <prop key="supportMethodsArguments">trueprop>
                    props>
                property>
            bean>
        property>
    bean>

    
    <mybatis:scan base-package="edu.nf.ch04.dao"/>

    
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <tx:annotation-driven transaction-manager="txManager"/>
beans>
View Code

mapper:ClassDao.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="edu.nf.ch04.dao.ClassDao">

    <resultMap id="classMap" type="classInfo">
        <id property="id" column="c_id"/>
        <result property="className" column="c_name"/>
    resultMap>

    <select id="listClassInfo" resultMap="classMap">
        select * from class_info
    select>

    <select id="getClassById" parameterType="integer" resultMap="classMap">
        select * from class_info where c_id = #{id}
    select>

    <insert id="saveClassInfo" parameterType="classInfo">
        insert into class_info(c_name) values(#{className});
    insert>

    <update id="updateClassInfo" parameterType="classInfo">
        update class_info set c_name = #{className}
    update>

mapper>
View Code

五、Log4j日志的配置:

xml version="1.0" encoding="UTF-8"?>
DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>

    
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        
        <layout class="org.apache.log4j.PatternLayout">
            
            <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss} %-5p] [%t] %l - %m%n" />
        layout>
        
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="levelMin" value="debug" />
            <param name="levelMax" value="error" />
            <param name="AcceptOnMatch" value="true" />
        filter>
    appender>

    
    <root>
        
        <priority value ="debug"/>
        
        <appender-ref ref="console"/>
    root>

log4j:configuration>
View Code

 

六、编写代码

Controller

BaseController:

package edu.nf.ch04.controller;

import edu.nf.ch04.controller.vo.ResponseVO;

/**
 * @author wangl
 * @date 2018/11/12
 * 父级控制器
 * 封装了给子类调用的成功响应视图的方法
 */
public class BaseController {

    protected ResponseVO success(){
        return new ResponseVO();
    }

    protected ResponseVO success(Object value){
        ResponseVO vo = new ResponseVO();
        vo.setValue(value);
        return vo;
    }

    protected ResponseVO success(Integer code, Object value){
        ResponseVO vo = new ResponseVO();
        vo.setCode(code);
        vo.setValue(value);
        return vo;
    }
}
View Code

ClassController:

package edu.nf.ch04.controller;

import edu.nf.ch04.controller.vo.ResponseVO;
import edu.nf.ch04.entity.ClassInfo;
import edu.nf.ch04.servie.ClassService;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author wangl
 * @date 2018/11/12
 */
@Controller
public class ClassController extends BaseController{

    /**
     * 日志对象
     */
    private static final Logger logger = LoggerFactory.getLogger(ClassController.class);

    /**
     * 注入对象
     */
    @Autowired
    private ClassService classService;

    @GetMapping("/listClassInfo")
    @ResponseBody
    public ResponseVO listClassInfo(Integer pageNum, Integer pageSize){
        List list = classService.listClassInfo(pageNum, pageSize);
        logger.info("查询用户列表: " + list.size());
        return success(list);
    }

    @PostMapping("/add")
    public ResponseVO addClass(ClassInfo classInfo){
        classService.saveClassInfo(classInfo);
        return success();
    }
}
View Code

advice(GlobalExceptionHandler):异常处理类

package edu.nf.ch04.controller.advice;


import edu.nf.ch04.controller.vo.ResponseVO;
import edu.nf.ch04.servie.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author wangl
 * @date 2018/11/12
 * 定义一个全局的异常处理类(类似一个切面)
 * 这个类中定义的所有方法都是异常处理方法,
 * 也可以理解为是全局的异常通知
 * value属性指定对哪些控制器进行切入拦截
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常处理方法
     * 用于处理参数异常
     * @param e
     * @return
     */
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public ResponseVO handleDataAccessException(DataAccessException e){
        ResponseVO vo = new ResponseVO();
        //设置相应状态码以及异常信息
        vo.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        vo.setMessage(e.getMessage());
        return vo;
    }
}
View Code

vo响应视图

package edu.nf.ch04.controller.vo;

import org.springframework.http.HttpStatus;

/**
 * @author wangl
 * @date 2018/11/12
 * 响应视图
 */
public class ResponseVO {

    private Integer code = HttpStatus.OK.value();

    private String message;

    private Object value;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "ResponseVO{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", value=" + value +
                '}';
    }
}
View Code

Service

自定义异常DataAccessException:

package edu.nf.ch04.servie;

/**
 * @author wangl
 * @date 2018/11/12
 */
public class DataAccessException extends RuntimeException{

    public DataAccessException(String message) {
        super(message);
    }

    public DataAccessException(String message, Throwable cause) {
        super(message, cause);
    }

    public DataAccessException(Throwable cause) {
        super(cause);
    }
}
View Code

业务层 接口ClassService

package edu.nf.ch04.servie;

import edu.nf.ch04.entity.ClassInfo;

import java.util.List;

/**
 * @author wangl
 * @date 2018/11/8
 */
public interface ClassService {

    /**
     * 查询班级信息
     * @param pageNum
     * @param pageSize
     * @return
     */
    List listClassInfo(Integer pageNum, Integer pageSize);

    /**
     * 根据id查询班级信息
     * @param id
     * @return
     */
    ClassInfo getClassById(Integer id);

    /**
     * 新建班级信息
     * @param classInfo
     */
    void saveClassInfo(ClassInfo classInfo);

    /**
     * 修改班级信息
     * @param classInfo
     */
    void updateClassInfo(ClassInfo classInfo);
}
View Code

业务层 实现类ClassServiceImpl

package edu.nf.ch04.servie.impl;

import edu.nf.ch04.dao.ClassDao;
import edu.nf.ch04.entity.ClassInfo;
import edu.nf.ch04.servie.ClassService;
import edu.nf.ch04.servie.DataAccessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wangl
 * @date 2018/11/8
 * @Transactional 事务注解
 */
@Service("classService")
@Transactional(rollbackFor = RuntimeException.class)
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassDao classDao;

    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List listClassInfo(Integer pageNum, Integer pageSize) {
        return classDao.listClassInfo(pageNum, pageSize);
    }

    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public ClassInfo getClassById(Integer id) {
        return classDao.getClassById(id);
    }

    @Override
    public void saveClassInfo(ClassInfo classInfo) {
        try {
            classDao.saveClassInfo(classInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new DataAccessException("添加失败");
        }
    }

    @Override
    public void updateClassInfo(ClassInfo classInfo) {
        try {
            classDao.updateClassInfo(classInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("修改失败");
        }
    }
}
View Code

Dao(ClassDao持久层 接口)

package edu.nf.ch04.dao;

import edu.nf.ch04.entity.ClassInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author wangl
 * @date 2018/11/8
 */
@Repository
public interface ClassDao {

    /**
     * 查询班级列表信息
     * @param pageNum
     * @param pageSize
     * @return
     */
    List listClassInfo(@Param("pageNum") Integer pageNum, @Param("pageSize") Integer pageSize);

    /**
     * 根据id查询班级信息
     * @param id
     * @return
     */
    ClassInfo getClassById(Integer id);

    /**
     * 新建班级信息
     * @param classInfo
     */
    void saveClassInfo(ClassInfo classInfo);

    /**
     * 修改班级信息
     * @param classInfo
     */
    void updateClassInfo(ClassInfo classInfo);
}
View Code

Entity(ClassInfo 实体类)

package edu.nf.ch04.entity;

/**
 * @author wangl
 * @date 2018/11/8
 */
public class ClassInfo {

    private Integer id;

    private String className;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "ClassInfo{" +
                "id=" + id +
                ", className='" + className + '\'' +
                '}';
    }
}
View Code

 

你可能感兴趣的:(Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件))