亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot增強Controller方法@ControllerAdvice注解的使用詳解

 更新時間:2023年10月12日 10:31:19   作者:fengyehongWorld  
這篇文章主要介紹了SpringBoot增強Controller方法@ControllerAdvice注解的使用詳解,@ControllerAdvice,是Spring3.2提供的新注解,它是一個Controller增強器,可對controller進行增強處理,需要的朋友可以參考下

一. @ControllerAdvice注解作用

@ControllerAdvice ,是Spring3.2提供的新注解,它是一個Controller增強器,可對controller進行增強處理。

  • 配合@ExceptionHandler注解,進行全局異常處理。
  • 配合@InitBinder注解,用來設(shè)置WebDataBinder,用于自動綁定前臺請求參數(shù)到Model中,全局?jǐn)?shù)據(jù)預(yù)處理,多用于表單提交數(shù)據(jù)或者url傳參。
  • 配合@ModelAttribute注解,讓Controller類中所有的方法都可以獲取到通過@ModelAttribute注解設(shè)置的值,進行全局?jǐn)?shù)據(jù)綁定。

注意: @ControllerAdvice 注解將作用在所有Controller層的方法上。

二. @ControllerAdvice注解 + assignableTypes屬性

作用:增強指定 .class 的類,非指定的Controller類不會被增強

2.1 @ControllerAdvice增強類

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// 指定增強S001LoginController和S002LogoutController
@ControllerAdvice(assignableTypes = {S001LoginController.class, S002LogoutController.class})
public class S_Controller {
    @Autowired
    private HttpServletRequest request;
	// 方式1: @ModelAttribute注解的使用
    @ModelAttribute
    public void initData1(Model model) {
        request.setAttribute("num1", 66);
        model.addAttribute("userMail", List.of("123@mail.com", "456@mail.com"));
    }
	// 方式2: @ModelAttribute注解的使用
    @ModelAttribute(name = "userInfo")
    public Map<String, String> initData2() {
        request.setAttribute("num2", 99);
       return new HashMap<>(){
           {
               put("name", "賈飛天");
               put("age", "18");
           }
       };
    }
	// 捕獲S001LoginController或S002LogoutController類中的Exception異常
    @ExceptionHandler(Exception.class)
    public void exceptionHandle(Exception ex) {
        System.out.println(ex.getMessage());
    }
}

2.2 Controller層

目錄結(jié)構(gòu)如下

  • s_controller包
    • S001LoginController.java
    • S002LogoutController.java
    • S003Controller.java

說明

  • @ControllerAdvice增強類中,指定對S001LoginController.java和S002LogoutController.java進行了增強,因此這兩個類中可以獲取到增強類中放入的數(shù)據(jù),并且這兩個類中拋出的Exception異常也會被增強類所捕獲。
  • 由于S003Controller.java并沒有被增強,因此該類無法獲取增強類中放入的數(shù)據(jù),并且拋出的異常也無法被增強類捕獲。

S001LoginController.java

有2種方式可以獲取出@ControllerAdvice增強類中放入Model中的數(shù)據(jù)

  1. model.asMap()
  2. @ModelAttribute("key名稱") 類型 變量名

還可以通過request.getAttribute("key名稱")來獲取放入request的attribute中的數(shù)據(jù)。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/ss001")
public class S001LoginController {
    @Autowired
    private HttpServletRequest request;
    @GetMapping("/init")
    public ModelAndView init(Model model) {
		// ?方式1: 獲取出@ControllerAdvice增強類中提前放入Model中的數(shù)據(jù)
        Map<String, Object> mapInfo = model.asMap();
        Object userMailObj = mapInfo.get("userMail");
        List<String> userMailList = (List<String>)userMailObj;
        System.out.println(userMailList);  // [123@mail.com, 456@mail.com]
        Map<String, String> userInfoMap = (Map<String, String>) mapInfo.get("userInfo");
        System.out.println(userInfoMap);  // {name=賈飛天, age=18}
		// ?獲取出@ControllerAdvice增強類中提前放入request的attribute中的數(shù)據(jù)
        Integer num1 = (Integer) request.getAttribute("num1");
        System.out.println(num1);  // 66
        Integer num2 = (Integer) request.getAttribute("num2");
        System.out.println(num2);  // 99
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("s001");
        return modelAndView;
    }
    @GetMapping("/showInfo")
    @ResponseBody
    public void showInfo(
    		// ?方式2: 獲取出@ControllerAdvice增強類中提前放入Model中的數(shù)據(jù)
            @ModelAttribute("userMail") List<String> userMail
            , @ModelAttribute("userInfo") Map<String, String> userInfo
    ) {
        System.out.println(userMail);  // [123@mail.com, 456@mail.com]
        System.out.println(userInfo);  // {name=賈飛天, age=18}
    }
}

S002LogoutController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
@Controller
@RequestMapping("/ss002")
public class S002LogoutController {
    @GetMapping("/init")
    public ModelAndView init(Model model) {
		// 獲取出@ControllerAdvice增強類中提前放入Model中的數(shù)據(jù)
        Map<String, Object> mapInfo = model.asMap();
        System.out.println(mapInfo);
		// 代碼出現(xiàn)異常
        int num = 1 / 0;
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("s002");
        return modelAndView;
    }
}

S003Controller.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/ss003")
public class S003Controller {
    @GetMapping("/init")
    public ModelAndView init() {
        int num = 1 / 0;
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("s003");
        return modelAndView;
    }
}

2.3 效果

獲取數(shù)據(jù)

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

異常

在這里插入圖片描述

三. @ControllerAdvice注解 + basePackages屬性

增強指定包下面所有的Controller

3.1 @ControllerAdvice增強類

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice(basePackages = {"com.example.jmw.t_controller"})
public class T_Controller {
    @ExceptionHandler(Exception.class)
    public void exceptionHandle(Exception ex) {
        System.out.println(ex.getMessage());
    }
}

四. @ControllerAdvice注解 + annotations屬性

增強標(biāo)記了 指定注解 的所有的Controller

4.1 自定義注解

import java.lang.annotation.*;
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerMarkAnnotation {
}

4.2 @ControllerAdvice增強類

mport org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice(annotations = ControllerMarkAnnotation.class)
public class X_Controller {
    @ExceptionHandler(Exception.class)
    public void exceptionHandle(Exception ex) {
        System.out.println(ex.getMessage());
    }
}

到此這篇關(guān)于SpringBoot增強Controller方法@ControllerAdvice注解的使用詳解的文章就介紹到這了,更多相關(guān)SpringBoot的@ControllerAdvice注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論