欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot MVC 使用 JSP 作为模板

程序员文章站 2023-08-30 14:18:51
Spring Boot 默认使用 Thymeleaf 作为模板引擎,直接在 template 目录中存放 JSP 文件并不能正常访问,需要在 main 目录下新建一个文件夹来存放 JSP 文件,而且需要添加依赖。 1. 创建目录存放 JSP 文件 首先在 目录下新建一个 目录(任何名称都可以),然后 ......

spring boot 默认使用 thymeleaf 作为模板引擎,直接在 template 目录中存放 jsp 文件并不能正常访问,需要在 main 目录下新建一个文件夹来存放 jsp 文件,而且需要添加依赖。

1. 创建目录存放 jsp 文件

首先在 main 目录下新建一个 webapp 目录(任何名称都可以),然后在 project structure 中将它添加到 web resource directory。

Spring Boot MVC 使用 JSP 作为模板

2. 添加依赖

在 pom.xml 中添加依赖以支持 jstl 和 jsp:

<dependency>
    <groupid>javax.servlet</groupid>
    <artifactid>jstl</artifactid>
</dependency>
<dependency>
    <groupid>org.apache.tomcat.embed</groupid>
    <artifactid>tomcat-embed-jasper</artifactid>
</dependency>

3. mvc 配置

编辑 application.yml:

spring:
  mvc:
    view:
      suffix: .jsp
      prefix: /view/

设置前缀为 jsp 文件存放的相对路径(这里将 jsp 文件放在 view 目录),后缀为 .jsp

4. 编写控制器和页面

indexcontroller

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.servlet.modelandview;

@controller
public class indexcontroller {

    @requestmapping("/")
    public modelandview index() {
        modelandview index = new modelandview("index");
        index.addobject("message", "hello, spring boot!");
        return index;
    }
}

index.jsp:

<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>
<body>
<h1>spring boot with jsp</h1>
<h2>${message}</h2>
</body>
</html>

5. 访问页面

访问 http://localhost:8080/

Spring Boot MVC 使用 JSP 作为模板