1.创建pojo类,实现对象的封装
package com.ws.domain;
public class User {
private Integer userid;
private String username;
private Integer userage;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserage() {
return userage;
}
public void setUserage(Integer userage) {
this.userage = userage;
}
public User(Integer userid, String username, Integer userage) {
super();
this.userid = userid;
this.username = username;
this.userage = userage;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
}
2.pom引入starter和freemarker坐标
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.release</version>
</parent>
<groupId>com.ws</groupId>
<artifactId>springboot-freemarker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.7</java.version>
</properties>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- freemarker启动器的坐标 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
</project>
3.创建controller,将list放入到model中;
package com.ws.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ws.domain.Users;
/**
* SpringBoot整合jsp
*
*
*/
@Controller
public class UserController {
/*
* 处理请求,产生数据
*/
@RequestMapping("/showUser")
public String showUser(Model model){
List<Users> list = new ArrayList<>();
list.add(new Users(1,"张三",20));
list.add(new Users(2,"李四",22));
list.add(new Users(3,"王五",24));
//需要一个Model对象
model.addAttribute("list", list);
//跳转视图
return "userList";
}
}
4.在resources目录下创建templates文件夹,创建userList.ftl文件,然后遍历循环
<html>
<head>
<title>展示用户数据</title>
<meta charset="utf-8"></meta>
</head>
<body>
<table border="1" align="center" width="50%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<#list list as user >
<tr>
<td>${user.userid}</td>
<td>${user.username}</td>
<td>${user.userage}</td>
</tr>
</#list>
</table>
</body>
</html>
5.添加启动类,实现项目的启动
package com.ws;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SpringBoot启动类
*
*
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}