❤️最后的大爆发❤️五万字总结SpringMVC教程——三部曲封神之作(建议收藏)

2021-10-12 16:13:04 浏览数 (1)

上回分别为各位分享了《六万字最全总结Java数据库编程MyBatis》《爆肝万字!一文最全总结之Spring从入门到入土》。 没有学过的同学,建议先学MyBatis,后学Spring,这次在此基础上我们来学习SpringMVC,此篇学完再无后端!

❤️爆肝六万字最全总结Java数据库编程MyBatis(建议收藏)

❤️爆肝万字!一文最全总结之Spring从入门到入土❤️(建议收藏)

相关资料:

已上传到Gitee,欢迎start!!

1. Spring MVC 概述

2.1 Spring MVC是什么

​ Spring web mvc是表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出来:

1.0 Spring MVC处理流程

l 1)核心控制器:处理特定请求。(例如:以*.action为后缀)

名称:DispatcherServlet 配置:是一个servlet,需要在web.xml中配置。 XML:需要确定核心XML配置文件的位置

l 2)核心XML配置文件:确定Controller位置、确定JSP页面位置

名称:springmvc.xml

l 3)控制器:开发人员编写的主要内容

名称:*Controller

l 流程示意图

2. 入门案例:查询详情 ( xml)

3.1 需求说明

在index.html中点击 Hello SpringMVC 超链接,在 show01 .jsp 页面显示信息。

2.1 思路分析

整体思路:

跟HelloServlet入门案例几乎相同 .

服务器设置一个Controller,相当于之前的Servlet,可以接收请求,把请求在转发给jsp页面.

这里的区别就是需要设置web.xml和springmvc.xml两个配置文件,前者是用来配置核心控制器,后者是用来扫描我们自己书写的Controller的.

书写步骤:

1.拷贝pom文件,SpringMVC.xml文件和web.xml配置文件核心代码.

2.创建HelloController和show01.jsp

项目结构如下:

2.2 实现步骤

2.2.1 拷贝配置文件相关代码

获取pom文件:

参见当前文档末尾的附录 <SpringMVC01_pom>

获取springmvc.xml文件

代码如下直接拷贝

代码语言:javascript复制
<?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: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-4.2.xsd
                  http://www.springframework.org/schema/mvc
                  http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    <!-- 扫描注解包 -->
    <context:component-scan base-package="com.Maynor.controller" />  
</beans>

获取Web.xml代码配置如下:

代码语言:javascript复制
<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">

  <display-name>Archetype Created Web Application</display-name>


  <!-- 设置核心配置器 -->  
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>  
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.action</url-pattern>  
  </servlet-mapping>

</web-app>

2.2.2 创建java类和jsp文件

代码语言:javascript复制
创建HelloController.java 
package com.Maynor.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller  
public class HelloController {

   @RequestMapping("/hello.action")  
   public String show(Model model){

      model.addAttribute("data", "嘿嘿嘿"); 

      return "/WEB-INF/show01.jsp"; 
   }

}

Show01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

你好啊 老弟儿 ${data}

</body>
</html>

Index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>

<a href="${pageContext.request.contextPath}/hello.action">入门案例</a>
</body>
</html>

测试结果:

index.jsp页面

点击入门案例结果:

3. 入门查询:查询所有(无xml)

3.2 需求说明

该需求跟上一个入门案例需求完全相同.

在index.html中点击 Hello SpringMVC 超链接,在 show01 .jsp 页面显示信息。

区别在于实现的时候:

使用 WebInitializer类代替web.xml

使用MVCConfig代替springmvc.xml

3.1 思路分析

书写步骤:

1.拷贝pom文件,书写MVCConfig和WebInitializer类.

2.创建HelloController和show01.jsp

项目结构如下:

3.2 步骤实现

3.2.1 拷贝pom文件,创建MVCConfig和WebInitializer类

Pom文件,沿用上一个案例.即附录 <SpringMVC01_pom>

MVCConfig类代码如下:

代码语言:javascript复制
package com.Maynor.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.Maynor.controller")  
public class MVCConfig {
}

传统Web项目中,程序的入口是web.xml文件。

​ 在spring4中提供WebApplicationInitializer接口,表示服务器启动初始化。也就是说接口实现类中编写的内容,就是web.xml文件中配置的内容。

类或方法

描述

AnnotationConfigWebApplicationContext

WEB环境下spring工厂

servletContext.addFilter(name , Class)

添加过滤器,等效

servletContext.addServlet(name , Class)

添加servlet,等效

过滤器相关方法 ServletRegistration.Dynamic

描述

addMapping(urlPatterns)

追加过滤路径

setLoadOnStartup(int)

设置启动顺序

WebInitializer类代码如下:

代码语言:javascript复制
package com.Maynor.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebInitializer implements WebApplicationInitializer {
   @Override
   public void onStartup(ServletContext servletContext) throws ServletException {

      //1.初始化spring容器
      AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
      applicationContext.register(MVCConfig.class);  
      applicationContext.setServletContext(servletContext);
      //2.设置核心控制器
      ServletRegistration.Dynamic springMVCServlet = servletContext.addServlet("springmvc", new DispatcherServlet(applicationContext)); 
      springMVCServlet.addMapping("*.action"); 
      springMVCServlet.setLoadOnStartup(2);

   }
}

3.2.2 创建HelloController和show01.jsp

代码语言:javascript复制
HelloController代码:
package com.Maynor.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

   @RequestMapping(path = "/hello.action")
   public String show(Model model){

      model.addAttribute("data", "呵呵呵");
      
      return "/WEB-INF/show01.jsp";

   }


}
Show01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    来了 老弟儿 ${data}

</body>
</html>

测试结果:

练习:

查询所有. 希望得到如下结果:

参考代码:

l 编写JavaBean用于封装数据

代码语言:javascript复制
public class Item {
	private String name;	//名称
	private Float price;	//价格
	private String detail;	//详情

l 编写业务控制器Controller

代码语言:javascript复制
@Controller
@RequestMapping("/user")
public class HelloController {

    @RequestMapping("showInfo")
    public String showInfo(Model model){
        System.out.println("展示页面");
        //1 模拟数据
        List<Item> list = new ArrayList<Item>();
        list.add(new Item("联想笔记本", 6999f, "ThinkPad T430 联想笔记本电脑!"));
        list.add(new Item("苹果手机", 8800f, "iphone X 苹果手机!"));

        //设置数据
        model.addAttribute("list", list);
        return "/showInfo.jsp";
    }
}

l 展示数据

代码语言:javascript复制
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 86153
  Date: 2019/6/14
  Time: 0:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <td>名称</td>
        <td>价格</td>
        <td>描述</td>
    </tr>
    <c:forEach items="${list}" var="item">
        <tr>
            <td>${item.name }</td>
            <td>${item.price }</td>
            <td>${item.detail }</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

配置类

代码语言:javascript复制
*MVCConfig
@Configuration
@ComponentScan("com.Maynor.controller")
public class MVCConfiguration {

}


WebInitalizer
public class WebInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		//1 初始化spring容器
		AnnotationConfigWebApplicationContext appliation = new AnnotationConfigWebApplicationContext();
		appliation.register(MVCConfiguration.class);
		appliation.setServletContext(servletContext);
		
		//3 前端控制器
		ServletRegistration.Dynamic springMvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(appliation));  
		springMvcServlet.addMapping("*.action");
		springMvcServlet.setLoadOnStartup(2);

	}

}

测试:

l 步骤2:启动,并访问

http://localhost:8080/s02/user/showInfo.action

4. SSM整合:改造UMS

需求:

改造ums 实现 查询所有用户.

示意图如下:

思路:

  1. 环境搭建:拷贝pom,资源文件和配置文件,初始化数据库和表,创建javaBean
  2. 编写功能:dao,Service,Controller
  3. 编写配置类:SpringConfig,MyBatisConfig,SpringMvcConfig,Web启动类.
  4. 测试

项目最终结构如下:

4.1 搭建环境

4.0.1 创建项目、 拷贝pom文件

代码语言:javascript复制
<org.springframework.version>4.2.4.RELEASE</org.springframework.version>

<dependencies>
  <!-- spring start -->

  <!--spring core start-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <!--spring core end-->

  <!--spring aop start-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <!--spirng aop end-->

  <!--spring aspects start-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <!--spring aspects end-->

  <!--spring instrumentation start -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-instrument</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <!--spring instrumentation end-->

  <!--spring messaging start -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-messaging</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <!--spring messaging end-->

  <!--spring data access start -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jms</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <!--spring data access end-->

  <!--spring web start -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>


  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc-portlet</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <!--spring web end -->

  <!--spring test start -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>

  <!--spring test end -->
  <!-- spring end -->


  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper</artifactId>
    <version>3.5.2</version>
  </dependency>
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>3.7.5</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
  </dependency>

  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
  </dependency>
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
  </dependency>

  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
  </dependency>


  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>


  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.1</version>
    <scope>provided</scope>
  </dependency>
  
</dependencies>


<!-- jdk版本插件 -->
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.2</version>
  <configuration>
    <source>1.8</source>
    <target>1.8</target>
    <encoding>UTF-8</encoding>
    <showWarnings>true</showWarnings>
  </configuration>
</plugin>

<!-- tomcat7插件 -->
<plugin>
  <groupId>org.apache.tomcat.maven</groupId>
  <artifactId>tomcat7-maven-plugin</artifactId>
  <version>2.1</version>
  <configuration>
    <port>8081</port>
    <server>tomcat7</server>
  </configuration>
</plugin>

4.0.2 拷贝UMS页面

4.0.3 配置文件

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/ums_db jdbc.username=root jdbc.password=1234

4.0.4 初始化数据库和表

代码语言:javascript复制
CREATE TABLE t_user (

 uid INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,

 login_name VARCHAR(50) DEFAULT NULL,

 login_pwd VARCHAR(32) DEFAULT NULL,

 age INT(11) DEFAULT NULL,

 birthday DATE DEFAULT NULL,

 sex VARCHAR(1) DEFAULT NULL,

 education VARCHAR(50),

 telephone VARCHAR(11),

 interest VARCHAR(100),

 remark VARCHAR(200)

)
代码语言:javascript复制
insert  into `t_user`(`uid`,`login_name`,`login_pwd`,`age`,`birthday`,`sex`,`education`,`telephone`,`interest`,`remark`) values (1,'jack','1234',18,'1996-11-11','男',NULL,NULL,NULL,NULL),(2,'rose','1234',21,'1993-11-11','女',NULL,NULL,NULL,NULL),(3,'tom','1234',23,'1996-12-24','男',NULL,NULL,NULL,NULL);

4.0.5 创建JavaBean

代码语言:javascript复制
@Table(name="t_user")
public class User {
	@Id
	private Integer uid;
	private String loginName;
	private String loginPwd;
	private Integer age;
	private String sex;
	private String birthday;
	private String education;
	private String telephone;
	private String interest;		//爱好:对应数据库(内容:A,B,C)
	private String[] interestArr;	//爱好:对应页面表单
	private String remark;

l 爱好需要特殊处理

代码语言:javascript复制
	public String getInterest() {
		if(interestArr != null){
			interest = Arrays.toString(interestArr);  //[A,B,C]
			interest = interest.substring(1, interest.length() - 1);	//A,B,C
		}
		return interest;
	}
	public void setInterest(String interest) {
		this.interest = interest;
		if(interest != null){
			interestArr = interest.split(", ");
		}
	}

4.1 编写功能:dao、service、web、jsp页面

4.1.1 编写mapper接口(dao)

代码语言:javascript复制
package com.Maynor.dao;

import com.Maynor.domain.User;
import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<User> {
}

4.1.2 编写service接口

代码语言:javascript复制
package com.Maynor.service;

import com.Maynor.domain.User;

import java.util.List;

public interface UserService {

   public List<User> findAll();
   
}

4.1.3 编写service实现类

代码语言:javascript复制
package com.Maynor.service.impl;

import com.Maynor.dao.UserMapper;
import com.Maynor.domain.User;
import com.Maynor.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

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

@Service(value = "userServiceImpl")
@Transactional
public class UserServiceImpl implements UserService {


   @Resource
   private UserMapper userMapper;

   @Override
   public List<User> findAll() {

      List<User> users = userMapper.selectAll();

      return users;
   }
}

4.1.4 编写Controller

代码语言:javascript复制
package com.Maynor.controller;


import com.Maynor.domain.User;
import com.Maynor.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
public class UserController {

   @Autowired
   private UserService userService;

   @RequestMapping("/findAllUsers.action")
   public String findAll(Model model){

      List<User> userList = userService.findAll();

      model.addAttribute("userList", userList);

      return "/user/list.jsp";
   }


}

4.1.5 编写jsp

List.jsp

Left.jsp

代码语言:javascript复制
${pageContext.request.contextPath}/findAllUsers.action

4.2 编写配置类

4.2.1 spring配置类

代码语言:javascript复制
package com.Maynor.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.sql.DataSource;

//配置类
@Configuration
//要扫描的包
@ComponentScan(basePackages = {"com.Maynor"})
//开启事务支持
@EnableTransactionManagement
//读取properties配置文件
@PropertySource(value = "classpath:db.properties")
public class SpringConfig {

   //4.2.4 读取properties的固定代码
   @Bean
   public static PropertySourcesPlaceholderConfigurer create(){

      return new PropertySourcesPlaceholderConfigurer();
   }
   //读取数据库中的相关配置
   @Value("${jdbc.driver}")
   private String driverClass;
   @Value("${jdbc.url}")
   private String url;
   @Value("${jdbc.username}")
   private String username;
   @Value("${jdbc.password}")
   private String password;


   //设置德鲁伊连接池
   @Bean
   public DataSource dataSource(){
      DruidDataSource dataSource = new DruidDataSource();
      dataSource.setPassword(password);
      dataSource.setUsername(username);
      dataSource.setUrl(url);
      dataSource.setDriverClassName(driverClass);
      return dataSource;
   }
   //开启事务管理器
   @Bean
   @Resource
   public DataSourceTransactionManager txManager(DataSource dataSource){
      return  new DataSourceTransactionManager(dataSource);
   }
}

4.2.2 mybatis配置类

代码语言:javascript复制
package com.Maynor.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.sql.DataSource;

//配置类
@Configuration
//要扫描的包
@ComponentScan(basePackages = {"com.Maynor"})
//开启事务支持
@EnableTransactionManagement
//读取properties配置文件
@PropertySource(value = "classpath:db.properties")
public class SpringConfig {

   //4.2.4 读取properties的固定代码
   @Bean
   public static PropertySourcesPlaceholderConfigurer create(){

      return new PropertySourcesPlaceholderConfigurer();
   }
   //读取数据库中的相关配置
   @Value("${jdbc.driver}")
   private String driverClass;
   @Value("${jdbc.url}")
   private String url;
   @Value("${jdbc.username}")
   private String username;
   @Value("${jdbc.password}")
   private String password;


   //设置德鲁伊连接池
   @Bean
   public DataSource dataSource(){
      DruidDataSource dataSource = new DruidDataSource();
      dataSource.setPassword(password);
      dataSource.setUsername(username);
      dataSource.setUrl(url);
      dataSource.setDriverClassName(driverClass);
      return dataSource;
   }
   //开启事务管理器
   @Bean
   @Resource
   public DataSourceTransactionManager txManager(DataSource dataSource){
      return  new DataSourceTransactionManager(dataSource);
   }
}

4.2.3 spring mvc 配置类【无内容】

代码语言:javascript复制
package com.Maynor.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//声明为配置类
@Configuration
//设置扫描 controller
@ComponentScan("com.Maynor.controller")
public class SpringMvcConfig {
}

4.2.4 web启动配置类【新内容】

​ 传统Web项目中,程序的入口是web.xml文件。

​ 在spring4中提供WebApplicationInitializer接口,表示服务器启动初始化。也就是说接口实现类中编写的内容,就是web.xml文件中配置的内容。

类或方法

描述

AnnotationConfigWebApplicationContext

WEB环境下spring工厂

servletContext.addFilter(name , Class)

添加过滤器,等效

servletContext.addServlet(name , Class)

添加servlet,等效

过滤器相关方法 ServletRegistration.Dynamic

描述

addMapping(urlPatterns)

追加过滤路径

setLoadOnStartup(int)

设置启动顺序

过滤器相关方法 FilterRegistration.Dynamic

描述

addMappingForUrlPatterns(null, isMatchAfter, urlPatterns)

追加过滤路径参数2:参数3:路径

代码语言:javascript复制
package com.Maynor.config;


import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebInitializer implements WebApplicationInitializer {
   @Override
   public void onStartup(ServletContext servletContext) throws ServletException {
      //1.初始化 Spring 容器
      AnnotationConfigWebApplicationContext applicationContext  = new AnnotationConfigWebApplicationContext();
      applicationContext.register(SpringMvcConfig.class);
      applicationContext.register(SpringConfig.class);
      applicationContext.register(MybatisConfig.class);
      applicationContext.setServletContext(servletContext);

      //2.设置核心控制器
      ServletRegistration.Dynamic ds = servletContext.addServlet("springmvc", new DispatcherServlet(applicationContext));
      ds.addMapping("*.action");
      ds.setLoadOnStartup(2);


      //3 post乱码配置    
      FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("CharacterEncodingFilter", new CharacterEncodingFilter("UTF-8"));
      encodingFilter.addMappingForUrlPatterns(null, true, "/*");

   }
}

4.3 测试

启动项目,点击用户管理 可以看到如下效果即可.

5. 视图 解析器

5.1 分析

5.2 修改代码

l 其他代码与“查询所有”案例相同,不同内容如下:

5.2.1 编写控制器

l 业务控制器返回“视图”名称

代码语言:javascript复制
@Controller
@RequestMapping("/user")
public class ItemsController {
	
	@RequestMapping("/itemsList")
	public String itemsList(Model model) throws Exception {
		
		//1 模拟数据
		List<Items> list = new ArrayList<Items>();
		list.add(new Items("联想笔记本", 6999f, "ThinkPad T430 联想笔记本电脑!"));
		list.add(new Items("苹果手机", 8800f, "iphone X 苹果手机!"));
		
		//设置数据
		model.addAttribute("list", list);
		
		return "itemslist"; //"/WEB-INF/jsp/itemslist.jsp";
	}

}

5.2.2 配置视图解析器

代码语言:javascript复制
@Configuration
@ComponentScan("com.Maynor.controller")
public class MVCConfiguration {
	@Bean
	public InternalResourceViewResolver viewResolver(){
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/jsp/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
}

6. SSM整合:改造UMS(添加视图解析器)

7. 参数 绑定

7.1 简单数据类型

l 在控制器的方法中,只要有对应的参数名,spring mvc就可以自动完成参数封装。

7.1.1 支持的数据类型

l 参数类型推荐使用包装数据类型,因为基础数据类型不可以为null,此时进行访问没有设置参数,程序抛异常。

| 数据类型 |

|:----|

| 整型:Integer、int |

| 字符串:String |

| 单精度:Float、float |

| 双精度:Double、double |

| 布尔型:Boolean、boolean |

7.1.2 @RequestParam

l 如果请求参数名和方法参数名不一致时,需要使用@RequestParam标记对应关系。

l 如果类型是基本类型,此时没有参数,默认抛异常。

解决方案1:可以设置默认值。

解决方案2:可以设置成 包装类型

7.2 绑定POJO类型

代码语言:javascript复制
JSP页面
<form action="${pageContext.request.contextPath}/user/additems.action" method="post">
		姓名:<input type="text" name="name"/> <br/>
		价格:<input type="text" name="price"/> <br/>
		<input type="submit" value="提交" />
	</form>
控制器:
@Controller
@RequestMapping("/user")
public class ItemsController {

	@RequestMapping("additems")
	public String addItems(Items items){
		System.out.println(items);
		return "itemslist";
	}
}

l 分析

l 注意:数据不能是日期,日期必须采用自定义参数绑定。

7.3 POST中文乱码

代码语言:javascript复制
在web.xml文件中
<filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
我们采用web启动配置类的方式
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		//1 初始化spring容器
		AnnotationConfigWebApplicationContext appliation = new AnnotationConfigWebApplicationContext();
		appliation.register(MVCConfiguration.class);
		appliation.setServletContext(servletContext);
		
		//2 post乱码配置 
		FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("CharacterEncodingFilter", new CharacterEncodingFilter("UTF-8"));
		encodingFilter.addMappingForUrlPatterns(null, true, "/*");
		
		//3 前端控制器
		ServletRegistration.Dynamic springMvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(appliation));  
		springMvcServlet.addMapping("*.action");
		springMvcServlet.setLoadOnStartup(2);

	}

7.4 绑定包装POJO

代码语言:javascript复制
提供JavaBean:QueryVo
public class QueryVo {
	private Items items;

	public Items getItems() {
		return items;
	}

	public void setItems(Items items) {
		this.items = items;
	}
}
修改控制器
	@RequestMapping("findall")
	public String findAll(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		return "itemslist";
	}
JSP页面
<form action="${pageContext.request.contextPath}/user/findall.action" method="post">
		姓名:<input type="text" name="items.name"/> <br/>
		价格:<input type="text" name="items.price"/> <br/>
		<input type="submit" value="提交findall" />
	</form>

7.5 自定义参数绑定

​ 由于日期数据有很多种格式,所以springmvc没办法把字符串转换成日期类型(不够智能,2019/01/01这种格式可以自动转,2019-01-01这种格式就不能了)。所以需要自定义参数绑定。

代码语言:javascript复制
JavaBean
public class QueryVo {
	private Items items;
	private Date createDate;
JSP页面
<form action="${pageContext.request.contextPath}/user/findall2.action" method="post">
		姓名:<input type="text" name="items.name"/> <br/>
		价格:<input type="text" name="items.price"/> <br/>
		日期:<input type="text" name="createDate"/> <br/>
		<input type="submit" value="提交findall2" />
	</form>
控制器
	@RequestMapping("findall2")
	public String findAll2(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		System.out.println(queryVo.getCreateDate());
		return "itemslist";
	}

方式一:

1. 在MVCConfig类上添加@EnableWebMvc 注解

2. 在实体类上添加注解@DateTimeFormat

代码语言:javascript复制
JavaBean
public class QueryVo {
	private Items items;
	private Date createDate;
JSP页面
<form action="${pageContext.request.contextPath}/user/findall2.action" method="post">
		姓名:<input type="text" name="items.name"/> <br/>
		价格:<input type="text" name="items.price"/> <br/>
		日期:<input type="text" name="createDate"/> <br/>
		<input type="submit" value="提交findall2" />
	</form>
控制器
	@RequestMapping("findall2")
	public String findAll2(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		System.out.println(queryVo.getCreateDate());
		return "itemslist";
	}

7.6 绑定数组

代码语言:javascript复制
JavaBean
public class QueryVo {
	private Items items;
	private Date createDate;
JSP页面
<form action="${pageContext.request.contextPath}/user/findall2.action" method="post">
		姓名:<input type="text" name="items.name"/> <br/>
		价格:<input type="text" name="items.price"/> <br/>
		日期:<input type="text" name="createDate"/> <br/>
		<input type="submit" value="提交findall2" />
	</form>
控制器
	@RequestMapping("findall2")
	public String findAll2(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		System.out.println(queryVo.getCreateDate());
		return "itemslist";
	}

7.7 表单数据绑定到List

代码语言:javascript复制
JavaBean
public class QueryVo {
	private Items items;
	private Date createDate;
JSP页面
<form action="${pageContext.request.contextPath}/user/findall2.action" method="post">
		姓名:<input type="text" name="items.name"/> <br/>
		价格:<input type="text" name="items.price"/> <br/>
		日期:<input type="text" name="createDate"/> <br/>
		<input type="submit" value="提交findall2" />
	</form>
控制器
	@RequestMapping("findall2")
	public String findAll2(QueryVo queryVo){
		System.out.println(queryVo.getItems());
		System.out.println(queryVo.getCreateDate());
		return "itemslist";
	}

8. @RequestMapping

8.1 多路径映射

l 同时设置多个路径

代码语言:javascript复制
@RequestMapping(value={"/index","/index2"})
	public String index(){
		return "itemslist";
	}

http://localhost:8080/spring_mvc_day01_05/user/index.action
http://localhost:8080/spring_mvc_day01_05/user/index2.action
//都可以访问 

8.2 窄化请求路径

@RequestMapping放在类名上边,设置请求前缀

@RequestMapping放在方法名上边,设置方法对应请求路径。

完整请求:前缀 请求路径

8.3 请求方法限定

l 限定GET方法 @RequestMapping(method = RequestMethod.GET) l 限定POST方法 @RequestMapping(method = RequestMethod.POST) l GET和POST都可以 @RequestMapping(method={RequestMethod.GET,RequestMethod.POST})

9. Controller方法返回值

9.1 返回ModelAndView

controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。

代码语言:javascript复制
@RequestMapping("/findById")
	public ModelAndView findById(){
		ModelAndView modelAndview = new ModelAndView();
		//设置数据
		modelAndview.addObject("id", "猜猜看");
		//设置视图
		modelAndview.setViewName("itemslist");
		return modelAndview;
	}

9.2 返回void

如果方法返回void,有3种情况:request请求转发、response重定向、给前端响应Json

代码语言:javascript复制
请求转发
@RequestMapping("/findById2")
public void findById2(HttpServletRequest request , HttpServletResponse response) 
								throws ServletException, IOException{
	request.getRequestDispatcher("/index.jsp").forward(request, response);
}
重定向
@RequestMapping("/findById3")
public void findById3(HttpServletRequest request , HttpServletResponse response) 
								throws ServletException, IOException{
	response.sendRedirect(request.getContextPath()   "/index.jsp");
}
Json 处理
@RequestMapping("/findById4")
public void findById4(HttpServletRequest request , HttpServletResponse response)
								 throws ServletException, IOException{
	response.setCharacterEncoding("UTF-8");
	response.setContentType("application/json;charset=UTF-8");
	String jsonStr = "{"username":"jack"}";
	response.getWriter().write(jsonStr);
}

9.3 返回字符串

9.3.1 逻辑视图名

controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。

代码语言:javascript复制
@RequestMapping(value={"/index","/index2"})
public String index(){
	return "itemslist";
}

9.3.2 Redirect重定向

​ Contrller方法返回结果重定向到一个url地址,如下商品修改提交后重定向到商品查询方法,参数无法带到商品查询方法中。

代码语言:javascript复制
return "redirect:其他路径";

@RequestMapping("/update")
public String update() throws ServletException, IOException{
	return "redirect:queryItem.action";
}

9.3.3 forward转发

​ controller方法执行后继续执行另一个controller方法,如下商品修改提交后转向到商品修改页面,修改商品的id参数可以带到商品修改方法中。

代码语言:javascript复制
return "forward:其他路径";
@RequestMapping("/updateSubmit")
public String updateSubmit() throws ServletException, IOException{
	return "forward:editItem.action";
}

10. 异常处理器

10.1 异常处理器分析

10.2 自定义异常

代码语言:javascript复制
public class CustomException extends Exception {

	private static final long serialVersionUID = 8222256702797084775L;

	public CustomException() {
		super();
	}

	public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

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

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

	public CustomException(Throwable cause) {
		super(cause);
	}
	
}

10.3 异常处理器编写

代码语言:javascript复制
public class CustomException extends Exception {

	private static final long serialVersionUID = 8222256702797084775L;

	public CustomException() {
		super();
	}

	public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

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

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

	public CustomException(Throwable cause) {
		super(cause);
	}
	
}

10.4 异常页面

代码语言:javascript复制
<body>
	您的操作出现错误如下:<br/>
	${message }
</body>

10.5 测试程序

代码语言:javascript复制
@Controller
@RequestMapping("/user")
public class ItemsController {
	
	@RequestMapping("index")
	public String index(String id) throws CustomException{
		if(id == null){
			throw new CustomException("没有id参数");
		}
		return "itemslist";
	}
}

<a href="${pageContext.request.contextPath}/user/index.action">异常演示</a><br/>

异常演示

11. 上传图片

11.1 单图片上传

11.1.1 JSP页面

代码语言:javascript复制
<form id="itemForm" action="${pageContext.request.contextPath }/user/upload.action" method="post" enctype="multipart/form-data">
		姓名:<input type="text" name="name"/> <br/>
		价格:<input type="text" name="price"/> <br/>
		图片:<input type="file" name="picFile"/> <br/>
		<input type="submit" value="提交" />
	</form>

11.1.2 文件上传解析器

代码语言:javascript复制
<form id="itemForm" action="${pageContext.request.contextPath }/user/upload.action" method="post" enctype="multipart/form-data">
		姓名:<input type="text" name="name"/> <br/>
		价格:<input type="text" name="price"/> <br/>
		图片:<input type="file" name="picFile"/> <br/>
		<input type="submit" value="提交" />
	</form>

l 使用的commons-fileupload完成上传,确定导入fileupload jar包

代码语言:javascript复制
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.2.2</version>
</dependency>

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.3</version>
</dependency>

11.1.3 Controller实现

需要使用MultipartFile类型表示一个文件上传对象。

方法名

描述

String getOriginalFilename()

获得原始上传文件名

transferTo(File file)

将上传文件转换到一个指定的文件中

String getContentType()

获取文件MIME类型,如image/pjpeg、text/plain等

String getName()

获取表单中文件组件的名字

代码语言:javascript复制
	@RequestMapping("upload")
	public String upload(String name,Double price,
@RequestParam(required=false,value="picFile") MultipartFile picFile) throws Exception{
		System.out.println("姓名:"   name);
		System.out.println("价格:"   price);
		
		String originalFileName = picFile.getOriginalFilename();
		System.out.println("上传文件名:"   originalFileName);
		//保存文件到指定的位置
		File file = new File("D:\temp", originalFileName);
		picFile.transferTo(file);
		return "itemslist";
	}

11.2 多图片上传

11.2.1 JSP页面

代码语言:javascript复制
<form id="itemForm" action="${pageContext.request.contextPath }/user/upload2.action"
 								method="post" enctype="multipart/form-data">
		姓名:<input type="text" name="name"/> <br/>
		价格:<input type="text" name="price"/> <br/>
		图片:<input type="file" name="picFile"/> <br/>
		图片:<input type="file" name="picFile"/> <br/>
		<input type="submit" value="提交" />
	</form>

11.2.2 JavaBean

代码语言:javascript复制
public class QueryVo {
	private String name;
	private Double price;
	public List<MultipartFile> picFile;

	//getter and setter

11.2.3 Controller实现

代码语言:javascript复制
@RequestMapping("upload2")
	public String upload2(QueryVo queryVo) throws Exception{
		System.out.println("姓名:"   queryVo.getName());
		System.out.println("价格:"   queryVo.getPrice());
		
		System.out.println("上传文件个数:"   queryVo.getPicFile().size());
		for(MultipartFile picFile : queryVo.getPicFile()){
			String originalFileName = picFile.getOriginalFilename();
			System.out.println("上传文件名:"   originalFileName);
			//保存文件到指定的位置
			File file = new File("D:\temp", originalFileName);
			picFile.transferTo(file);
		}
		return "itemslist";
	}

12. JSON数据交互

12.1 概述

@RequestBody:将json、xml 等内容 转换 成Java对象。

@ResponseBody:将Java对象 转换 成 json、xml等内容。

12.2 前端发送ajax请求,后端获取json数据

需求:

前端发送ajax请求,后端通过VO自动获取数据打印

代码语言:javascript复制
  前端代码:
   <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
    <script>
        $(function () {

            var url = "${pageContext.request.contextPath}/tJson.action";
            var params={
                "name":"zhangsan",
                "price":"123"
            }
            var callBack=function (rel) {
                //后端有返回结果 就会弹窗显示, 没有就不会弹窗
                alert(rel.name " " rel.price)
            }
            //发射
            $.post(url,params,callBack,"json")

        })
    </script>
</head>
<body>
  页面加载完毕就发射ajax 
</body>
</html>
后端代码: 
 Qvo 
  public class QVo {

    private String name;
    private Double price;
....
}

Controller
@RequestMapping("/tJson.action")
public String testJson(QVo qvo){
    //查看前端传递的json 自动转化的VO结果
    System.out.println(qvo);

    return "/show04.jsp";//随便转发到一个页面,不影响测试结果.
}

测试结果:

12.3 后端给前端响应Json数据.

需求:

跟上一个例子类似, 前端发送请求给后端, 后端接收数据后给前端再相应回一个json数据.

该例子中,需要直接把java对象通过SpringMvc自动转化成json数据. 需要使用两个东西完成.

1. 导入Jackson-databind坐标

2. 在方法的返回值上使用@ResponseBody注解.

具体代码如下:

代码语言:javascript复制
Pom文件坐标
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.7</version>
</dependency>

Controller代码:
@RequestMapping("tj.action")
public @ResponseBody QVo getInfo(String name,Double price){

    System.out.println("接收到前端数据:" name " " price);

    //创建一个对象, 通过SpringMvc自动把这个对象转化成Json响应给前端
    QVo qVo = new QVo("lisiguang", 220.4);
    return qVo;
}

前端:
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>
    $(function () {

        var url = "${pageContext.request.contextPath}/tj.action";
        var params={
            "name":"zhangsan",
            "price":"123"
        }
        var callBack=function (rel) {
            //后端有返回结果 就会弹窗显示, 没有就不会弹窗
            alert(rel.name " " rel.price)
        }
        //发射
        $.post(url,params,callBack,"json")

    })
</script>

测试结果:

后端:

前端:

13. RESTful支持

13.1 什么是RESTful

​ Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。 l 资源定位:每一个URL都是一个资源。要求url中没有动词,只有名词。没有参数 Url格式:http://blog.csdn.net/beat_the_world/article/details/45621673 l 资源操作:通过HTTP请求方式确定不同的操作。 get查询资源、post新建资源(也可以修改资源)、put更新资源、delete删除资源。 一般使用时还是post和get。 @RequestMapping(value="/viewItems/{id}" , method= RequestMethod.GET ) l RESTful初体验 在URL中包含操作的数据,而不是通过参数进行传递。

13.2 添加jar包

13.3 修改web.xml,支持RESTful

代码语言:javascript复制
	<!-- 前端控制器 -->
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>

13.4 JSP页面

代码语言:javascript复制
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
	<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.12.4.js"></script>
	<script type="text/javascript">
		$(function(){
			alert("静态资源(js)可以使用");
		});
	</script>
</head>
<body>
	<a href="${pageContext.request.contextPath}/user/viewItems/1">查询id=1</a><br/>
	<a href="${pageContext.request.contextPath}/user/viewItems/999.action">查询id=999</a><br/>
	
</body>

13.5 Controller实现

通过@RequestMapping可以设置URL模板模式映射。 @RequestMapping(value="/ viewItems/{xxx}") ,{xxx}相当于占位符,可以匹配到/viewItems/1、/viewItems/2 等路径 xxx就是占位符的名称,用于方法参数获得匹配到的数据 通过@PathVariable(“xxx”) 获得从路径匹配到的对应数据

代码语言:javascript复制
	@RequestMapping("/viewItems/{id}")
	public String viewItems(@PathVariable("id") String id , Model model) {
		model.addAttribute("id", id);
		return "itemslist";
	}

13.6 静态资源问题及解决

l 当程序运行时,首页的js代码将不能执行。

原因:DispatcherServlet中设置url-pattern为 /,静态资源不能成功访问。 解决:配置 mvc:resources

代码语言:javascript复制
<!-- 确保所有注解正常使用 -->
<mvc:annotation-driven></mvc:annotation-driven>
	
<!-- 静态资源访问 -->
<mvc:resources location="/js/" mapping="/js/*"></mvc:resources>

14. 拦截器

14.1 概述

​ Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器执行前后进行处理。

​ 自定义连接性需要实现接口:HandlerInterceptor

14.2 分析

方法名

描述

boolean preHandle()

在处理器(控制器)前执行。返回一个boolean值。true:继续执行处理器。false:程序直接结束。

void postHandle()

在处理器方法执行后,视图显示前执行。

void afterCompletion()

在视图解析成功后执行。

14.3 自定义 拦截器

14.3.1 JSP页面,测试入口

代码语言:javascript复制
<a href="${pageContext.request.contextPath}/user/index.action">拦截器演示</a><br/>

14.3.2 控制器,测试程序

代码语言:javascript复制
@Controller
@RequestMapping("/user")
public class ItemsController {
	
	@RequestMapping("index")
	public String index(String id) {
		System.out.println("2.controller");
		return "itemslist";
	}
}

14.3.3 拦截器实现类

代码语言:javascript复制
package com.Maynor.interceptor;

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

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

@Component
public class MyInterceptor1 implements HandlerInterceptor {
    /*
     * 在方法执行之前执行
     * 如果返回true 继续执行下一个拦截器
     * 如果返回false,请求被终止
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor1拦截器的preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor1拦截器的postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor1拦截器的afterCompletion");
    }
}

14.3.4 注册拦截器

拦截器编写完成之后,需要在SpringMVCConfiguration配置文件中注册

注册步骤:

1 SpringMVCConfiguration实现WebMvcConfigurerAdapter

2 重写AddInterceptors方法

代码语言:javascript复制
public class SpringMvcConfig  extends WebMvcConfigurerAdapter {
    @Autowired
    private MyInterceptor1 myInterceptor1;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration1 = registry.addInterceptor(myInterceptor1);
        interceptorRegistration1.addPathPatterns("/*");
    }
     //.....
}

14.3.5 执行结果

14.4 多拦截器配置

14.4.1 分析

14.4.2 拦截器实现类

代码语言:javascript复制
package com.Maynor.interceptor;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyInterceptor2 implements HandlerInterceptor {
    /*
     * 在方法执行之前执行
     * 如果返回true 继续执行下一个拦截器
     * 如果返回false,则程序终止
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor2拦截器的preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor2拦截器的postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor2拦截器的afterCompletion");
    }
}

14.4.3 注册 拦截器

代码语言:javascript复制
@Resource
private MyInterceptor1 myInterceptor1;

@Resource
private MyInterceptor2 myInterceptor2;

@Override
public void addInterceptors(InterceptorRegistry registry) {

    //拦截全部
    InterceptorRegistration interceptorRegistration2 = registry.addInterceptor(myInterceptor2);
    interceptorRegistration2.addPathPatterns("/*");
    //拦截全部
    InterceptorRegistration interceptorRegistration = registry.addInterceptor(myInterceptor1);
    interceptorRegistration.addPathPatterns("/*");

}

14.4.4 执行结果

15. 附录

用到的相关配置文件

15.1 SpringMVC01_pom

SpringMVC入门案例1的pom文件核心代码

Pom.xml文件

代码语言:javascript复制
<properties>
  <org.springframework.version>4.2.4.RELEASE</org.springframework.version>
</properties>


<dependencies>
    <!-- spring start -->

    <!--spring core start-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <!--spring core end-->

    <!--spring aop start-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <!--spirng aop end-->

    <!--spring aspects start-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <!--spring aspects end-->

    <!--spring instrumentation start -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <!--spring instrumentation end-->

    <!--spring messaging start -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-messaging</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <!--spring messaging end-->

    <!--spring data access start -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-oxm</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <!--spring data access end-->

    <!--spring web start -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-websocket</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>


    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc-portlet</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <!--spring web end -->

    <!--spring test start -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!--spring test end -->
    <!-- spring end -->


    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>3.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.10</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

</dependencies>

<!-- jdk版本插件 -->
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.2</version>
  <configuration>
    <source>1.8</source>
    <target>1.8</target>
    <encoding>UTF-8</encoding>
    <showWarnings>true</showWarnings>
  </configuration>
</plugin>

<!-- tomcat7插件 -->
<plugin>
  <groupId>org.apache.tomcat.maven</groupId>
  <artifactId>tomcat7-maven-plugin</artifactId>
  <version>2.1</version>
  <configuration>
    <port>8080</port>
    <server>tomcat7</server>
  </configuration>
</plugin>

后记

0 人点赞