spring boot 使用视图modelandview
生活随笔
收集整理的這篇文章主要介紹了
spring boot 使用视图modelandview
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1:springboot使用視圖解析器,添加依賴
<!-- freemarker模板引擎視圖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><!-- 熱部署,不用重啟 ,這個(gè)在這里不需要--><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:主函數(shù)需要繼承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頁(yè)面必須繼承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等就會(huì)先找視圖解析器
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/demousername: rootpassword: 1367356mvc:view:prefix: /WEB-INF/suffix: .jspmybatis:config-location: classpath:mybatis-config.xml4: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;//這個(gè)注解不能使用RestController,不然會(huì)返回模板類型的頁(yè)面 @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);//設(shè)置返回的數(shù)據(jù)為json類型,也可以不設(shè)置,返回對(duì)象//mv.setView(new MappingJackson2JsonView());return mv;}@RequestMapping("index")public String index(){return "index";}}5:測(cè)試成功:
6:目錄結(jié)構(gòu)
總結(jié)
以上是生活随笔為你收集整理的spring boot 使用视图modelandview的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 对外汉语偏误语料库_BCC语料库
- 下一篇: jenkins执行bat失败_关于批处理