Spring Boot实践——SpringMVC视图解析
admin
2023-01-25 01:40:03
0

一、注解说明

  在spring-boot+spring mvc 的项目中,有些时候我们需要自己配置一些项目的设置,就会涉及到这三个,那么,他们之间有什么关系呢?
首先,@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc注解等于扩展了WebMvcConfigurationSupport但是没有重写任何方法。

所以有以下几种使用方式:

  1. @EnableWebMvc+extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置
  2. extends WebMvcConfigurationSupport,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置
  3. extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式依旧使用springboot的@EnableAutoConfiguration中的设置

具体哪种方法适合,看个人对于项目的需求和要把控的程度

在WebMvcConfigurationSupport(@EnableWebMvc)和@EnableAutoConfiguration这两种方式都有一些默认的设定
而WebMvcConfigurationAdapter则是一个abstract class

具体如何类内如何进行个性化的设置,可以参考以下文章:

Spring Boot:定制HTTP消息转换器
EnableWebMvc官方文档

  • 使用 @EnableWebMvc 注解,需要以编程的方式指定视图文件相关配置
/**
 * Web MVC 配置适配器
 * @ClassName: WebAppConfigurer 
 * @Description: 
 * @author OnlyMate
 * @Date 2018年8月28日 下午2:39:31  
 * 
 * WebAppConfigurer extends WebMvcConfigurerAdapter 在Spring Boot2.0版本已过时了,用官网说的新的类替换
 *
 */
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {

    /**
     * springmvc视图解析
     * @Title: viewResolver 
     * @Description: TODO
     * @Date 2018年8月28日 下午4:46:07 
     * @author OnlyMate
     * @return
     */
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        // viewResolver.setViewClass(JstlView.class); // 这个属性通常并不需要手动配置,高版本的Spring会自动检测
        return viewResolver;
    }

    /**
     * SpringBoot设置首页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        WebMvcConfigurer.super.addViewControllers(registry);
        registry.addViewController("/").setViewName("index");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

}
  • 使用 @EnableAutoConfiguration 注解,会读取 application.properties 或 application.yml 文件中的配置

视图

## 视图
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

spring:
    http:
        encoding:
            charset: UTF-8
            enabled: true
            force: true
    messages:
        encoding: UTF-8
    profiles:
        active: dev
    mvc:
        view:
            prefix: /WEB-INF/views/
            suffix: .jsp

二、模版引擎

  Spring boot 在springmvc的视图解析器方面就默认集成了ContentNegotiatingViewResolver和BeanNameViewResolver,在视图引擎上就已经集成自动配置的模版引擎,如下:

  1. FreeMarker
  2. Groovy
  3. Thymeleaf
  4. Velocity (deprecated in 1.4)
  5. Mustache

JSP技术spring boot 官方是不推荐的,原因有三:

  1. 在tomcat上,jsp不能在嵌套的tomcat容器解析即不能在打包成可执行的jar的情况下解析
  2. Jetty 嵌套的容器不支持jsp
  3. Undertow

而其他的模版引擎spring boot 都支持,并默认会到classpath的templates里面查找模版引擎,这里假如我们使用freemarker模版引擎

  1. 现在pom.xml启动freemarker模版引擎视图

    org.springframework.boot
    spring-boot-starter-freemarker
  1. 定义一个模版后缀是ftp,注意是在classpath的templates目录下
    Spring Boot实践——SpringMVC视图解析

  2. 在controller上返回视图路径
@Controller
public class HelloWorldController {
    private Logger logger = LoggerFactory.getLogger(HelloWorldController.class);

    @Value("${question}")
    private String question;
    @Value("${answer}")
    private String answer;
    @Value("${content}")
    private String content;

    @ResponseBody
    @RequestMapping("/hello")
    public String index() {
        return "hello world";
    }

    @ResponseBody
    @RequestMapping(value="/hello1")
    public String index1() {
        return question + answer;
    }

    @ResponseBody
    @RequestMapping(value="/hello2")
    public String index2() {
        return content;
    }

    @RequestMapping(value="/hello3")
    public String index3(Model model) {
        try {
            model.addAttribute("question", question);
            model.addAttribute("answer", answer);
        } catch (Exception e) {
            logger.info("HelloWorldController ==> index3 method: error", e);
        }
        return "/hello";
    }
}

如果使用@RestController,默认就会在每个方法上加上@Responsebody,方法返回值会直接被httpmessageconverter转化,如果想直接返回视图,需要直接指定modelAndView。

public class HelloWorldController{
    private Logger logger = LoggerFactory.getLogger(HelloWorldController.class);

    @Value("${question}")
    private String question;
    @Value("${answer}")
    private String answer;
    @Value("${content}")
    private String content;

    @RequestMapping("/hello3")
    public ModelAndView hello3() {
        try {
        model.addAttribute("question", question);
        model.addAttribute("answer", answer);
    } catch (Exception e) {
        logger.info("HelloWorldController ==> index3 method: error", e);
    }
        return new ModelAndView("hello");
    }
}
  1. 配置首页
/**
 * Web MVC 配置适配器
 * @ClassName: WebAppConfigurer 
 * @Description: 
 * @author OnlyMate
 * @Date 2018年8月28日 下午2:39:31  
 * 
 * WebAppConfigurer extends WebMvcConfigurerAdapter 在Spring Boot2.0版本已过时了,用官网说的新的类替换
 *
 */
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {/**
     * SpringBoot设置首页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        WebMvcConfigurer.super.addViewControllers(registry);
        registry.addViewController("/").setViewName("index");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

}
  1. 访问 http://localhost:8088/springboot
    Spring Boot实践——SpringMVC视图解析
    Spring Boot实践——SpringMVC视图解析

虽然,jsp技术,spring boot 官方不推荐,但考虑到是常用的技术,这里也来集成下jsp技术

  1. 首先,需要在你项目上加上webapp标准的web项目文件夹
    Spring Boot实践——SpringMVC视图解析
  2. 配置jsp的前缀和后缀
    参考头部 ‘注解说明’
  3. 在controller中返回视图
    同freemaker的第三步

  4. 配置首页
    同freemaker的第四步

  5. 访问 http://localhost:8088/springboot
    Spring Boot实践——SpringMVC视图解析
    Spring Boot实践——SpringMVC视图解析

注意

  如果出现freemarker模版引擎和jsp技术同时存在的话,springmvc会根据解析器的优先级来返回具体的视图,默认,FreeMarkerViewResolver的优先级大于InternalResourceViewResolver的优先级,所以同时存在的话,会返回freemarker视图
Spring Boot实践——SpringMVC视图解析

相关内容

热门资讯

德国总理:美国正在被伊朗羞辱 德国之声4月27日报道,德国总理默茨在访问一所学校时表示,在当前的持续冲突中,伊朗领导层正试图羞辱美...
理响中国|“长”歌以行,风云激... 光阴如梭,东方潮阔。这里是中国的长三角,世界的长三角。无论过去、现在还是未来,这片土地都因时代而生,...
白宫:特朗普及其国安团队开会讨... 新华社华盛顿4月27日电 美国白宫新闻秘书莱维特27日在记者会上证实,总统特朗普及其国家安全团队当天...
人民日报刊文:日本放开杀伤性武... 日本放开杀伤性武器出口推高地缘冲突风险(国际论坛)常思纯《人民日报》(2026年04月28日 第 0...
医疗保障法草案二审:明确生育保... 满足多样化健康保障需求本报记者 彭 波4月27日,医疗保障法草案二审稿提请十四届全国人大常委会第二十...
天津一景区发生自转旋翼机事故1... 澎湃新闻记者 吕新文中国民用航空华北地区管理局4月22日公布《豪客通航“10•1”天津长芦汉盐旅游区...
卡塔尔埃米尔与美国总统特朗普通... 当地时间24日,卡塔尔埃米尔塔米姆与美国总统特朗普通电话,重点就中东地区局势以及伊朗与美国谈判问题交...
男子30年前被扣押2859克黄... 澎湃新闻记者 王鑫家住辽宁省大连市的潘永嘉近日向澎湃新闻反映称,三十年前,他在大连周水子机场被盖州市...
商务部:取消反制欧盟两家金融机... 中华人民共和国商务部令二〇二六年 第1号鉴于欧盟已取消对中国两家金融机构的制裁措施,现公布《关于取消...
过去24小时共有5艘船只通过霍... 总台记者当地时间24日获悉,过去24小时内,共有5艘船只通过霍尔木兹海峡,其中包括一艘伊朗油轮。(总...