使用Eclipse新建springboot项目要确保你的Eclipse安装了spingboot插件。
1.新建项目,选择Spring Starter Project.
2.点击next到以下页面,选择Template Engines目录下的Thymeleaf 和Web目录下的Web.
3.点击Finish完成项目的创建,得到的项目目录如下图所示。
- src/main/java 程序开发以及主程序入口
- src/main/resources 配置文件以及view层的显示页面文件
- src/test/java 测试程序
4.在src/main/java 目录下新建com.example.bean包,在该包下新建Person.java文件。
package com.example.bean;
public class Person {
private String name;
private Integer age;
public Person() {
super();
}
public Person(String name,Integer age) {
super();
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
5.打开com.example.demo包下的SpringbootTest2Application.java文件,添加代码如下图所示。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.bean.Person;
@Controller
@SpringBootApplication
public class SpringbootTest2Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootTest2Application.class, args);
}
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("userLogin")
public String userLogin(Model model) {
Person p=new Person("yxc",20);
model.addAttribute("user", p);
return "userLogin";
}
}
6.在src/main/resources 目录下的templates文件下新建index.html和userLogin.html.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p1> this is my first springboot project</p1>
<a href="/userLogin">west world</a>
</body>
</html>
userLogin.html
<html xmlns:th="http://www.thymeleaf.org">
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
welcome to west world
<span th:text="${user.name}"></span>
</body>
</html>
7.启动主程序,打开浏览器访问http://localhost:8080
点击west world ,可跳转到userLogin.html页面