本节将讲述springboot中的视图解析。
1、环境约束
- win10 64位操作系统
- idea2018.1.5
- maven-3.0.5
- jdk-8u162-windows-x64
2、前提约束
- 完成springboot创建支持jsp项目 https://www.jianshu.com/p/b7ba5b42cdaa
注意,作者使用的springboot版本是2.1.8.RELEASE
2.1、方式一
- 在pom.xml中加入依赖以及resource:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
......
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/webapp</directory>
<includes>
<include>**/**</include>
</includes>
</resource>
</resources>
</build>
- 在application.properties中配置:
server.port=8089
spring.mvc.view.prefix=/WEB-INF/pages/
spring.mvc.view.suffix=.jsp
- 在项目/src/main/webapp下创建WEB-INF/pages文件夹
- 在项目/src/main/webapp/WEB-INF/pages下创建index.jsp
- 在主启动类同级目录下创建PageController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class PageController {
@RequestMapping("/toIndex")
public ModelAndView toIndex()
{
ModelAndView modelAndView = new ModelAndView("index");
return modelAndView;
}
}
- 启动测试,浏览器中访问http://localhost:8089/toIndex
2.2、方式二
- 在方式一的基础上,修改application.properties如下:
server.port=8089
- 在主启动类同级目录下创建WebAppConfigurer.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
- 启动测试,浏览器中访问http://localhost:8089/toIndex
以上就是springboot中视图解析器的两种配置方式。