Spring MVC最佳教學(xué)教程入門筆記

一、Spring MVC入門

Spring MVC是Spring 提供的一個(gè)子模塊,是一個(gè)實(shí)現(xiàn)了 Web MVC設(shè)計(jì)模式的輕量級(jí)Web框架。其提供了一個(gè)前端控制器 DispatcherServlet ,使開發(fā)人員無(wú)須額外開發(fā)控制器對(duì)象,可自動(dòng)綁定用戶輸入,并能正確的轉(zhuǎn)換數(shù)據(jù)類型,并內(nèi)置了常見的校驗(yàn)器,可以校驗(yàn)用戶輸入 如果校驗(yàn)不能通過(guò),那么就會(huì)重定向到輸入表單。

MVC:Model+View+Controller(數(shù)據(jù)模型+視圖+控制器)

三層架構(gòu):Presentation tier+Application tier + Data tier(展現(xiàn)層(mvc)+應(yīng)用層(service)+數(shù)據(jù)訪問(wèn)層(dao))
MVC是三層架構(gòu)的展現(xiàn)層,M是數(shù)據(jù)模型,是包含數(shù)據(jù)的對(duì)象,也就是Model類。V是指視圖頁(yè)面,包含JSP、FreeMarker、Themeleaf等。C是指控制器,也就是使用@Controller注解的類。

1、Maven依賴

                <!--spring+springmvc依賴,引入此包會(huì)自動(dòng)引入Spring的四個(gè)核心包+spring-aop、spring-web、spring-webmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.14</version>
        </dependency>

                <!--servlet-api依賴-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

2、web.xml

此配置文件放在WEB-INF下。
web.xml中配置的DispatcherServlet, 該servelt會(huì)在服務(wù)啟動(dòng)的時(shí)候立即加載,并且在加載時(shí)需要一個(gè)springMVC配置文件,并根據(jù)該文件信息創(chuàng)建一個(gè)WebApplicationContext容器對(duì)象,也成為上下文環(huán)境。這個(gè)對(duì)象繼承與ApplicationContext容器,他的初始化與BeanFactory、ApplicationContext有所區(qū)別,因?yàn)閃ebApplicationcontext需要ServletContext實(shí)例,也就是說(shuō)他必須在擁有Web容器的前提下才能完成啟動(dòng)SpringWeb應(yīng)用上下文的工作。有了WebApplicationcontext,就可以使用spring的IOC和AOP等其他功能了。

<?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">

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

    <servlet>
        <!--配置前端過(guò)濾器-->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <!--初始化時(shí)加載配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/springmvc-config.xml</param-value>
        </init-param>
        <!--表示容器在啟動(dòng)時(shí)立即加載Servlet-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3、springmvc-config.xml

此配置文件放在WEB-INF下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

      <!--對(duì)url請(qǐng)求進(jìn)行處理的bean-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

    <!--對(duì)返回的數(shù)據(jù)進(jìn)行處理的bean:分為json和頁(yè)面兩種返回類型,對(duì)應(yīng)下面兩個(gè)配置-->
    <!--返回json時(shí)用到這個(gè)類-->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
    <bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
  
    <!--定義視圖解析器,返回jsp頁(yè)面時(shí)用到這個(gè)類-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--配置攔截器-->
    <mvc:interceptors>
        <!--全局?jǐn)r截器-->
        <bean class="com.example.ssm.interceptor.CustomInterceptor"/>
        <!--攔截全部url-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.example.ssm.interceptor.CustomInterceptor"/>
        </mvc:interceptor>
        <!--攔截以/hello結(jié)尾的url-->
        <mvc:interceptor>
            <mvc:mapping path="/hello"/>
            <bean class="com.example.ssm.interceptor.CustomInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

4、測(cè)試FirstController

package com.example.ssm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstController implements org.springframework.web.servlet.mvc.Controller {

    @RequestMapping("/hello")
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.addObject("msg", "這是我的第一個(gè)S平日那個(gè)MVC程序");
        mav.setViewName("first");
        return mav;
    }
}

// 或者

@Controller
public class FirstController {
    @RequestMapping("/hello")
    public String handleRequest(HttpServletRequest request, HttpServletResponse responsel, Model model) {
        System.out.println("進(jìn)來(lái)了。。。。。。");

        model.addAttribute("msg", "這是我的第一個(gè)Spring MVC程序!");
        return "first";

    }
}

handleRequest是Controller接口的實(shí)現(xiàn)方法, FirstController 類會(huì)調(diào)用該方法來(lái)處理請(qǐng)求,并返回一個(gè)包含視圖名或包含視圖名和模型的 ModelAndView 對(duì)象。

5、驗(yàn)證

image.png

二、核心類和注解

1、DispatcherServlet

DispatcherServlet 的全名是 org. springframework. web.servlet.DispatcherServlet ,它在程序中充當(dāng)著前端控制器的角色在使用時(shí),只需將其配置在項(xiàng)目的 web.xml 文件中。

<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WeApp_ID" version="3.0">

    <servlet>
        <!--配置前端過(guò)濾器-->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <!--初始化時(shí)加載SpringMVC的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
        <!--表示容器在啟動(dòng)時(shí)立即加載Servlet-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

<Ioad-on-startup> 元素和<init-param>元素都是可選的,如果<Ioad-ons-tartup>元素的值為1,則在應(yīng)用程序啟動(dòng)時(shí)會(huì)立即加載該 Servlet;如果<Ioad-on-startup>素不存在,則應(yīng)用程序會(huì)在第一個(gè)Servlet請(qǐng)求時(shí)加載該Servlet。如果<init-param>元素存在并且通過(guò)其子元素配置了 Sprihg MVC 配置文件的路徑,則應(yīng)用程序在啟動(dòng)時(shí)會(huì)加載配置路徑下的配置文件;如果沒(méi)有通過(guò)<init-param>元素配置,則應(yīng)用程序會(huì)默認(rèn)到 WEB-INF 目錄下尋找如下方式命名的配置文件。**servletName**-servlet.xml其中,servletName 指的是部署在 web.xml中的DispatcherServlet 的名稱,在上面 web.xml中的配置代碼中即為 springmvc ,而-servlet. xml是配置文件名的固定寫法,所以應(yīng)用程序會(huì)在WEB-INF 下尋找 springmvc-servlet. xml 。

2、SpringMVC注解

(1)@RequestMapping

RequestMapping 注解類型用于映射一個(gè)請(qǐng)求或一個(gè)方法,@RequestMapping("/firstController")

注意,路徑區(qū)分大小寫

(2)合注解

  • @GetMapping:匹配 GET 方式的請(qǐng)求
  • @PostMapping:匹配 POST 方式的請(qǐng)求
  • @PutMapping:匹配 PUT 方式的請(qǐng)求
  • @DeleteMapping:匹配 DELETE 方式的請(qǐng)求
  • @PatchMapping:匹配 PATCH 方式的請(qǐng)求

三、請(qǐng)求處理方法的參數(shù)類型和返回類型

1、參數(shù)類型

HttpServletRequest
HttpServletResponse
HttpSession
@PathVariable
@RequestParam
@RequestHeader
@RequestBody
@Model/ModelMap
......等等
String 類型的返回值不能攜帶數(shù)據(jù),需要Model 參數(shù)類型,通過(guò)該參數(shù)類型的addAttribute()方法,添加所需數(shù)據(jù)即可添加需要在視圖中顯示的屬性。需要注意的是,org.springframework.ui.Model 類型不是一個(gè) Servlet API 型,而是一個(gè)包含了 Map 對(duì)象的 Spring MVC 類型,如果方法中添加了 Model參數(shù),則每次調(diào)用請(qǐng)求處理方法時(shí),Spring MVC 都會(huì)創(chuàng)建 Model 對(duì)象,并將其作為參數(shù)傳遞給方法。

2、返回類型

(1)ModevlAndView

@Controller
public class FirstController {
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView mav = new ModelAndView();
        mav.addObject("這是我的第一個(gè)Spring MVC程序!");
        mav.setViewName("/WEB-INF/first.jsp");
        return mav;
    }
}

(2)String

由于 ModelAndView 類型未能實(shí)現(xiàn)數(shù)據(jù)與視圖之間的解耦,所以在企業(yè)開發(fā)時(shí),方法的返回類型通常都會(huì)使用 String,配合Model攜帶參數(shù),返回到頁(yè)面。

@Controller
public class FirstController {
    public String handleRequest(HttpServletRequest request, Model model) {

        model.addAttribute("msg", "這是我的第一個(gè)Spring MVC程序!");
        return "first";
    }
}

String處理返回視圖頁(yè)面外,還可以進(jìn)行重定向與請(qǐng)求轉(zhuǎn)發(fā)

public String handleRequest(HttpServletRequest request, Model model) {

        // 重定向請(qǐng)求路徑
    return "redirect:index";
}

public String handleRequest(HttpServletRequest request, Model model) {

        // 請(qǐng)求轉(zhuǎn)發(fā)
    return "forward:index";
}

(3)其它

void
Model/ModelMap
View
Map
......等等

四、數(shù)據(jù)綁定

在執(zhí)行程序時(shí),Spring MVC會(huì)根據(jù)客戶端請(qǐng)求參數(shù)的不同,將請(qǐng)求消息中的信息以一定的方式轉(zhuǎn)換并綁定到控制器類的方法參數(shù)中,這種將請(qǐng)求消息數(shù)據(jù)與后臺(tái)方法參數(shù)建立連接的過(guò)程,就是 Spring MVC 中的數(shù)據(jù)綁定。

1、綁定SpringMVC默認(rèn)數(shù)據(jù)類型

當(dāng)前端請(qǐng)求的參數(shù)比較簡(jiǎn)單是,可以在后臺(tái)的Controller形參中直接使用Spring MVC 提供的默認(rèn)參數(shù)類型。

  • HttpServletRequest:處理請(qǐng)求信息
  • HttpServletResponse:處理響應(yīng)信息
  • HttpSession:獲得session中存儲(chǔ)的對(duì)象
  • Mode/ModeMap:Model是一個(gè)接口,ModelMap是一個(gè)接口實(shí)現(xiàn),作用是將model數(shù)據(jù)填充到request域。

2、綁定Java基本數(shù)據(jù)類型

簡(jiǎn)單數(shù)據(jù)類型的綁定,就算指Java中幾種基本數(shù)據(jù)類型的綁定。如,int、String、Double等。
當(dāng)前端請(qǐng)求中的參數(shù)名和后臺(tái)控制器類中的形參名不一致,則后臺(tái)無(wú)法接收到前臺(tái)傳來(lái)的參數(shù),這時(shí)需要使用Spring MVC提供的@RequestParam注解進(jìn)行數(shù)據(jù)綁定。

3、綁定POJO類型

POJO類型的數(shù)據(jù)綁定就是將所有關(guān)聯(lián)的請(qǐng)求參數(shù)封裝在一個(gè)POJO中,然后在方法中直接使用POJO作為形參來(lái)完成數(shù)據(jù)綁定。前端參數(shù)名必須要和POJO屬性名一樣,否則后臺(tái)接收的參數(shù)值為null。POJO類型里面的屬性值,可以為其它相關(guān)POJO類。

4、自定義數(shù)據(jù)綁定

有些特殊類型的參數(shù)無(wú)法在后臺(tái)進(jìn)行直接轉(zhuǎn)換,如日期數(shù)據(jù)需要自定義轉(zhuǎn)換器(Converter)活格式化(Formatter)來(lái)進(jìn)行數(shù)據(jù)綁定。
Spring提供了一個(gè)Converter用于將一種類型的對(duì)象轉(zhuǎn)換為另一種類型的對(duì)象,如將前臺(tái)輸入的日期2021/04/08字符串與后臺(tái)的Date綁定,此時(shí)就可以自定義一個(gè)Converter。

  1. Converter
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConvert implements Converter<String, Date> {
    /*定義時(shí)間格式*/
    private String datePattern = "yyyy-MM-dd HH:mm:ss";

    @Override
    public Date convert(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            throw new IllegalArgumentException(
                    "無(wú)效的數(shù)據(jù)格式,請(qǐng)使用這種數(shù)據(jù)格式:" + datePattern);
        }
    }
}

springmvc-config.xml

    <mvc:annotation-driven conversion-service="conversionService"/>

    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.example.ssm.convert.DateConvert"/>
            </set>
        </property>
    </bean>
  1. Formatter
package com.example.ssm.convert;

import org.springframework.format.Formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class DateFormatter implements Formatter<Date> {
    //定義時(shí)間格式
    private String datePattern = "yyyy-MM-dd HH:mm:ss";
    // 生命SimpleDateFormat對(duì)象
    private SimpleDateFormat simpleDateFormat;


    @Override
    public Date parse(String source, Locale locale) throws ParseException {
        simpleDateFormat = new SimpleDateFormat(datePattern);
        return simpleDateFormat.parse(source);
    }

    @Override
    public String print(Date date, Locale locale) {
        return new SimpleDateFormat().format(date);
    }
}

springmvc-config.xml

    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="formatters">
            <set>
                <bean class="com.example.ssm.convert.DateFormatter"/>
            </set>
        </property>
    </bean>

5、綁定數(shù)組

例如前臺(tái)傳來(lái)多個(gè)類型相同的參數(shù),如用戶id,用來(lái)批量刪除用戶,就可以用綁定數(shù)組的方式。

    public String deleteUsers(Integer[] ids) {
        if (ids != null) {
            for (Integer id : ids) {
                System.out.println("已刪除id為" + id + "的用戶!");
            }
        } else {
            System.out.println("ids=null");
        }
        return "success";
    }

6、綁定集合

如果前臺(tái)批量傳來(lái)的數(shù)據(jù),包含不同類型例如用戶信息,需要用綁定集合。定義一個(gè)包含用戶信息類的集合,然后在接受方法中將參數(shù)類型定義為該包裝類的集合。后臺(tái)方法中不支持直接使用集合形參進(jìn)行數(shù)據(jù)綁定,所以需要使用包裝POJO作為形參,然后在包裝POJO中包裝一個(gè)集合屬性。

public class UserVO {
    private List<User> users;

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }
}
    public String editUsers(UserVO userList) {
        /*將所有用戶數(shù)據(jù)封裝到集合中*/
        List<User> users = userList.getUsers();
        /*循環(huán)輸出所有用戶信息*/
        for (User user : users) {
            if (user.getId() != null) {
                System.out.println("修改成功");
            }
        }

        return "success";
    }

五、JSON數(shù)據(jù)交互和RESTful支持

1、JSON數(shù)據(jù)交互

JSON ( JavaScript Object Notation , JS 對(duì)象標(biāo)記)是一種輕量級(jí)的數(shù)據(jù)交換格式 它是基于JavaScript 的一個(gè)子集,采用完全獨(dú)立于編程語(yǔ)言的文本格式來(lái)存儲(chǔ)和表示數(shù)據(jù)。

  1. Spring MVC中JSON 數(shù)據(jù)交互需默認(rèn)要使用Jackson讀取JSON數(shù)據(jù),或?qū)ava對(duì)象轉(zhuǎn)為json。引入以下maven依賴會(huì)自動(dòng)導(dǎo)入以下3個(gè)必須的Jackson包。
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>
  • jackson-annoations:JSON 轉(zhuǎn)換注解包
  • jackson-core:JSON 轉(zhuǎn)換核心包
  • jackson-databind:JSON 轉(zhuǎn)換的數(shù)據(jù)綁定包
  1. JSON格式轉(zhuǎn)換注解

@RequestBody用于將請(qǐng)求體中的數(shù)據(jù)綁定到萬(wàn)法的形參中 該注解用在方法的形參上
@ResponseBody用于直接返回陀turn 對(duì)象 該注解用在方法上

  1. Spring MVC配置
<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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!--定義組件掃描器,指定需要掃描的包-->
    <context:component-scan base-package="com.example.ssm.controller"/>
    <!--配置注解驅(qū)動(dòng)-->
    <mvc:annotation-driven/>
    <!--配置靜態(tài)資掘的訪問(wèn)映射,此配置中的文件,將不被前端控制器攔截-->
    <mvc:resources location="classpath:/js" mapping="/js/**"/>
    <!--配置視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  1. 測(cè)試代碼
    @RequestMapping("/testJson")
    @ResponseBody
    public User testJson(@RequestBody User user) {
        System.out.println(user);
        return user;
    }

2、RESTFul支持

RESTful 也稱之為 REST ( Representational State Transfer ),可以將它理解為一種軟件架構(gòu)風(fēng)格或設(shè)計(jì)風(fēng)格,而不是一個(gè)標(biāo)準(zhǔn)簡(jiǎn)單來(lái)說(shuō),RESTful 風(fēng)格就是把請(qǐng)求參數(shù)變成請(qǐng)求路徑的一種風(fēng)格。RESTful 風(fēng)格在 HTIP 請(qǐng)求中,使用 put delete post get 方式分別對(duì)應(yīng)添加、刪除、修改和查詢的操作。

  • 查詢案例
    @RequestMapping("/user/{id}")
    @ResponseBody
    public User selectUser(@PathVariable("id") String id){
        User user = new User();
        user.setUsername("king");
        return user;
    }

@PathVariable("id")注解則用于接收并綁定請(qǐng)求參數(shù),它可以將請(qǐng)求 URL 中的變量映射到方法的形參上,如果請(qǐng)求路徑為 "/user/{id}" ,即請(qǐng)求參數(shù)中的 id 和方法形參名稱 id 一樣,則@PathVariable 后面的("id") 可以省略。

六、攔截器

Spring MVC 中的攔截器( Interceptor )類似于 Servlet 中的過(guò)濾器( Filter) ,它主要用于攔截用戶請(qǐng)求并做相應(yīng)的處理 例如通過(guò)攔截器可以進(jìn)行權(quán)限驗(yàn)證、記錄請(qǐng)求信息的日志、判斷用戶是否登錄等,是AOP思想的具體應(yīng)用。

1、定義攔截器類

通常攔截器類可以通過(guò)兩種方式來(lái)定義:一種是通過(guò)實(shí)現(xiàn) Handlerlnterceptor接口,或繼承 Handlerlnterceptor 接口的實(shí)現(xiàn)類(如 HandlerlnterceptorAdapter )來(lái)定義;另一種是通過(guò)實(shí)現(xiàn) WebRequestlnterceptor接口,或繼承 WebRequestlnterceptor 接口的實(shí)現(xiàn)類來(lái)定義。

public class CustomInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle....");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle....");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion....");
    }
}

2、配置攔截器

<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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!--配置組件掃描器,指定需要掃描的包-->
    <context:component-scan base-package="com.example.ssm.controller"/>
    <mvc:resources location="classpath:/js" mapping="/js/**"/>
    <!--配置視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
  
    <!--配置攔截器-->
    <mvc:interceptors>
        <!--<mvc:interceptors>直接配置bean將攔截所有請(qǐng)求-->
        <bean class="com.example.interceptor.CustomInterceptor"/>
        <!--攔截全部url-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.example.interceptor.CustomInterceptor1"/>
        </mvc:interceptor>
        <!--攔截以/hello結(jié)尾的url-->
        <mvc:interceptor>
            <mvc:mapping path="/hello"/>
            <bean class="com.example.interceptor.CustomInterceptor2"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

當(dāng)有多個(gè)攔截器同時(shí)工作時(shí),它們的 preHandle()方法會(huì)按照配置文件中攔截器的配置順序執(zhí)行,而它們的 postHandle()方法和 afterCompletion()方法則會(huì)按照配置順序的反序執(zhí)行

3、案例:攔截器實(shí)現(xiàn)用戶登錄

。。。。待補(bǔ)充

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容