搭建不带JSP的项目
- POM中引入parent和web依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
- 在resource文件夹中创建application.yml(或者properties)文件,加入配置server.port=8090
- 编写启动类
@SpringBootApplication
public class Chapter1Application {
public static void main(String[] args) {
SpringApplication.run(Chapter1Application.class);
}
}
- 编写Controller
@RestController
public class IndexController {
@RequestMapping("/index")
public Object index() {
return "success";
}
}
- 搞定,访问http://localhost:8090/index
搭建带有JSP的项目
- 在上面依赖基础上加入tomcat-embed-jasper(内置tomcat时必须加入,详情看另一篇SpringBoot中使用JSP的坑)
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
- 在resource文件夹中创建application.yml(或者properties)文件,除了加入配置server.port=8090外,还需要加入springmvc视图解析的前、后缀配置:
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
- 编写启动类和上面一致
- 编写Controller时注意注解不能用RestController,因为默认会把String当做Json进行转换,而得不到jsp的后缀,导致不会让JspServlet进行解析,所以用Controller注解就可以了
- 访问同上面一样
- 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>Spring boot 视图解析器</title>
</head>
<body>
<h1>测试视图解析器</h1>
</body>
</html>