Spring Boot实践——SpringMVC视图解析

一、注解说明

  在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) 
6. Mustache

JSP技术spring boot 官方是不推荐的,原因有三: 
1. 在tomcat上,jsp不能在嵌套的tomcat容器解析即不能在打包成可执行的jar的情况下解析 
2. Jetty 嵌套的容器不支持jsp 
3. Undertow

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

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2.定义一个模版后缀是ftp,注意是在classpath的templates目录下

3.在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");
    }
}

4.配置首页

/**
 * 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);
    }

}

5.访问 http://localhost:8088/springboot


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

1.首先,需要在你项目上加上webapp标准的web项目文件夹

2.配置jsp的前缀和后缀

参考头部 ‘注解说明’

3.在controller中返回视图

同freemaker的第三步

4.配置首页

同freemaker的第四步

5.访问 http://localhost:8088/springboot


注意

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

原文地址:https://www.cnblogs.com/OnlyCT/p/9563374.html

时间: 2024-08-10 09:38:53

Spring Boot实践——SpringMVC视图解析的相关文章

Spring MVC资源绑定视图解析器

ResourceBundleViewResolver使用属性文件中定义的视图bean来解析视图名称. 以下示例显示如何使用Spring Web MVC框架中的ResourceBundleViewResolver. ResourceBundleViewResolver-servlet.xml 配置如下所示 - <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <p

五年阿里摸爬滚打,写出这一份Spring boot实践文档

毋庸置疑,Spring Boot在众多从事Java微服务开发的程序员群体中是一个很特别的存在.说它特别是因为它确实简化了基于Spring技术栈的应用/微服务开发过程,使得我们能够很快速地就搭建起一个应用的脚手架并在其上进行项目的开发,再也不用像以前那样使用大量的XML或是注解了,应用在这样的约定优于配置的前提下可以以最快的速度创建出来. 今天就给大家分享五年阿里摸爬滚打,写出的这一份Spring boot实践文档 如果你需要的话可以点赞后[点击我]来获取到 基础应用开发(入门) 1.Spring

Spring Boot实践教程:开篇

前言 ??Java项目开发Spring应该是最常被用到的框架了,但是老式的配置方式让人觉得特别的繁琐,虽然可以通过注解去简化xml文件的配置,但是有没有更简单的方式来帮我们完成这些重复性的事情呢?于是Spring Boot就出现了,Spring Boot极大的简化了Spring的应用开发,它采用约定优于配置的方式,让开发人员能够快速的搭建起项目并运行起来. ??我们在项目开发的过程中,总免不了要整合各种框架,类似什么SSM.SSH之类的,这些框架的整合过程是繁琐的,同时又是无聊的,因为大部分情况

Spring Boot 启动源码解析系列六:执行启动方法一

1234567891011121314151617181920212223242526272829303132333435363738394041424344 public ConfigurableApplicationContext (String... args) { StopWatch stopWatch = new StopWatch(); // 开始执行,记录开始时间 stopWatch.start(); ConfigurableApplicationContext context =

spring boot 实践

二.实践 一些说明: 项目IDE采用Intellij(主要原因在于Intellij颜值完爆Eclipse,谁叫这是一个看脸的时代) 工程依赖管理采用个人比较熟悉的Maven(事实上SpringBoot与Groovy才是天生一对) 1.预览: (1)github地址 https://github.com/djmpink/springboot-mybatis git :  https://github.com/djmpink/springboot-mybatis.git (2)完整项目结构 (3)数

SpringMVC视图解析器 转

  前言 在前一篇博客中讲了SpringMVC的Controller控制器,在这篇博客中将接着介绍一下SpringMVC视 图解析器.当我们对SpringMVC控制的资源发起请求时,这些请求都会被SpringMVC的DispatcherServlet处理,接着 Spring会分析看哪一个HandlerMapping定义的所有请求映射中存在对该请求的最合理的映射.然后通过该HandlerMapping取得 其对应的Handler,接着再通过相应的HandlerAdapter处理该Handler.H

springmvc 之 SpringMVC视图解析器

当我们对SpringMVC控制的资源发起请求时,这些请求都会被SpringMVC的DispatcherServlet处理,接着Spring会分析看哪一个HandlerMapping定义的所有请求映射中存在对该请求的最合理的映射.然后通过该HandlerMapping取得其对应的Handler,接着再通过相应的HandlerAdapter处理该Handler.HandlerAdapter在对Handler进行处理之后会返回一个ModelAndView对象.在获得了ModelAndView对象之后,

Spring Boot 实践折腾记(五):自定义配置,扩展Spring MVC配置并使用fastjson

每日金句 专注和简单一直是我的秘诀之一.简单可能比复杂更难做到:你必须努力理清思路,从而使其变得简单.但最终这是值得的,因为一旦你做到了,便可以创造奇迹.--源自乔布斯 题记 前两天有点忙,没有连续更新,今天接着聊.金句里老乔的话说得多好,但能真正做到的人又有多少?至少就我个人而言,我还远远没有做到这样,只是一个在朝着这个方向努力的人,力求简明易懂,用大白话让人快速的明白理解,简单的例子上手,让使用的人更多的去实战使用扩展,折腾记即是对自己学习使用很好的一次总结,对看的人也是一个参考的方法,希望

Spring Boot实践教程(一):Hello,world!

??本篇会通过完成一个常用的Helloworld示例,来开始我们的Spring Boot旅程 准备工作 15分钟 开发环境 项目创建 ??项目创建的时候我们可以选择通过自定义配置Maven文件来创建,也可以用Spring官方提供的Spring Initializr工具,Spring Initializr是一个可以简化Spring Boot项目构建的工具,有两种使用Spring Initializr的方法: 官方提供的web页面工具,地址 开发工具集成的方式 ??两种方式操作的步骤是一样的,只不过