SpringBoot--5.整合JSP
程序员文章站
2022-05-26 09:53:44
...
SpringBoot本身内置的Tomcat并不支持JSP,新建一个Maven工程,注意打包类型一定要选择为war,否则访问不了JSP页面。
pom文件中需要引入如下的依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- SpringBoot web 核心组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!-- SpringBoot 外部tomcat支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
</dependencies>
目录结构如下:
因为没有web.xml文件,所以提示有错误,但这个没关系。在src/main/java目录下新建
Application.java:
package com.springBoot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(Application.class, args);
}
}
JSPController.java:
package com.springBoot.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class JSPController {
@RequestMapping("/Index")
public String JSPIndex(){
return "Index";
}
}
在src/main/resources目录下建如下配置文件:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
根据该配置文件,需要在src目录下建如下结构,其中webapp是系统建好的:
Index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Hi,Mr YOUNG!
</body>
</html>```
然后点击运行Application.java,结果如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191002162810238.png)