SpringBoot如何支持Jsp

1、创建SpringBoot项目

2、添加相关的依赖

<packaging>war</packaging>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- 用于编译jsp springboot tomcat jsp 支持开启-->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>

    <!--jstl的支持,c标签-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <scope>compile</scope>
    </dependency>

</dependencies>

<build>
    <resources>
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>**/**</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

3、在application.yml中添加配置

server:
  port: 9999
  servlet:
    encoding:
      charset: UTF-8

# 视图配置
spring:
  mvc:
    view:
      prefix: /WEB-INF/
      suffix: .jsp

在resources文件夹的static文件夹,里面都是用来放js,css等静态文件

4、在main文件夹下创建webapp文件夹,然后在webapp下创建WEB-INF文件夹,以后的jsp文件就放在WEB-INF下面

5、(重点)选中项目,然后点击鼠标右键选择Open Module Settings项目属性配置画面

6、然后点击Modules,找到web选项。

如果没有web,就点击左上角的"+",创建一下

7、点击右边的"-",这是Spring boot项目,不需要web.xml文件,直接删除即可。(如果没有就不要管,跳过)

8、点击中间的+号,(如果有就先-掉,或者修改)点击+号后选中webapp的路径(main下的webapp路径),这一步多说一下,这一步是指向jsp文件的根目录,这一步设置之后你点击webapp文件夹右键创建的时候才会在上面出现jsp的创建选项

9、直接点击右下角Create Artifact,然后点击右下键的Apply就可以

10、在WEB-INF下面创建hello.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hello world</title>
    <link href="/hello.css" rel="stylesheet" type="text/css">
    <script src="/hello.js" type="application/javascript"></script>
</head>
<body>
<h4>欢迎您使用JSP</h4>
<img src="/hello.png"/>
</body>
</html>

hello.css、hello.js、hello.png在static目录下:

11、创建TestBean.java文件,配置简单的访问方法。

@Controller
@RequestMapping("/test")
public class TestBean {

    @RequestMapping("/hello2")
    public String test(){
        return "hello";
    }
}

12、项目启动配置,运行后访问http://127.0.0.1:9999/test/hello2:

 

posted @ 2022-04-30 18:35  残城碎梦  阅读(140)  评论(0编辑  收藏  举报