创建工程
file -> new project
选择你的JDK版本,最好是Java1.8,点击next
调整Java版本,选择构建Maven项目,next
选择需要的起始依赖,spring-boot会帮你自动添加和下载依赖(Maven),我在这只选了web和Thymeleaf,web会提供tomcat支持和SpringMVC,Thymeleaf则提供视图的模板引擎。不建议使用jsp。next。
确定项目名称和项目位置,Finish。
项目结构
生成的项目结构如下图所示:
目录结构与maven项目一样,不过自动生成了一个DemoApplication类,这个类是项目的引导程序,启动这个类中的main方法即可启动spring-boot项目。
Controller
在生成的目录下建立controller包,存放Controller。
建立entity包,存放Person实体类。
PersonListController
package com.example.demo.controller;
import com.example.demo.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zdxie
* @Date 下午 10:49 2017/9/19 0019
* @Description
*/
@Controller
@RequestMapping("/person")
public class PersonListController {
//模拟人员
List<Person> personList = new ArrayList<Person>();
//列表和新增表单页面
@RequestMapping("/index")
public String index(Model model){
model.addAttribute("personList",personList);
return "index";
}
//新增操作
@RequestMapping("/add")
public String add(Person person){
personList.add(person);
return "redirect:/person/index";
}
}
Person
package com.example.demo.entity;
/**
* @author zdxie
* @Date 下午 10:55 2017/9/19 0019
* @Description
*/
public class Person {
public Person(int age, String name, String gender, String schoolName) {
this.age = age;
this.name = name;
this.gender = gender;
this.schoolName = schoolName;
}
public Person(){}
private int age;
private String name;
private String gender;
private String schoolName;
//省略getter和setter
}
Thymeleaf模板
模板放在src/main/resource/templates下
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>人员列表</title>
<!--引用static下的css文件-->
<link th:href="@{/index.css}" rel="stylesheet"></link>
</head>
<body>
<!--判断人员列表是否为空-->
<table th:unless="${#lists.isEmpty(personList)}">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>毕业学校</th>
</tr>
<!--循环遍历人员列表-->
<tr th:each="person : ${personList}">
<td th:text="${person.name}"></td>
<td th:text="${person.age}"></td>
<td th:text="${person.gender}"></td>
<td th:text="${person.schoolName}"></td>
</tr>
</table>
<div class="msg" th:if="${#lists.isEmpty(personList)}">暂时没有人员信息!</div>
<form method="POST" action="/person/add">
<input name="name" id="name" type="text" placeholder="姓名"/><br/>
<input name="age" id="age" type="text" placeholder="年龄"/><br/>
<input name="gender" id="gender" type="text" placeholder="性别"/><br/>
<input name="schoolName" id="schoolName" type="text" placeholder="毕业学校"/><br/>
<input type="submit" value="新增+"/>
</form>
</body>
</html>
css,js等资源文件放在src/main/resource/static目录下
启动spring-boot项目
访问及效果
接下来访问
http://localhost:8080/person/index
效果: