1. 项目创建
下面这里只选择thymeleaf 选项就行,会自动集成其他运行jar包
2 .根据上面创建的项目结构,下面的1 2 3 均为自动生成,2为springboot启动类,非常重要,3为静态文件js html存放目录,页面
文件框架默认放在templates下面,js放在static下面
3. 代码实例
主类SpringbootPractiseApplication:右键直接run或debug, 运行main方法
package com.lm.practise;
import java.util.ArrayList;
import java.util.List;
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;
@Controller
@RequestMapping("lm")
@SpringBootApplication
public class SpringbootPractiseApplication {
/**
* springboot启动主方法
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(SpringbootPractiseApplication.class, args);
}
/**
* 跳转页面 传数据方法
* @param model
* @return
*/
@RequestMapping("/index")
public String index(Model model) {
Person obj = new Person("张三",25);
List<Person> list = new ArrayList<>();
Person p1 = new Person("aa",15);
Person p2 = new Person("bb",16);
Person p3 = new Person("cc",17);
Person p4 = new Person("dd",18);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
model.addAttribute("person",obj);
model.addAttribute("list",list);
// 返回 index.html页面
return "index";
}
}
实体类Person:
package com.lm.practise;
/**
* 描述:实体类
*
* @author
* @create_time
*/
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
页面,index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<!--单个取值-->
<div>
姓名:<span th:text="${person.name}"></span><br/>
年龄:<span th:text="${person.age}"></span>
</div>
<br/>
<br/>
***************************************
<!--list取值-->
<div th:each="person:${list}">
姓名:<span th:text="${person.name}"></span><br/>
年龄:<span th:text="${person.age}"></span><br/>
------------------------------------
</div>
</body>
<script th:inline="javascript">
var person = [[${person}]];
console.log(person.name + "/" + person.age);
</script>
</html>
运行结果:
至此,上面已经完成了一个完整的实例, 包括单个对象的取值, 对象集合list的取值,js 获取服务器传过来的值。
实践中一路遇坑,所以开发过程中需要注意以下几个问题:
1. controller中一定要用 @Controller 注解,而不能用 @RestController (@RestController相当于@Controller和@ResponseBody一起用,返回的是json数据,而不是页面)
2. idea工具创建的html页面 <meta> <br> 标签是没有闭合标签的,执行会报错,必须每个标签都闭合 <meta></meta> </br>
3. 在页面需要使用thymeleaf标签 th:... ,需要手动在html中引入thymeleaf的命名空间 <html lang="en" xmlns:th="http://www.thymeleaf.org">
以上,有问题请即时指正!!