欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用Spring Boot和JSP创建Web项目指南

最编程 2024-08-11 08:28:46
...

1. 背景

Spring Boot目前开发Web应用这块,使用Restful风格做前后端分离实现的应该是主流了。不过也有很多朋友们使用模板引擎,常用的如Jsp/ Thymeleaf/ Freemarker。


注意Spring Boot官方已经不推荐使用JSP了,确实操作起来也比较麻烦,但是由于JSP用户体量还是比较大的,所以还是简单演示下。


2. 修改pom.xml引入JSP依赖

添加依赖项,开启SpringBoot对Web项目及JSP的支持


 <!-- 添加web开发功能 -->

 <dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-web</artifactId>

 </dependency>

 <!--内嵌的tomcat支持模块 -->

 <dependency>

  <groupId>org.apache.tomcat.embed</groupId>

  <artifactId>tomcat-embed-jasper</artifactId>

  <scope>provided</scope>

 </dependency>

 <!-- 对jstl的支持 -->

 <dependency>

  <groupId>javax.servlet</groupId>

  <artifactId>jstl</artifactId>

 </dependency>


3. 添加webapp目录存放JSP文件

手工添加src/main/webapp及子目录如下,同时目录下放一个index.jsp用于测试。注意该目录是一个Source Folder源代码目录,不是普通文件夹目录。


如下图:

网络异常,图片无法展示
|

4. 注册视图解析器

在配置类内添加视图解析器


@SpringBootApplication

public class SpringbootTemplatedemoApplication {

public static void main(String[] args) {

 SpringApplication.run(SpringbootTemplatedemoApplication.class, args);

}

@Bean//注册视图解析器

public InternalResourceViewResolver setupViewResolver() {

 InternalResourceViewResolver resolver = new InternalResourceViewResolver();

 resolver.setPrefix("/WEB-INF/jsp/");//自动添加前缀

 resolver.setSuffix(".jsp");//自动添加后缀

 return resolver;

}

}


5. 创建一个控制器

创建控制器,用于跳转到index.jsp页面


@Controller

public class JspController {

@RequestMapping("/jsp") // 访问路径

public String jsp(Model model) {

 model.addAttribute("name", "猫哥");//携带属性值

 return "index";//跳转页面

}


6. 创建网页

创建index.jsp页面,取出后端穿过来的属性值


<%@ page language="java" contentType="text/html; charset=UTF-8"

   pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

${name}

</body>

</html>


7. 测试

直接访问http://127.0.0.1:1004/jsp,即可输出网页,完成!

推荐阅读