1. 程式人生 > 其它 >實現WebMvcConfigurer介面擴充套件Spring MVC的功能

實現WebMvcConfigurer介面擴充套件Spring MVC的功能

技術標籤:spring boot

前言:

先檢視WebMvcConfigurer介面中都定義了哪些內容

public interface WebMvcConfigurer {
    default void configurePathMatch(PathMatchConfigurer configurer) {
    }
    default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    }
    default void configureAsyncSupport
(AsyncSupportConfigurer configurer) { } default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { } default void addFormatters(FormatterRegistry registry) { } default void addInterceptors(InterceptorRegistry registry) { } default void addResourceHandlers
(ResourceHandlerRegistry registry) { } default void addCorsMappings(CorsRegistry registry) { } default void addViewControllers(ViewControllerRegistry registry) { } default void configureViewResolvers(ViewResolverRegistry registry) { } default void addArgumentResolvers
(List<HandlerMethodArgumentResolver> resolvers) { } default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) { } default void configureMessageConverters(List<HttpMessageConverter<?>> converters) { } default void extendMessageConverters(List<HttpMessageConverter<?>> converters) { } default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } @Nullable default Validator getValidator() { return null; } @Nullable default MessageCodesResolver getMessageCodesResolver() { return null; } }

我們來擴充套件default void addViewControllers(ViewControllerRegistry registry) { }這個檢視對映

1.建立一個配置類,使用@Configuration註解標明這是一個配置類

/**
 * @author:抱著魚睡覺的喵喵
 * @date:2020/12/18
 * @description:
 */
//使用WebMvcConfigurer介面擴充套件Spring MVC的功能
@Configuration
public class MyMVcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //向瀏覽器傳送/hao請求來到success
        registry.addViewController("/hao").setViewName("forward:success");
    }
}

這個registry.addViewController("/hao").setViewName(“forward:success”);相當於SpringMVC當中的<mvc:view-controller path="/hao" view-name=“success” >

2.建立Controller類

/**
 * @author:抱著魚睡覺的喵喵
 * @date:2020/12/18
 * @description:
 */
@Controller
public class HelloController {

    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("zsh","真棒!");
        return "success";
    }
}

3.編寫success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
<!--    th:text 將div裡面的內容設定為我們指定的值-->
    <div th:text="${zsh}"></div>
</body>
</html>

4.啟動主配置類訪問http://localhost:8080/hao
在這裡插入圖片描述