主頁 > 軟體設計 > SSM整合以及相關補充

SSM整合以及相關補充

2022-10-09 08:09:11 軟體設計

SSM整合以及相關補充

我們在前面已經學習了Maven基本入門,Spring,SpringMVC,MyBatis三件套

現在我們來通過一些簡單的案例,將我們最常用的開發三件套整合起來,進行一次完整的專案展示

溫馨提示:在閱讀本篇文章前,請學習Maven,Spring,SpringMVC,MyBatis等內容

SSM整合案例

接下來我們通過各個部分的準備與介紹進行一次SSM專案的內容整合

案例介紹階段

案例介紹:

  • 我們希望通過網頁進行操作資料庫內容

資料庫目前資料:

案例準備階段

  1. 創建工程

我們采用Maven專案的maven-webapp創建專案

  1. 補充相關檔案以及設定檔案構造名稱

案例書寫階段

  1. 資料庫準備階段
CREATE DATABASE SMM;

USE SMM;

-- ----------------------------
-- Table structure for tbl_book
-- ----------------------------
DROP TABLE IF EXISTS `tbl_book`;
CREATE TABLE `tbl_book`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of tbl_book
-- ----------------------------
INSERT INTO `tbl_book` VALUES (1, '計算機理論', 'Spring實戰 第5版', 'Spring入門經典教程,深入理解Spring原理技術內幕');
INSERT INTO `tbl_book` VALUES (2, '計算機理論', 'Spring 5核心原理與30個類手寫實戰', '十年沉淀之作,手寫Spring精華思想');
INSERT INTO `tbl_book` VALUES (3, '計算機理論', 'Spring 5 設計模式', '深入Spring原始碼剖析Spring原始碼中蘊含的10大設計模式');
INSERT INTO `tbl_book` VALUES (4, '計算機理論', 'Spring MVC+MyBatis開發從入門到專案實戰', '全方位決議面向Web應用的輕量級框架,帶你成為Spring MVC開發高手');
INSERT INTO `tbl_book` VALUES (5, '計算機理論', '輕量級Java Web企業應用實戰', '原始碼級剖析Spring框架,適合已掌握Java基礎的讀者');
INSERT INTO `tbl_book` VALUES (6, '計算機理論', 'Java核心技術 卷I 基礎知識(原書第11版)', 'Core Java 第11版,Jolt大獎獲獎作品,針對Java SE9、10、11全面更新');
INSERT INTO `tbl_book` VALUES (7, '計算機理論', '深入理解Java虛擬機', '5個維度全面剖析JVM,大廠面試知識點全覆寫');
INSERT INTO `tbl_book` VALUES (8, '計算機理論', 'Java編程思想(第4版)', 'Java學習必讀經典,殿堂級著作!贏得了全球程式員的廣泛贊譽');
INSERT INTO `tbl_book` VALUES (9, '計算機理論', '零基礎學Java(全彩版)', '零基礎自學編程的入門圖書,由淺入深,詳解Java語言的編程思想和核心技術');
INSERT INTO `tbl_book` VALUES (10, '市場營銷', '直播就該這么做:主播高效溝通實戰指南', '李子柒、李佳琦、薇婭成長為網紅的秘密都在書中');
INSERT INTO `tbl_book` VALUES (11, '市場營銷', '直播銷講實戰一本通', '和秋葉一起學系列網路營銷書籍');
INSERT INTO `tbl_book` VALUES (12, '市場營銷', '直播帶貨:淘寶、天貓直播從新手到高手', '一本教你如何玩轉直播的書,10堂課輕松實作帶貨月入3W+');
  1. 匯入相關坐標
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.itheima</groupId>
  <artifactId>springmvc_08_ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>
	
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.16</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

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

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
      
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>80</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
  1. jdbc配置資檔案準備
// jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=123456
  1. SpringConfig配置類
// SpringConfig

package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

// Spring配置類
@Configuration
// 掃描包
@ComponentScan({"com.itheima.service"})
// 資源載入
@PropertySource("classpath:jdbc.properties")
// 與MyBatis鏈接
@Import({JdbcConfig.class,MyBatisConfig.class})
// 開啟事務平臺
@EnableTransactionManagement
public class SpringConfig {
}
  1. MyBatisConfig配置類
// JdbcConfig

package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

public class JdbcConfig { 
    
    // 獲得配置資源(采用${}獲得)
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    // 設定為Bean
    // 配置資源(這里采用的是DruidDataSource)
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    // 設定為Bean
    // 配置事務平臺(這里采用的是DataSourceTransactionManager)
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
}
// MyBatisConfig

package com.itheima.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MyBatisConfig {

    // 設定為Bean
    // 創建工廠SqlSessionFactory,用于實作資料庫互動
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.itheima.domain");
        return factoryBean;
    }

    // 設定為Bean
    // 創建映射,并定義映射地址,采用MapperScannerConfigurer
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }

}
  1. SpringMvcConfig配置類
// SpringMvcConfig

package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

// Spring配置類
@Configuration
// 掃描包
@ComponentScan("com.itheima.controller")
// 萬能工具注解
@EnableWebMvc
public class SpringMvcConfig {
}
// ServletConfig

package com.itheima.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

// 注意:繼承于AbstractAnnotationConfigDispatcherServletInitializer
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    // 設定SpringConfig
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    // 設定SpringMvcConfig
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    // 設定路徑鎖定"/"即可
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}
  1. 資料庫對應物體類創建
// Book

package com.itheima.domain;

public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
  1. 資料層代碼
// BookDao

package com.itheima.dao;

import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface BookDao {

    // 采用Mapper代理開發
    // 采用#{}匹配引數
    
    @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
    public void save(Book book);

    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public void update(Book book);

    @Delete("delete from tbl_book where id = #{id}")
    public void delete(Integer id);

    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);

    @Select("select * from tbl_book")
    public List<Book> getAll();
}
  1. 業務層代碼
// BookService

package com.itheima.service;

import com.itheima.domain.Book;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

// 給出事務開啟標志
@Transactional
public interface BookService {
    
    // 采用檔案注釋,表明各方法作用

    /**
     * 保存
     * @param book
     * @return
     */
    public boolean save(Book book);

    /**
     * 修改
     * @param book
     * @return
     */
    public boolean update(Book book);

    /**
     * 按id洗掉
     * @param id
     * @return
     */
    public boolean delete(Integer id);

    /**
     * 按id查詢
     * @param id
     * @return
     */
    public Book getById(Integer id);

    /**
     * 查詢全部
     * @return
     */
    public List<Book> getAll();
}
// BookServiceImpl

package com.itheima.service.impl;

import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

// 標記為Bean
@Service
public class BookServiceImpl implements BookService {
    
    // 自動裝配
    @Autowired
    private BookDao bookDao;

    public boolean save(Book book) {
        bookDao.save(book);
        return true;
    }

    public boolean update(Book book) {
        bookDao.update(book);
        return true;
    }

    public boolean delete(Integer id) {
        bookDao.delete(id);
        return true;
    }

    public Book getById(Integer id) {
        return bookDao.getById(id);
    }

    public List<Book> getAll() {
        return bookDao.getAll();
    }
}
  1. 服務層代碼
package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 標記為Bean
// 采用REST書寫方式
@RestController
// 設定總體路徑前綴
@RequestMapping("/books")
public class BookController {

	// 自動裝配
    @Autowired
    private BookService bookService;

    // 新添采用POST請求
    // 資料位于請求體,采用@RequestBody
    @PostMapping
    public boolean save(@RequestBody Book book) {
        return bookService.save(book);
    }

    // 更新采用PUT請求
    // 資料位于請求體,采用@RequestBody
    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }

    // 洗掉采用DELETE請求
    // 資料位于請求路徑,采用@PathVariable,并在路徑采用{}表示
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }

    // 訪問采用GET請求
    // 資料位于請求路徑,采用@PathVariable,并在路徑采用{}表示
    @GetMapping("/{id}")
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }

    // 訪問采用GET請求
    @GetMapping
    public List<Book> getAll() {
        return bookService.getAll();
    }
}

案例測驗階段

  1. Java內部代碼測驗
// 測驗均實作于test檔案夾下

package com.itheima.service;

import com.itheima.config.SpringConfig;
import com.itheima.domain.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

// 測驗采用的junit
@RunWith(SpringJUnit4ClassRunner.class)
// 測驗采用的組態檔
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {

    // 自動裝配
    @Autowired
    private BookService bookService;

    // 查詢id=1的值
    @Test
    public void testGetById(){
        Book book = bookService.getById(1);
        System.out.println(book);
    }

    // 查詢所有資料
    @Test
    public void testGetAll(){
        List<Book> all = bookService.getAll();
        System.out.println(all);
    }

}
  1. Postman測驗

我們需要采用網頁進行測驗是否滿足需求,下面僅列出簡單示例:

案例總結階段

以上部分就是根據我們之前所學內容所整合出來的整體框架,我們已經基本做成了一個簡單的服務器

SSM表現層資料封裝

我們在上一小節已經完成了一個基本專案的開發

但是我們會注意到我們服務層的回傳資料型別不盡相同:

package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    // 我們會注意到我們回傳的資料有時為boolean,有時為Book,有時為List<Book>
    
    @PostMapping
    public boolean save(@RequestBody Book book) {
        return bookService.save(book);
    }

    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }

    @GetMapping("/{id}")
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }

    @GetMapping
    public List<Book> getAll() {
        return bookService.getAll();
    }
}

我們需要注意的是:

  • 專案并非我們一個人開發,我們在實際開發中大部分前后端是分離的,也就是說我們回傳的資料是回傳給前端進行處理的
  • 但前端并不熟悉后端的代碼,所以我們如果毫無忌憚的傳遞沒有任何說明的資料,前端是無法把它做成頁面展現出來的
  • 所以前后端通常需要一種規范來設計回傳型別,讓前端能夠明白后端所傳遞的資料,我們通常把他稱為表現層資料封裝

表現層資料封裝概念

為了保障前后端溝通無障礙,在專案開始時,前后端會進行一次溝通來確定后端傳遞資料的規范,我們通常把它稱為表現層資料封裝

我們通常采用一個實作類來規定資料封裝格式:

public class Result{
    
    // 這里我們假設給出三種資料來進行前后端溝通
    /*
    data:資料內容
    code:狀態碼
    msg:相關資訊
    */
	private Object data;
    private Integer code;
    private String msg;
}

這里的data資料就是取自表現層資料,code是雙方規定的狀態碼,msg是用于提供相關附屬資訊

Result類中的欄位不是固定的,可以根據需求自行刪減

注意需要提供若干個構造方法,方便操作

表現層資料封裝操作

接下里我們以第一階段案例給出相關修改案例:

  1. 設計Code狀態碼
package com.itheima.controller;

//狀態碼
//通常是雙方協議或公司規定
public class Code {
    public static final Integer SAVE_OK = 20011;
    public static final Integer DELETE_OK = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer GET_OK = 20041;

    public static final Integer SAVE_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer GET_ERR = 20040;
}
  1. 設計Result回傳資料規范
package com.itheima.controller;

public class Result {
    //描述統一格式中的資料
    private Object data;
    //描述統一格式中的編碼,用于區分操作,可以簡化配置0或1表示成功失敗
    private Integer code;
    //描述統一格式中的訊息,可選屬性
    private String msg;

    // 注意:我們需要提供構造方法便捷操作
    
    public Result() {
    }

    public Result(Integer code,Object data) {
        this.data = https://www.cnblogs.com/qiuluoyuweiliang/p/data;
        this.code = code;
    }

    public Result(Integer code, Object data, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
  1. 服務層回傳資料更替
package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//統一每一個控制器方法回傳值
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    // 我們按照Result的構造方法以及實際需求提供回傳值
    // 我們可以根據三目運算子來直接輸出其結果
    
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "資料查詢失敗,請重試!";
        return new Result(code,book,msg);
    }

    @GetMapping
    public Result getAll() {
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "資料查詢失敗,請重試!";
        return new Result(code,bookList,msg);
    }
}

例外處理器

我們的程式可能或者說必然會出現一些漏洞,有些可能是人為的,有些可能是我們代碼的問題

所以為了處理這些例外,首先我們需要把例外出現的常見位置與原因進行分類:

  • 框架內部拋出的例外:因使用不合規導致
  • 資料層拋出的例外:因外部服務器故障導致(例如:服務器訪問超時)
  • 業務層拋出的例外:因業務邏輯書寫錯誤導致(例如:遍歷業務書寫操作,導致索引例外等)
  • 表現層拋出的例外:因資料收集,校驗等規則導致(例如:不匹配的資料型別間導致例外)
  • 工具類拋出的例外:因工具類書寫不嚴謹不夠健全導致(例如:必要釋放的連接長期未釋放)

那么我們來思考兩個問題來確定例外處理器的書寫方法和位置:

  1. 在上述我們可以看到各個層級都會出現問題,那么我們的例外處理器應該寫在哪一層?
  • 所有的例外均向上拋出至表現層進行處理
  1. 表現層處理例外,每個方法單獨書寫,代碼書寫量巨大且意義不大,該怎么處理?
  • 采用AOP思想

撰寫基本例外處理器

我們常常會集中的,統一的處理專案中出現的例外

前面我們說過需要在表現層統一處理例外,所以我們選擇在表現層書寫例外處理器:

package com.itheima.controller;

import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//@RestControllerAdvice用于標識當前類為REST風格對應的例外處理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
    
    // @ExceptionHandler用于設定當前處理器類對應的例外型別
    // 這里處理的是Exception.class,屬于最大的例外處理
    @ExceptionHandler(Exception.class)
    public Result doOtherException(Exception ex){
        // Code.SYSTEM_UNKNOW_ERR是在Code狀態碼檔案中統一設定的,null是回傳值,后面屬于附加內容用于安撫用戶
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系統繁忙,請稍后再試!");
    }
}

/*
名稱:@RestControllerAdvice
型別:類注解
位置:Rest風格開發的控制器增強類定義上方
作用:為Rest風格開發的控制器類做增強
說明:此注解自帶@ResponseBody注解與@Component注解,具備對應的功能

名稱:@ExceptionHandler
型別:方法注解
位置:專用于例外處理的控制器方法上方
作用:設定指定例外的處理方案,功能等同于控制器方法,出現例外后終止原始控制器操作,并轉入該方法進行執行
說明:此類方法可以根據處理的例外不同,制作多個方法分別處理對應的例外

*/

撰寫專案例外處理

我們的專案例外處理通常不會直接對最大例外處理

因為我們的專案通常會出現很多種型別的例外,例如用戶操作錯誤產生的例外,編程人員未預期到的例外

我們進行一個簡單的分類:

  • 業務例外(BusinessException)
    • 規范的用戶行為產生的例外
    • 不規范的用戶行為操作產生的例外
  • 系統例外(SystemException)
    • 專案運行程序中可預計且無法避免的例外
  • 其他例外(Exception)
    • 編程人員未預期到的例外

對于不同的例外,我們采用不同的應對方法,我們下面做出簡單的處理:

  1. Code狀態碼增加
package com.itheima.controller;

public class Code {
    public static final Integer SAVE_OK = 20011;
    public static final Integer DELETE_OK = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer GET_OK = 20041;

    public static final Integer SAVE_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer GET_ERR = 20040;

    public static final Integer SYSTEM_ERR = 50001;
    public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
    public static final Integer SYSTEM_UNKNOW_ERR = 59999;

    public static final Integer BUSINESS_ERR = 60002;
}
  1. 書寫自定義例外處理器
// SystemException

package com.itheima.exception;
//自定義例外處理器,用于封裝例外資訊,對例外進行分類,需要繼承RuntimeException
public class SystemException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

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

    public SystemException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public SystemException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }

}
// BusinessException

package com.itheima.exception;
//自定義例外處理器,用于封裝例外資訊,對例外進行分類,需要繼承RuntimeException
public class BusinessException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

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

    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public BusinessException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }

}
  1. 這里選擇在業務層拋出例外
package com.itheima.service.impl;

import com.itheima.controller.Code;
import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    public boolean save(Book book) {
        bookDao.save(book);
        return true;
    }

    public boolean update(Book book) {
        bookDao.update(book);
        return true;
    }

    public boolean delete(Integer id) {
        bookDao.delete(id);
        return true;
    }

    public Book getById(Integer id) {
        //模擬業務例外,包裝成自定義例外
        if(id == 1){
            throw new BusinessException(Code.BUSINESS_ERR,"請不要使用你的技術挑戰我的耐性!");
        }
        //模擬系統例外,將可能出現的例外進行包裝,轉換成自定義例外
        try{
            int i = 1/0;
        }catch (Exception e){
            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服務器訪問超時,請重試!",e);
        }
        return bookDao.getById(id);
    }

    public List<Book> getAll() {
        return bookDao.getAll();
    }
}
  1. 表現層例外處理器增加
package com.itheima.controller;

import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//@RestControllerAdvice用于標識當前類為REST風格對應的例外處理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
    //@ExceptionHandler用于設定當前處理器類對應的例外型別
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){
        //記錄日志
        //發送訊息給運維
        //發送郵件給開發人員,ex物件發送給開發人員
        return new Result(ex.getCode(),null,ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex){
        return new Result(ex.getCode(),null,ex.getMessage());
    }

    //除了自定義的例外處理器,保留對Exception型別的例外處理,用于處理非預期的例外
    @ExceptionHandler(Exception.class)
    public Result doOtherException(Exception ex){
        //記錄日志
        //發送訊息給運維
        //發送郵件給開發人員,ex物件發送給開發人員
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系統繁忙,請稍后再試!");
    }
}

前后端協議聯調

在定義了前后端的協議規范并完成了后端開發后,我們還需要設計前端的開發

關于前端開發并不是我們的重點,所以下面只作簡單介紹

攔截器設定

首先我們需要注意我們的SpringMVC的攔截路徑設定為全部路徑:

// ServletContainersInitConfig

package com.itheima.config;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    protected String[] getServletMappings() {
        // 系統會將全部路徑下的請求都交付給SpringMVC處理
        return new String[]{"/"};
    }

    //亂碼處理
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}

所以當我們查詢主頁網頁時,會被SpringMVC接收并且要求回傳一個相關的服務層方法,很明顯這是錯誤的

所以我們需要設定一個攔截器用來放行一些網頁相關的資源,使用戶訪問時,直接將相關頁面資源反饋回去:

// 我們選擇在Config檔案夾下創建SpringMvcSupport繼承WebMvcConfigurationSupport作為SpringMVC的工具類

package com.itheima.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

// 需要繼承WebMvcConfigurationSupport用作工具類
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    
    // 繼承addResourceHandlers方法,進行放行操作
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 利用引數registry,addResourceHandler后跟引數路徑,addResourceLocations后跟訪問頁面
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }
}

同時記得在SpringMvcConfig中掃描相關類:

// SpringMvcConfig

package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan({"com.itheima.controller","com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig {
}

前端操作簡單講解

當我們設定好攔截器后,我們就可以通過頁面訪問進入到html主頁:

我們希望可以實作查詢,創建,修改,洗掉等操作

在下述操作中我們采用html和Ajax兩門技術實作上述操作:

  1. 首先我們需要在Dao資料層進行一些回傳值的修改:
package com.itheima.dao;

import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface BookDao {
    // 我們采用int作為回傳值,當作資料庫操作的行數回傳值,用來判斷是否操作成功

    @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
    public int save(Book book);

    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public int update(Book book);

    @Delete("delete from tbl_book where id = #{id}")
    public int delete(Integer id);

    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);

    @Select("select * from tbl_book")
    public List<Book> getAll();
}
  1. 我們對html頁面進行操作:
<!DOCTYPE html>

<html>

    <head>

        <!-- 頁面meta -->

        <meta charset="utf-8">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <title>SpringMVC案例</title>

        <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">

        <!-- 引入樣式 -->

        <link rel="stylesheet" href="https://www.cnblogs.com/qiuluoyuweiliang/plugins/elementui/index.css">

        <link rel="stylesheet" href="https://www.cnblogs.com/qiuluoyuweiliang/plugins/font-awesome/css/font-awesome.min.css">

        <link rel="stylesheet" href="https://www.cnblogs.com/qiuluoyuweiliang/css/style.css">

    </head>

    <body >

        <div id="app">

            <div >

                <h1>圖書管理</h1>

            </div>

            <div >

                <div >

                    <div >

                        <el-input placeholder="圖書名稱" v-model="pagination.queryString" style="width: 200px;" ></el-input>

                        <el-button @click="getAll()" >查詢</el-button>

                        <el-button type="primary"  @click="handleCreate()">新建</el-button>

                    </div>

                    <el-table size="small" current-row-key="id" :data="https://www.cnblogs.com/qiuluoyuweiliang/p/dataList" stripe highlight-current-row>

                        <el-table-column type="index" align="center" label="序號"></el-table-column>

                        <el-table-column prop="type" label="圖書類別" align="center"></el-table-column>

                        <el-table-column prop="name" label="圖書名稱" align="center"></el-table-column>

                        <el-table-column prop="description" label="描述" align="center"></el-table-column>

                        <el-table-column label="操作" align="center">

                            <template slot-scope="scope">

                                <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">編輯</el-button>

                                <el-button type="danger" size="mini" @click="handleDelete(scope.row)">洗掉</el-button>

                            </template>

                        </el-table-column>

                    </el-table>

                    <!-- 新增標簽彈層 -->

                    <div >

                        <el-dialog title="新增圖書" :visible.sync="dialogFormVisible">

                            <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label->

                                <el-row>

                                    <el-col :span="12">

                                        <el-form-item label="圖書類別" prop="type">

                                            <el-input v-model="formData.type"/>

                                        </el-form-item>

                                    </el-col>

                                    <el-col :span="12">

                                        <el-form-item label="圖書名稱" prop="name">

                                            <el-input v-model="formData.name"/>

                                        </el-form-item>

                                    </el-col>

                                </el-row>


                                <el-row>

                                    <el-col :span="24">

                                        <el-form-item label="描述">

                                            <el-input v-model="formData.description" type="textarea"></el-input>

                                        </el-form-item>

                                    </el-col>

                                </el-row>

                            </el-form>

                            <div slot="footer" >

                                <el-button @click="dialogFormVisible = false">取消</el-button>

                                <el-button type="primary" @click="handleAdd()">確定</el-button>

                            </div>

                        </el-dialog>

                    </div>

                    <!-- 編輯標簽彈層 -->

                    <div >

                        <el-dialog title="編輯檢查項" :visible.sync="dialogFormVisible4Edit">

                            <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" label->

                                <el-row>

                                    <el-col :span="12">

                                        <el-form-item label="圖書類別" prop="type">

                                            <el-input v-model="formData.type"/>

                                        </el-form-item>

                                    </el-col>

                                    <el-col :span="12">

                                        <el-form-item label="圖書名稱" prop="name">

                                            <el-input v-model="formData.name"/>

                                        </el-form-item>

                                    </el-col>

                                </el-row>

                                <el-row>

                                    <el-col :span="24">

                                        <el-form-item label="描述">

                                            <el-input v-model="formData.description" type="textarea"></el-input>

                                        </el-form-item>

                                    </el-col>

                                </el-row>

                            </el-form>

                            <div slot="footer" >

                                <el-button @click="dialogFormVisible4Edit = false">取消</el-button>

                                <el-button type="primary" @click="handleEdit()">確定</el-button>

                            </div>

                        </el-dialog>

                    </div>

                </div>

            </div>

        </div>

    </body>

    <!-- 引入組件庫 -->

    <script src="https://www.cnblogs.com/qiuluoyuweiliang/js/vue.js"></script>

    <script src="https://www.cnblogs.com/qiuluoyuweiliang/plugins/elementui/index.js"></script>

    <script type="text/javascript" src="https://www.cnblogs.com/qiuluoyuweiliang/js/jquery.min.js"></script>

    <script src="https://www.cnblogs.com/qiuluoyuweiliang/js/axios-0.18.0.js"></script>

    <script>
        var vue = new Vue({

            el: '#app',
            data:{
                pagination: {},
				dataList: [],//當前頁要展示的串列資料
                formData: {},//表單資料
                dialogFormVisible: false,//控制表單是否可見
                dialogFormVisible4Edit:false,//編輯表單是否可見
                rules: {//校驗規則
                    type: [{ required: true, message: '圖書類別為必填項', trigger: 'blur' }],
                    name: [{ required: true, message: '圖書名稱為必填項', trigger: 'blur' }]
                }
            },

            //鉤子函式,VUE物件初始化完成后自動執行
            created() {
                this.getAll();
            },

            methods: {
                //串列
                getAll() {
                    //發送ajax請求
                    axios.get("/books").then((res)=>{
                        this.dataList = res.data.data;
                    });
                },

                //彈出添加視窗
                handleCreate() {
                    this.dialogFormVisible = true;
                    this.resetForm();
                },

                //重置表單
                resetForm() {
                    this.formData = https://www.cnblogs.com/qiuluoyuweiliang/p/{};
                },

                //添加
                handleAdd () {
                    //發送ajax請求
                    axios.post("/books",this.formData).then((res)=>{
                        console.log(res.data);
                        //如果操作成功,關閉彈層,顯示資料
                        if(res.data.code == 20011){
                            this.dialogFormVisible = false;
                            this.$message.success("添加成功");
                        }else if(res.data.code == 20010){
                            this.$message.error("添加失敗");
                        }else{
                            this.$message.error(res.data.msg);
                        }
                    }).finally(()=>{
                        this.getAll();
                    });
                },

                //彈出編輯視窗
                handleUpdate(row) {
                    // console.log(row);   //row.id 查詢條件
                    //查詢資料,根據id查詢
                    axios.get("/books/"+row.id).then((res)=>{
                        // console.log(res.data.data);
                        if(res.data.code == 20041){
                            //展示彈層,加載資料
                            this.formData = https://www.cnblogs.com/qiuluoyuweiliang/p/res.data.data;
                            this.dialogFormVisible4Edit = true;
                        }else{
                            this.$message.error(res.data.msg);
                        }
                    });
                },

                //編輯
                handleEdit() {
                    //發送ajax請求
                    axios.put("/books",this.formData).then((res)=>{
                        //如果操作成功,關閉彈層,顯示資料
                        if(res.data.code == 20031){
                            this.dialogFormVisible4Edit = false;
                            this.$message.success("修改成功");
                        }else if(res.data.code == 20030){
                            this.$message.error("修改失敗");
                        }else{
                            this.$message.error(res.data.msg);
                        }
                    }).finally(()=>{
                        this.getAll();
                    });
                },

                // 洗掉
                handleDelete(row) {
                    //1.彈出提示框
                    this.$confirm("此操作永久洗掉當前資料,是否繼續?","提示",{
                        type:'info'
                    }).then(()=>{
                        //2.做洗掉業務
                        axios.delete("/books/"+row.id).then((res)=>{
                            if(res.data.code == 20021){
                                this.$message.success("洗掉成功");
                            }else{
                                this.$message.error("洗掉失敗");
                            }
                        }).finally(()=>{
                            this.getAll();
                        });
                    }).catch(()=>{
                        //3.取消洗掉
                        this.$message.info("取消洗掉操作");
                    });
                }
            }
        })

    </script>

</html>

攔截器

我們在前面已經接觸到了攔截器,在這一節中我們詳細介紹一下攔截器

攔截器定義:

  • 一種動態攔截方法呼叫的機制

攔截器作用:

  • 在指定的方法呼叫前后執行預先設定的代碼
  • 阻止原始方法的執行

攔截器的大概圖示如下:

簡單講解:

  • html發送的所有資料被Tomcat所接收
  • 對于靜態資料我們直接歸納于靜態資源中不做處理
  • 對于動態資源,我們先通過Filter過濾器進行過濾,然后才進入到Spring階段進行處理
  • 進入Spring階段之后,我們開始進行處理,但在對Controller服務層進行操作前,需要進行的檢測或者補充內容就是攔截器

攔截器和過濾器的區別:

歸屬不同:Filter屬于Servlet技術,Interceptor屬于SpringMVC技術

攔截內容不同:Filter對所有訪問進行增強,Interceptor僅針對SpringMVC的訪問進行增強

攔截器入門案例

我們同樣采用一個案例來進行攔截器的講解:

  1. 創建攔截器(我們通常在Controller檔案夾下創建一個Interceptor檔案夾來存放各種攔截器)
// src/main/java/com/itheima/controller/interceptor/ProjectInterceptor.java

package com.itheima.controller.interceptor;

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

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

@Component
//定義攔截器類,實作HandlerInterceptor介面
//注意當前類必須受Spring容器控制(采用@Component)
public class ProjectInterceptor implements HandlerInterceptor {
    @Override
    //原始方法呼叫前執行的內容
    //回傳值型別可以攔截控制的執行,true放行,false終止
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        return true;
    }

    @Override
    //原始方法呼叫后執行的內容
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override
    //原始方法呼叫完成后執行的內容
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
  1. 創建攔截路徑(在SpringMvcSupport中操作)
package com.itheima.config;

import com.itheima.controller.interceptor.ProjectInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    
    // 這里我們自動裝配我們之前配置過的攔截器
    @Autowired
    private ProjectInterceptor projectInterceptor;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
    }

    // 我們繼承實作addInterceptors方法添加攔截
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //配置攔截器(addInterceptor后面跟攔截器,addPathPatterns后面跟攔截路徑)
        registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
    }
}
  1. 記得在SpringMvcConfig中添加掃描路徑
package com.itheima.config;

import com.itheima.controller.interceptor.ProjectInterceptor;
import com.itheima.controller.interceptor.ProjectInterceptor2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ComponentScan({"com.itheima.controller","com.itheima.config"})
@EnableWebMvc
//實作WebMvcConfigurer介面可以簡化開發,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
}

攔截器入門案例簡化開發

上述是我們正常開發的流程,但實際上我們還存在一種簡化開發的方法:

  1. 創建攔截器(不發生變化)
// src/main/java/com/itheima/controller/interceptor/ProjectInterceptor.java

package com.itheima.controller.interceptor;

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

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

@Component
//定義攔截器類,實作HandlerInterceptor介面
//注意當前類必須受Spring容器控制(采用@Component)
public class ProjectInterceptor implements HandlerInterceptor {
    @Override
    //原始方法呼叫前執行的內容
    //回傳值型別可以攔截控制的執行,true放行,false終止
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        return true;
    }

    @Override
    //原始方法呼叫后執行的內容
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override
    //原始方法呼叫完成后執行的內容
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
  1. 我們直接在SpringMvcConfig中實作攔截方法的添加
package com.itheima.config;

import com.itheima.controller.interceptor.ProjectInterceptor;
import com.itheima.controller.interceptor.ProjectInterceptor2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
// 直接繼承WebMvcConfigurer介面,實作內部方法即可
//實作WebMvcConfigurer介面可以簡化開發,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
    @Autowired
    private ProjectInterceptor projectInterceptor;

    // 實作addInterceptors方法,添加攔截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
    }
}

攔截器執行程序

我們在前面介紹了攔截器的相關代碼,現在我們來簡單介紹一下攔截器的執行程序:

package com.itheima.controller.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
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 ProjectInterceptor implements HandlerInterceptor {
    @Override
    //原始方法呼叫前執行的內容
    //回傳值型別可以攔截控制的執行,true放行,false終止
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        return true;
    }

    @Override
    //原始方法呼叫后執行的內容
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override
    //原始方法呼叫完成后執行的內容
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

根據上述代碼,我們可以基本確定其執行順序為:

注意:當PreHandle反饋出false時,所有后續操作均失效!

攔截器引數

攔截器一共分為三個方法,接下來我們對方法中的各個引數進行解釋:

  1. 前置處理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 我們可以根據request,response獲得網頁互動資訊
        String contentType = request.getHeader("Content-Type");
        // 我們可以根據handler轉換型別為HandlerMethod,從而完成了一些暴力反射操作
        HandlerMethod hm = (HandlerMethod)handler;
        System.out.println("preHandle..."+contentType);
        return true;
    }

引數:

  • request:請求物件
  • response:回應物件
  • handler:被呼叫的處理器物件,本質上是一個方法物件,對反射技術中的Method物件進行了再包裝

回傳值:

  • 回傳值為true,后續操作執行
  • 回傳值為false,后續操作不執行
  1. 后置處理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

引數:

  • modelAndView:如果處理器執行完成具有回傳結果,可以讀取到對應資料與頁面資訊進行調整(了解即可)
  1. 完成后操作
    @Override
    //原始方法呼叫完成后執行的內容
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }

引數:

  • ex:如果處理器執行程序中出現例外物件,可以針對例外情況進行單獨處理(了解即可)

攔截器鏈配置

攔截器和過濾器同樣,可以配置多個,也具有一定的攔截順序

我們先給出代碼展示:

  1. 攔截器設定:
package com.itheima.controller.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
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 ProjectInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...);
        return true;
    }

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

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
package com.itheima.controller.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
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 ProjectInterceptor2 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...222");
        return false;
    }

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

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...222");
    }
}
  1. 攔截器添加
package com.itheima.config;

import com.itheima.controller.interceptor.ProjectInterceptor;
import com.itheima.controller.interceptor.ProjectInterceptor2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
//實作WebMvcConfigurer介面可以簡化開發,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
    @Autowired
    private ProjectInterceptor projectInterceptor;
    @Autowired
    private ProjectInterceptor2 projectInterceptor2;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //配置多攔截器
        registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
        registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
    }
}

經過測驗,我們可以發現:

// 正常運行
preHandle...
preHandle...222
具體操作...
postHandle...222
postHandle...
afterCompletion...222
afterCompletion...
// 攔截器2出錯
preHandle...
preHandle...222
afterCompletion...
// 攔截器1出錯
preHandle...

三層攔截器具體操作圖:

所以我們可以總結出相關規定:

  • 當配置多個攔截器時,形成攔截器鏈
  • 攔截器鏈的運行順序參照攔截器的添加順序為準
  • 當攔截器中出現對原始處理器的攔截,后面的攔截器均終止運行
  • 當攔截器運行中斷,僅運行配置在前面的攔截器的afterCompletion操作

結束語

好的,關于SSM整合的內容就介紹到這里,希望能為你帶來幫助!

附錄

該文章屬于學習內容,具體參考B站黑馬程式員李老師的SSM框架課程

這里附上鏈接:SpringMVC-17-SSM整合(整合配置)_嗶哩嗶哩_bilibili

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/511084.html

標籤:架構設計

上一篇:沒有所謂的B/S架構,只有C/S

下一篇:新零售SaaS架構:中央庫存系統架構設計

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 面試突擊第一季,第二季,第三季

    第一季必考 https://www.bilibili.com/video/BV1FE411y79Y?from=search&seid=15921726601957489746 第二季分布式 https://www.bilibili.com/video/BV13f4y127ee/?spm_id_fro ......

    uj5u.com 2020-09-10 05:35:24 more
  • 第三單元作業總結

    1.前言 這應該是本學期最后一次寫作業總結了吧。總體來說,對作業的節奏也差不多掌握了,作業做起來的效率也更高了。雖然和之前的作業一樣,作業中都要用到新的知識,但是相比之前,更加懂得了如何利用工具以及資料。雖然之間卡過殼,但總體而言,這幾次作業還算完成的比較好。 2.作業程序總結 相比前兩個單元,此單 ......

    uj5u.com 2020-09-10 05:35:41 more
  • 北航OO(2020)第四單元博客作業暨課程總結博客

    北航OO(2020)第四單元博客作業暨課程總結博客 本單元作業的架構設計 在本單元中,由于UML圖具有比較清晰的樹形結構,因此我對其中需要進行查詢操作的元素進行了包裝,在樹的父節點中存盤所有孩子的參考。考慮到性能問題,我采用了快取機制,一次查詢后盡可能快取已經遍歷過的資訊,以減少遍歷次數。 本單元我 ......

    uj5u.com 2020-09-10 05:35:48 more
  • BUAA_OO_第四單元

    一、UML決議器設計 ? 先看下題目:第四單元實作一個基于JDK 8帶有效性檢查的UML(Unified Modeling Language)類圖,順序圖,狀態圖分析器 MyUmlInteraction,實際上我們要建立一個有向圖模型,UML中的物件(元素)可能與同級元素連接,也可與低級元素相連形成 ......

    uj5u.com 2020-09-10 05:35:54 more
  • 6.1邏輯運算子

    邏輯運算子 1. && 短路與 運算式1 && 運算式2 01.運算式1為true并且運算式2也為true 整體回傳為true 02.運算式1為false,將不會執行運算式2 整體回傳為false 03.只要有一個運算式為false 整體回傳為false 2. || 短路或 運算式1 || 運算式2 ......

    uj5u.com 2020-09-10 05:35:56 more
  • BUAAOO 第四單元 & 課程總結

    1. 第四單元:StarUml檔案決議 本單元采用了圖模型決議UML。 UML檔案可以抽象為圖、子圖、邊的邏輯結構。 在實作中,圖的節點包括類、介面、屬性,子圖包括狀態圖、順序圖等。 采用了三次遍歷UML元素的方法建圖,第一遍遍歷建點,第二、三次遍歷設定屬性、連邊,實作圖物件的初始化。這里借鑒了一些 ......

    uj5u.com 2020-09-10 05:36:06 more
  • 談談我對C# 多型的理解

    面向物件三要素:封裝、繼承、多型。 封裝和繼承,這兩個比較好理解,但要理解多型的話,可就稍微有點難度了。今天,我們就來講講多型的理解。 我們應該經常會看到面試題目:請談談對多型的理解。 其實呢,多型非常簡單,就一句話:呼叫同一種方法產生了不同的結果。 具體實作方式有三種。 一、多載 多載很簡單。 p ......

    uj5u.com 2020-09-10 05:36:09 more
  • Python 資料驅動工具:DDT

    背景 python 的unittest 沒有自帶資料驅動功能。 所以如果使用unittest,同時又想使用資料驅動,那么就可以使用DDT來完成。 DDT是 “Data-Driven Tests”的縮寫。 資料:http://ddt.readthedocs.io/en/latest/ 使用方法 dd. ......

    uj5u.com 2020-09-10 05:36:13 more
  • Python里面的xlrd模塊詳解

    那我就一下面積個問題對xlrd模塊進行學習一下: 1.什么是xlrd模塊? 2.為什么使用xlrd模塊? 3.怎樣使用xlrd模塊? 1.什么是xlrd模塊? ?python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫。 今天就先來說一下xl ......

    uj5u.com 2020-09-10 05:36:28 more
  • 當我們創建HashMap時,底層到底做了什么?

    jdk1.7中的底層實作程序(底層基于陣列+鏈表) 在我們new HashMap()時,底層創建了默認長度為16的一維陣列Entry[ ] table。當我們呼叫map.put(key1,value1)方法向HashMap里添加資料的時候: 首先,呼叫key1所在類的hashCode()計算key1 ......

    uj5u.com 2020-09-10 05:36:38 more
最新发布
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:20:47 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:20:25 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:20:17 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:20:10 more
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:19:44 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:19:07 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:18:57 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:18:49 more
  • 05單件模式

    #經典的單件模式 public class Singleton { private static Singleton uniqueInstance; //一個靜態變數持有Singleton類的唯一實體。 // 其他有用的實體變數寫在這里 //構造器宣告為私有,只有Singleton可以實體化這個類! ......

    uj5u.com 2023-04-19 08:42:51 more
  • 【架構與設計】常見微服務分層架構的區別和落地實踐

    軟體工程的方方面面都遵循一個最基本的道理:沒有銀彈,架構分層模型更是如此,每一種都有各自優缺點,所以請根據不同的業務場景,并遵循簡單、可演進這兩個重要的架構原則選擇合適的架構分層模型即可。 ......

    uj5u.com 2023-04-19 08:42:41 more