当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot MVC 使用 JSP 作为模板

Spring Boot MVC 使用 JSP 作为模板

2019年11月03日  | 移动技术网IT编程  | 我要评论

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

1. 创建目录存放 jsp 文件

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

project-structure

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://www.lhsxpumps.com/_localhost:8080/

mvc-demo

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网