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";
    }
}
相关推荐
止语Lab2 小时前
Go并发编程实战:Channel 还是 Mutex?一个场景驱动的选择框架
开发语言·后端·golang
小码哥_常2 小时前
Spring Boot一键限速:守护你的接口“高速路”
后端
HoneyMoose3 小时前
Jenkins Cloudflare 部署提示错误
java·servlet·jenkins
阿丰资源3 小时前
基于SpringBoot的物流信息管理系统设计与实现(附资料)
java·spring boot·后端
Predestination王瀞潞3 小时前
Java EE3-我独自整合(第四章:Spring bean标签的常见配置)
java·spring·java-ee
overmind3 小时前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python
资深数据库专家3 小时前
总账EBS 应用服务器1 的监控分析
java·网络·数据库
房开民3 小时前
可变参数模板
java·开发语言·算法
t***5443 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
_深海凉_3 小时前
LeetCode热题100-最小栈
java·数据结构·leetcode