SpringBoot使用jsp展示页面

一、通过Maven坐标集成jsp

JSP需要如下的三个依赖提供运行环境

内嵌的 tomcat容器,spring-boot-starter-web 包含了 spring-boot-starter-tomcat ,所以不需要再单独引入。
tomcat-embed-jasper 主要用来支持 JSP 的解析和运行。
jstl ,提供给Java Web开发人员一个标准通用的标签库。开发人员可以利用这些标签取代JSP页面上写Java代码,从而提高程序的可读性,降低程序的维护难度。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot 内置tomcat jsp支持 -->
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--jsp页面使用jstl标签-->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
</dependency>

二、配置JSP查找位置

我们需要通过配置告诉Spring Boot在进行页面渲染的时候,去哪里寻找JSP文件

spring:
 mvc:
   view:
     suffix: .jsp
     prefix: /WEB-INF/jsp/

debug: true

spring.mvc.view.prefix 指明 jsp 文件在 webapp 下的哪个目录
spring.mvc.view.suffix 指明 jsp 以什么样的后缀结尾。一定是/WEB-INF/下的目录,否则后面我们打包会报错。
目录结构如下:

使用上述配置,提示404,改为如下方法:

package com.dj.lunch;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
public class JspWebConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }
}

测试结果如下


源码地址
参考链接:https://www.kancloud.cn/hanxt/springboot2/1177618

posted @ 2021-02-04 14:06  离人怎挽_wdj  阅读(207)  评论(0编辑  收藏  举报