Spring Boot 拓展SpringMVC

时间:2022-07-22
本文章向大家介绍Spring Boot 拓展SpringMVC,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

自定义配置MVC类

我们自定义使用 Configuration 注解实现了一个配置类,并实现了 WebMvcConfigurer 接口

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {  // 实现接口

}

实现自定义一个视图解析器

//自定义了一个视图解析器
public static class MyViewResolver implements ViewResolver {
    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        return null;
    }
}

将视图解析器绑定到spring

//将视图解析器拓展至spring
@Bean
public ViewResolver myViewResolver(){
    return new MyViewResolver();
}

全部代码如下

config > MyMvcConfig.java

package com.b5ck.config;


//拓展SpringMvc

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {  // 实现接口
    //ViewResolver 实现了视图解析器的接口,我们就可以把它看作为视图解析器


    //将视图解析器拓展至spring
    @Bean
    public ViewResolver myViewResolver(){
        return new MyViewResolver();
    }

    //自定义了一个视图解析器
    public static class MyViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception {
            return null;
        }
    }
}

自定义控制器

使 Configuration 注解,配置一个视图控制器

//如果我们要拓展SpringMvc,官方建议我们这样去配置
@Configuration
public class ExtendMvcConfig implements WebMvcConfigurer {
    // 视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //添加一个视图解析器
        registry.addViewController("/b5ck").setViewName("hello");
    }
}

这时我们访问 /b5ck 就会自动解析 hello.html 页面

验证