springboot支持jsp的实现

刚开始使用springboot就发现它对JSP的支持不是很友好,springboot默认支持的视图是Thymeleaf,而作为一个java开发人员,我更习惯使用的是JSP,于是上网搜查了一些资料,最后整理记录一下。

创建springboot项目已有讲解,在这里不做赘述。重点整理springboot是如何支持jsp的。

首先添加jsp的maven依赖

<dependency>
	<groupId>org.apache.tomcat.embed</groupId>
	<artifactId>tomcat-embed-jasper</artifactId>
	<!--<scope>provided</scope>-->
</dependency>
<!-- servlet依赖. -->
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<scope>provided</scope>
</dependency>

如果要在jsp中使用jstl来处理页面逻辑的话,还需要引入对jstl的依赖(一般情况是不可缺少的)

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
</dependency>

新建目录结构存放jsp页面(根据编码习惯创建目录结构如下图所示)这时候如果新建jsp,是没有模板的:


然后要在Project Structure中指定webapp为web目录(未指定之前,在jsp下新建jsp文件找不到jsp模板)


在jsp文件夹下创建index.jsp页面,这时候JSP模板就出来了。


<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/5/21
  Time: 15:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    测试jsp
</body>
</html>

然后在application.properties中配置jsp的前缀和后缀

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

写一个controller测试类MainController.java

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

启动项目,进入http://localhost:8080/main/index,结果如下,则说明我们已经完成了springboot对jsp的支持。


猜你喜欢

转载自blog.csdn.net/qq_23543983/article/details/80392625