zl程序教程

您现在的位置是:首页 >  后端

当前栏目

SpringBoot整合JSP

SpringBootJSP 整合
2023-06-13 09:11:46 时间

大家好,又见面了,我是你们的朋友全栈君。

以下整合jsp使用的开发工具为intellij idea。其他开发工具目录结构相同

在pom.xml文件中加入注释部分的依赖

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 添加servlet依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <!-- 添加jstl标签库依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!--添加tomcat依赖模块.-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

    </dependencies>

其中最主要的,提供jsp引擎的就是

tomcat-embed-jasper这个依赖(一定要加)

然后修改配置文件中的Jsp文件访问路径(视图解析)

在application.properties文件中加入

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

配置完成后在webapp/WEB-INF/jsp文件夹下放jsp文件(必须有webapp/WEB-INF这个包,否则访问不到)

下面是我的项目目录

最后再建立一个控制器进行访问

@Controller
public class IndexController {
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}

访问结果如下,成功显示jsp页面

解决在Intellij Idea项目中无法新建jsp文件问题

点击File-Project Structrue,选择Modules,展开项目下的web,如下图

点击右下的+号,在弹出的窗口指定你的项目资源路径,这里直接点确定就好了

保存退出,现在可以在项目中的任何一个地方建jsp文件了

搜索公众号”源码宇宙“,回复”面试题“获取,关注获取最新面试与软件资料。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/141903.html原文链接:https://javaforall.cn