springboot项目整合jsp项目

前言:虽然 jsp 逐渐成为过去式,但是有些"需求"还是会要求使用jsp项目,下面就是springboot项目中整合jsp文件的过程。

一、添加依赖

pom.xml文件中导入依赖

xml 复制代码
<!-- JSP解析依赖-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
 
<!-- jstl 标准标签库 -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

二、修改配置文件

applicaiton.yml文件

xml 复制代码
spring:
    mvc:
        view:
            prefix: /WEB-INF/views   # 存放jsp文件的路径
            suffix: .jsp # 后缀

三、新建视图解析类

位置:/config/WebMvcConfig.java

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
* 在 WebMvcConfigurer 中配置视图解析器
* InternalResourceViewResolver是SpringMVC自带的一个视图解析器。
* setPrefix() 方法指定 JSP 文件所在的目录,
* setSuffix() 方法指定 JSP 文件的后缀名。
* 在使用 JSP 视图时,可以将视图名称设置为 JSP 文件名,例如 return "index",无需指定完整的 JSP 文件路径与后缀。
*/


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

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

}

四、新建web文件夹

位置:/src/main/web

新建文件夹后,在idea中添加web模块

第二步中的 \WEB-INF\web.xml 不需要自己创建,idea会帮助自动生成。

完成上述操作后,再在WEB-INF目录下新建views文件夹。

五、在views文件夹下新建index.jsp文件

java 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Jsp</title>
</head>
<body>
<h1>index.jsp</h1>
<h1>${msg}</h1>
</body>
</html>

六、编写测试类

java 复制代码
@Controller
public class HelloController {
    @GetMapping("/index")
    public String index(Model model){
        //参数1:将要用到jsp文件中的名字
        //参数2:查询到的内容或对象
        model.addAttribute( "msg","Hello world,springboot + jsp" );
        return "index";
    }
}
相关推荐
爬山算法7 分钟前
Maven(6)如何使用Maven进行项目构建?
java·maven
.生产的驴11 分钟前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
爱学的小涛18 分钟前
【NIO基础】基于 NIO 中的组件实现对文件的操作(文件编程),FileChannel 详解
java·开发语言·笔记·后端·nio
吹老师个人app编程教学19 分钟前
详解Java中的BIO、NIO、AIO
java·开发语言·nio
爱学的小涛20 分钟前
【NIO基础】NIO(非阻塞 I/O)和 IO(传统 I/O)的区别,以及 NIO 的三大组件详解
java·开发语言·笔记·后端·nio
北极无雪24 分钟前
Spring源码学习:SpringMVC(4)DispatcherServlet请求入口分析
java·开发语言·后端·学习·spring
琴智冰28 分钟前
SpringBoot
java·数据库·spring boot
binqian28 分钟前
【SpringSecurity】基本流程
java·spring
爱码少年30 分钟前
springboot工程中使用tcp协议
spring boot·后端·tcp/ip
《源码好优多》1 小时前
基于SpringBoot+Vue+Uniapp的植物园管理小程序系统(2024最新,源码+文档+远程部署+讲解视频等)
vue.js·spring boot·uni-app