1.新建springboot项目,选择以war包的方式package;
2.勾选Web模块,DevTools可不选(用作热部署,不影响运行)
3.创建完成后,项目结构如下图:
4.pom.xml文件中添加jsp的依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
5.在application.properties文件中添加以下内容:
#路径,在webapp文件夹下新建文件夹WEB-INF,在往下建文件夹jsp
spring.mvc.view.prefix=/WEB-INF/jsp/
#文件名的后缀,例如:index.jsp,放在jsp文件夹下
spring.mvc.view.suffix=.jsp
6.新建index.jsp文件,路径结构如图:
7.index.jsp页面内容如下:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>登录</title>
<link rel="stylesheet" href="<%=request.getContextPath() %>/css/signin.css">
<link rel="stylesheet" href="<%=request.getContextPath() %>/css/bootstrap.min.css">
<style type="text/css">
body {
padding-top: 50px;
}
.starter-template {
padding: 40px 15px;
text-align: center;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Spring Boot+JSP</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="starter-template">
<h2>登录</h2>
<form class="form-signin" role="form" name="form" action="/login" method="post">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" value="" placeholder="用户名"/>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" placeholder="密码"/>
</div>
<input type="submit" id="login" value="Login" class="btn btn-primary"/>
</form>
</div>
</div>
</body>
</html>
8.引入css文件,这个不影响效果,只是index.jsp的页面会不好看
9.新建IndexController.java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
10.启动服务,访问localhost:8080/index 即可访问index.jsp成功