SpringBoot使用ModelAndView時配置視圖解析器


spring boot 使用視圖modelandview

原文:https://www.cnblogs.com/liyafei/p/7955943.html

 

 

 1:springboot使用視圖解析器,添加依賴

復制代碼
        <!-- freemarker模板引擎視圖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!-- 熱部署,不用重啟 ,這個在這里不需要--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!-- jsp解析器 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency>
復制代碼

2:主函數需要繼承SpringBootServletInitializer,並覆蓋其方法。

 

復制代碼
package com.liyafei; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @EnableAutoConfiguration @SpringBootApplication //返回jsp頁面必須繼承SpringBootServletInitializer類重寫里面的方法 public class Main extends SpringBootServletInitializer{ public static void main(String[] args) { SpringApplication.run(Main.class, args); } protected SpringApplicationBuilder config(SpringApplicationBuilder applicationBuilder){ return applicationBuilder.sources(Main.class); } }
復制代碼

3:配置文件中添加spring.mvc.view配置,配置了視圖解析器之后,controlller返回的String,View等就會先找視圖解析器

復制代碼
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo
    username: root
    password: 1367356
 mvc: view: prefix: /WEB-INF/ suffix: .jsp mybatis: config-location: classpath:mybatis-config.xml
復制代碼


4:controller映射

  

復制代碼
package com.liyafei.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import com.liyafei.pojo.User; //這個注解不能使用RestController,不然會返回模板類型的頁面 @Controller public class MyController { User user=new User(); @RequestMapping("/my") public ModelAndView test(){ ModelAndView mv=new ModelAndView(); mv.setViewName("modelandview"); mv.addObject("name", "liyafei"); user.setAge(20); user.setName("wangwu"); mv.addObject("user", user); //設置返回的數據為json類型,也可以不設置,返回對象 //mv.setView(new MappingJackson2JsonView()); return mv; } @RequestMapping("index") public String index(){ return "index"; } 

 

}
復制代碼

5:測試成功:

  

 

 

6:目錄結構


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM