【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例

SSM的整合思想

将MyBatis整合入Spring中,由Spring管理MyBatis的数据源注入和事务。
第一个S表示SpringMVC,是Spring框架的一个拓展,无需整合,只需要处理好Service的注入即可,不用Struts2是因为,拦截器太多,性能不好

Spring和MyBatis整合原则

将MyBatis的数据源配置交给Spring来注入,将事务交给Spring进行管理

准备条件

Spring框架:
https://projects.spring.io/spring-framework/
spring-framework-5.0.3.RELEASE-dist.zip【JDK8】
jar文件在压缩包的libs目录中,除了javadoc(文档注释)、sources(源码),剩下的就是需要导入的jar文件
其中,核心jar文件有4个:spring-beans、spring-context、spring-core、spring-expression

拓展的jar文件:spring-jdbc、spring-tx、spring-aop
commons-logging-1.2.jar(spring日志必备)

如果引入spring-aop,还需要再拓展AspectJ-plugin-3.0.0.zip
https://plugins.jetbrains.com/plugin/1127-aspectj-weaver

SpringMVC框架:
在Spring框架的基础上引入2个核心jar文件:spring-web、spring-webmvc

MyBatis框架:
https://github.com/mybatis
mybatis-3.4.5.zip(包括自带的Log4j)
mybatis-spring-1.3.1.zip(与Spring整合时,需要引入)
https://github.com/mybatis/spring/releases

创建SSM项目(无Maven的IDEA环境搭建,注解和配置混搭)

Mybatis不建议使用注解,官方在说明文档中指出会影响性能,SpringMVC推荐使用注解,方便Spring自动注入
1、创建JavaEE网页项目
注意:Spring框架的最低要求为JDK8+
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第1张图片

2、导入Jar文件
数据库使用MySQL
除了基础的jar文件以外,拓展的jar文件也需要导入
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第2张图片
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第3张图片

3、创建项目包结构
resources:配置文件(右键,Make Directory as,Resource root)
controller:SpringMVC
entity:pojo类
mapper:MyBatis
service:业务功能

4、连接数据库,创建pojo到entity包中
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第4张图片
数据表创建脚本
Target Server Type : MySQL
Target Server Version : 50721
File Encoding : 65001

-- ----------------------------
-- Table structure for grade
-- ----------------------------
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade`  (
  `GradeID` int(11) NOT NULL AUTO_INCREMENT COMMENT '年级编号',
  `GradeName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '年级名称',
  PRIMARY KEY (`GradeID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for result
-- ----------------------------
DROP TABLE IF EXISTS `result`;
CREATE TABLE `result`  (
  `StudentNo` int(4) NOT NULL COMMENT '学号',
  `SubjectNo` int(4) NOT NULL COMMENT '课程编号',
  `ExamDate` datetime(0) NOT NULL COMMENT '考试日期',
  `StudentResult` int(4) NOT NULL COMMENT '考试成绩',
  INDEX `SubjectNo`(`SubjectNo`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `StudentNo` int(4) NOT NULL COMMENT '学号',
  `LoginPwd` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `StudentName` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '学生姓名',
  `Sex` tinyint(1) NULL DEFAULT NULL COMMENT '性别,取值0或1',
  `GradeId` int(11) NULL DEFAULT NULL COMMENT '年级编号',
  `Phone` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '联系电话,允许为空,即可选输入',
  `Address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地址,允许为空,即可选输入',
  `BornDate` datetime(0) NULL DEFAULT NULL COMMENT '出生时间',
  `Email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱账号,允许为空,即可选输入',
  `IdentityCard` varchar(18) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '身份证号',
  PRIMARY KEY (`StudentNo`) USING BTREE,
  UNIQUE INDEX `IdentityCard`(`IdentityCard`) USING BTREE,
  INDEX `Email`(`Email`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for subject
-- ----------------------------
DROP TABLE IF EXISTS `subject`;
CREATE TABLE `subject`  (
  `SubjectNo` int(11) NOT NULL AUTO_INCREMENT COMMENT '课程编号',
  `SubjectName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '课程名称',
  `ClassHour` int(4) NULL DEFAULT NULL COMMENT '学时',
  `GradeID` int(4) NULL DEFAULT NULL COMMENT '年级编号',
  PRIMARY KEY (`SubjectNo`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 18 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

配置IDEA的数据库映射,创建pojo类
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第5张图片
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第6张图片
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第7张图片

注意修正每个pojo的包名;日期类型可以使用java.util.Date
配置成功后,稍后在Mapper中写SQL语句时也会智能提示,快速排版

5、将三个框架所需的空配置文件放入resource中
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第8张图片
创建连接数据库的配置文件,日志配置文件

6、创建web.xml配置文件
可以从Tomcat的\webapps\ROOT\WEB-INF获取


<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" metadata-complete="true">

    
    <listener>
        
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    <context-param>
        
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring/*.xmlparam-value>
    context-param>

    
    <servlet>
        
        <servlet-name>SpringMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springMVC/*.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        
        <servlet-name>SpringMVCservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <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>forceRequestEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
        <init-param>
            <param-name>forceResponseEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>EncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
web-app>

7、日志和数据库配置文件

log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.jbit.dao=debug
log4j.logger.com.ibatis=debug 
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
log4j.logger.java.sql.Connection=debug 
log4j.logger.java.sql.Statement=debug 
log4j.logger.java.sql.PreparedStatement=debug 
log4j.logger.java.sql.ResultSet=debug 
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
######################################################################################
# Console Appender  日志在控制输出配置
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %d %c - %m%n
######################################################################################
# DailyRolling File  每天产生一个日志文件
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
log4j.logger.com.opensymphony.xwork2=error  
# 数据库驱动
db_driver=com.mysql.jdbc.Driver
# 数据库连接地址
db_url=jdbc:mysql://localhost:3306/test
# 数据库登录
db_username=root
db_password=root

8、配置Spring的核心配置文件
applicationContext.xml


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

    
    <context:property-placeholder location="classpath:database.properties"/>

    
    <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
        
        <property name="driverClassName" value="${db_driver}"/>
        <property name="url" value="${db_url}"/>
        <property name="username" value="${db_username}"/>
        <property name="password" value="${db_password}"/>
    bean>

    
    <tx:annotation-driven/>

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

    
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            
            
            <tx:method name="add*" isolation="SERIALIZABLE" propagation="REQUIRED"/>
            <tx:method name="delete*"/>
            <tx:method name="update*"/>
            
            <tx:method name="find*" read-only="true"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*" read-only="true"/>
        tx:attributes>
    tx:advice>

    
    <aop:config>
        
        <aop:pointcut id="studentPointcut" expression="execution(* cn.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="studentPointcut"/>
    aop:config>

    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="configLocation" value="classpath:myBatis/mybatis-config.xml"/>
        
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="basePackage" value="cn.mapper"/>
    bean>

    
    <context:component-scan base-package="cn.service"/>
beans>

9、配置SpringMVC和MyBatis的核心配置文件
springmvc-servlet.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    

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

    
    <mvc:resources mapping="/js/**" location="/pageSource/js/"/>
    <mvc:resources mapping="/img/**" location="/pageSource/img/"/>
    <mvc:resources mapping="/css/**" location="/pageSource/css/"/>

    
    <mvc:annotation-driven/>

    
    <context:component-scan base-package="cn.controller"/>
beans>

mybatis-config.xml



<configuration>
    
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    settings>

    
    <typeAliases>
        <package name="cn.entity"/>
    typeAliases>

    
    <mappers>
        <package name="cn.mapper"/>
    mappers>
configuration>

到此,以上就是SSM的空项目整合基础架构(除了数据库,这里预先配置了)

实现基本的CRUD操作

1、创建Student的Mapper类(dao接口)

package cn.mapper;

import cn.entity.Student;

import java.util.List;

public interface StudentMapper {
    //增加学生信息
    public int addStu(Student student);
    //通过id查找学生信息
    public Student findStuById(int studentNo);
    //修改学生信息
    public int updateStu(Student student);
    //通过id删除学生
    public int deleteStu(int studentNo);
    //查询所有学生所属年级(学生,多对一,年级)
    public List getStudentsGrade();
    //查询学生的所有课程的成绩(学生,一对多,成绩,一对一,课程)
    public Student getStudentResults(int studentNo);
}

2、Mapper.xml,实现接口的方法、SQL语句的配置




<mapper namespace="cn.mapper.StudentMapper">
    
    
    <insert id="addStu" parameterType="Student">
        INSERT INTO student (
            StudentNo,
            LoginPwd,
            StudentName,
            Sex,
            GradeId,
            Phone,
            Address,
            BornDate,
            Email,
            IdentityCard)
        VALUES (
            #{studentNo},
            #{loginPwd},
            #{studentName},
            #{sex},
            #{gradeId},
            #{phone},
            #{address},
            #{bornDate},
            #{email},
            #{identityCard}
        )
    insert>
    
    <select id="findStuById" parameterType="int" resultType="Student">
        SELECT
            StudentNo,
            LoginPwd,
            StudentName,
            Sex,
            GradeId,
            Phone,
            Address,
            BornDate,
            Email,
            IdentityCard
        FROM student
        WHERE StudentNo = #{studentNo}
    select>
    
    <update id="updateStu" parameterType="Student">
        UPDATE student
        SET
            LoginPwd     = #{loginPwd},
            StudentName  = #{studentName},
            Sex          = #{sex},
            GradeId      = #{gradeId},
            Phone        = #{phone},
            Address      = #{address},
            BornDate     = #{bornDate},
            Email        = #{email},
            IdentityCard = #{identityCard}
        WHERE StudentNo = #{studentNo}
    update>
    
    <delete id="deleteStu" parameterType="int">
        DELETE FROM student
        WHERE StudentNo = #{studentNo}
    delete>

    
    
    <resultMap id="stuGrade" type="Student">
        <id property="studentNo" column="StudentNo"/>
        <result property="studentName" column="StudentName"/>
        
        <association property="grade" javaType="Grade">
            <id property="gradeId" column="GradeID"/>
            <result property="gradeName" column="GradeName"/>
        association>
    resultMap>
    
    <select id="getStudentsGrade" parameterType="int" resultMap="stuGrade">
        SELECT
            s.StudentNo,
            s.StudentName,
            g.GradeID,
            g.GradeName
        FROM
            grade AS g
            INNER JOIN student AS s ON s.GradeId = g.GradeID
    select>

    
    <resultMap id="stuResults" type="Student">
        <id property="studentNo" column="StudentNo"/>
        <result property="studentName" column="StudentName"/>
        
        <collection property="resultList" ofType="Result">
            <result property="studentResult" column="StudentResult"/>
            
            <association property="subject" javaType="Subject">
                <id property="subjectNo" column="SubjectNo"/>
                <result property="subjectName" column="SubjectName"/>
            association>
        collection>
    resultMap>
    <select id="getStudentResults" parameterType="int" resultMap="stuResults">
        SELECT
            st.StudentNo,
            st.StudentName,
            re.StudentResult,
            su.SubjectNo,
            su.SubjectName
        FROM
            student AS st
            INNER JOIN result AS re ON st.StudentNo = re.StudentNo
            INNER JOIN `subject` AS su ON re.SubjectNo = su.SubjectNo
        WHERE
            st.StudentNo = #{studentNo}
    select>
mapper>

3、创建Student的Service类

package cn.service;

import cn.entity.Student;
import cn.mapper.StudentMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/*
指定为Service类,影响到Controller的注入,可以自定义名称
 */
@Service(value = "StuService")
public class StudentService {

    /*
    spring会根据类型自动装配
     */
    @Resource
    private StudentMapper studentMapper;

    /*
    以下方法都被增强,具有事务,进入方法前开启事务,方法执行完成后递交事务
     */
    public int addStu(Student student) {
        return studentMapper.addStu(student);
    }

    public Student findStuById(int studentNo) {
        return studentMapper.findStuById(studentNo);
    }

    public int updateStu(Student student) {
        return studentMapper.updateStu(student);
    }

    public int deleteStu(int studentNo) {
        //手动制造异常,如果非正常退出方法,事务回滚至进入方法前
        int n = 1 / 0;
        return studentMapper.deleteStu(studentNo);
    }

    public List getStudentsGrade() {
        return studentMapper.getStudentsGrade();
    }

    public Student getStudentResults(int studentNo) {
        return studentMapper.getStudentResults(studentNo);
    }
}

4、创建Student的Controller类
add方法中详细列出了注解配置的说明,排版有些凌乱请在IDE中重新对齐

package cn.controller;

import cn.entity.Student;
import cn.service.StudentService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/*
默认为singleton单例模式,对应配置中的
 */
@Scope(value = "prototype")
/*
请求映射,链接地址第一层满足指定的value则进入这个控制类中的方法
 */
@RequestMapping(value = "/test")
/*
指定当前类为控制类,value可以重命名(无法自动装配)
不使用注解时,需实现org.springframework.web.servlet.mvc.Controller接口
 */
@Controller
public class StudentController {
    /*
    指定Service,需要在Spring中配置相关注解扫描(自动装配)
    可以使用
    @Autowired@Qualifier(value = "StuService")
    进行配置,也可以使用
    @Resource
     */
    @Resource(name = "StuService")
    private StudentService studentService;

    /*
    value为数组,可以设置多个链接,method为请求方式
     */
    @RequestMapping(
            value = "/add.html",
            method = RequestMethod.GET
    )
    public String addStu(
            //如果链接中有数据的获取方法,value为链接中的名称,required = false为可缺省
            @RequestParam(
                    value = "info",
                    required = false
            ) String msg,

            //以下写出后会自动装配,可省略不写
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response,
            Model model//可以用Map代替
    ) throws RuntimeException {
        //模拟页面传入了注册的信息
        Student student = new Student();
        student.setStudentNo(9999);
        student.setLoginPwd("123123");
        student.setStudentName("张三");
        student.setSex(2);
        student.setGradeId(2);
        student.setPhone("13512312312");
        student.setAddress("测试地址");
        student.setBornDate(new Date());
        student.setEmail("[email protected]");
        student.setIdentityCard("123123123123123123");

        //执行增加
        int n = studentService.addStu(student);
        if (n == 0) {
            //jsp页面中,使用${msg}即可获取
            model.addAttribute("msg", "增加" + student.getStudentName() + "成功");
            //手动抛出异常
            throw new RuntimeException("添加失败");
        } else {
            //jsp页面中,使用${msg}即可获取
            model.addAttribute("msg", "增加" + student.getStudentName() + "成功");
        }
        //使用index的视图呈现,前后缀见视图解析器配置
        return "index";
    }

    @RequestMapping(value = "/find.html", method = RequestMethod.GET)
    public String findStuById(@RequestParam(value = "id") String stuId, Model model) {
        Student student = studentService.findStuById(Integer.parseInt(stuId));
        model.addAttribute("msg", student.getStudentName());
        return "index";
    }

    @RequestMapping(value = "/update.html", method = RequestMethod.GET)
    public String updateStu(Model model) {
        Student student = new Student();
        student.setStudentNo(9999);
        student.setLoginPwd("asdasdasdsad");
        student.setStudentName("李四");
        student.setSex(1);
        student.setGradeId(1);
        student.setPhone("13500000000");
        student.setAddress("测试地址12313215");
        student.setBornDate(new Date());
        student.setEmail("[email protected]");
        student.setIdentityCard("12345123412121234");
        int n = studentService.updateStu(student);
        model.addAttribute("msg", "更新" + n + "条记录");
        return "index";
    }

    @RequestMapping(value = "/delete.html", method = RequestMethod.GET)
    public String deleteStu(Model model) {
        int n = studentService.deleteStu(9999);
        model.addAttribute("msg", "删除" + n + "条记录");
        return "index";
    }

    @RequestMapping(value = "/getGrade.html", method = RequestMethod.GET)
    public String getStudentsGrade(HttpServletRequest request, Model model) {
        List studentList = studentService.getStudentsGrade();
        model.addAttribute("msg", "获取到" + studentList.size() + "条记录");
        request.setAttribute("stuList", studentList);//前台页面用小脚本即可获取遍历
        return "index";
    }

    @RequestMapping(value = "/getResult.html", method = RequestMethod.GET)
    public String getStudentResults(@RequestParam("stuNo") String stuNO,
                                    HttpServletRequest request, Model model) {
        Student student = studentService.getStudentResults(Integer.parseInt(stuNO));
        model.addAttribute("msg", "获取到" + student.getStudentName() + "的记录");
        request.setAttribute("stu", student);//前台页面用小脚本即可获取遍历
        return "index";
    }

    /*
    全局异常处理配置
     
        
            
                error
            
        
    
    以下为局部异常处理方式
     */
    @ExceptionHandler(value = {RuntimeException.class})
    public String error(RuntimeException e, HttpServletRequest request) {
        request.setAttribute("e", e);//jsp页面显示 ${e.getMessage()}
        return "error";//跳转到异常页面
    }
}

特殊的返回情况

重定向:return "redirect:/jsp/page.jsp";
转发:return "forward:/jsp/page.jsp";

5、创建index.jsp页面进行输出测试
由于我的前端水平不是很好,就不考虑什么样式了,放在/WEB-INF/pages里面(和SpringMVC的核心配置有关)
在Controller类中,存入Request对象数据,在jsp页面中使用小脚本即可遍历显示出来

<%@ page import="java.util.List" %>
<%@ page import="cn.entity.Student" %>
<%@ page import="cn.entity.Result" %><%--
  Created by IntelliJ IDEA.
  User: kinlo
  Date: 2018/3/10
  Time: 15:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
${msg}<br/><br/>
<%
    StringBuffer sb1 = new StringBuffer();
    List studentList = (List) request.getAttribute("stuList");
    if (studentList != null) {
        sb1.append("getStudentsGrade方法:
"
); for (Student student : studentList) { sb1 .append(student.getStudentName()) .append("  ") .append(student.getGrade().getGradeName()) .append("
"
); } } %>
<%=sb1.toString()%><br/><br/> <% StringBuffer sb2 = new StringBuffer(); Student stu = (Student) request.getAttribute("stu"); if (stu != null) { sb2.append("getStudentResults方法:
"
); List resultList = stu.getResultList(); for (Result result : resultList) { sb2 .append(stu.getStudentName()) .append("  ") .append(result.getSubject().getSubjectName()) .append("  ") .append(result.getStudentResult()) .append("
"
); } } %>
<%=sb2.toString()%><br/> body> html>

6、部署项目
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第9张图片
7、依次执行访问链接进行测试
test/add.html?info=
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第10张图片

test/update.html
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第11张图片

test/find.html?id=9999
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第12张图片

test/delete.html
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第13张图片

test/getResult.html?stuNo=1004
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第14张图片

test/getGrade.html
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第15张图片

8、静态网页资源测试
在SpringMVC中配置mvc:resources标签,是为了解决web.xml中servlet-mapping的url-pattern配置,由于该配置为“/”,连资源文件也一起被捕获了,无法直接访问到真实路径,因此需要使用这个配置重新映射到真实路径中

<mvc:resources mapping="/js/**" location="/pageSource/js/"/>
<mvc:resources mapping="/img/**" location="/pageSource/img/"/>
<mvc:resources mapping="/css/**" location="/pageSource/css/"/>

mapping为链接的路径,location为本地的真实路径
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第16张图片
【SSM】SpringMVC、Spring(5.0.3)、MyBatis(3.4.5)三大框架的整合项目入门示例_第17张图片

你可能感兴趣的:(SSM项目)