SpringBoot實踐——SpringMVC視圖解析

一、注解說明

在spring-boot+spring mvc 的項目中,有些時候我們需要自己配置一些項目的設置,就會涉及到這三個,那么,他們之間有什么關系呢?
首先,@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc注解等于擴展了WebMvcConfigurationSupport但是沒有重寫任何方法。

網(wǎng)站建設哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、微信小程序開發(fā)、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了石首免費建站歡迎大家使用!

所以有以下幾種使用方式:

  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版本已過時了,用官網(wǎng)說的新的類替換
 *
 */
@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容器解析即不能在打包成可執(zhí)行的jar的情況下解析
  2. Jetty 嵌套的容器不支持jsp
  3. Undertow

而其他的模版引擎spring boot 都支持,并默認會到classpath的templates里面查找模版引擎,這里假如我們使用freemarker模版引擎

  1. 現(xiàn)在pom.xml啟動freemarker模版引擎視圖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
  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版本已過時了,用官網(wǎng)說的新的類替換
 *
 */
@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視圖解析

注意

如果出現(xiàn)freemarker模版引擎和jsp技術同時存在的話,springmvc會根據(jù)解析器的優(yōu)先級來返回具體的視圖,默認,F(xiàn)reeMarkerViewResolver的優(yōu)先級大于InternalResourceViewResolver的優(yōu)先級,所以同時存在的話,會返回freemarker視圖
Spring Boot實踐——SpringMVC視圖解析

網(wǎng)頁題目:SpringBoot實踐——SpringMVC視圖解析
文章URL:http://bm7419.com/article22/jjchjc.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供用戶體驗、網(wǎng)站收錄Google、網(wǎng)站內鏈、網(wǎng)站設計、企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

外貿網(wǎng)站建設