一、前言
在完成之前的环境配置下,现在来继续学习spring-boot中对web的支持,并用RESTful API风格
二、了解相关注解说明
之前做spring-mvc的开发时候经常使用@Controller、@RestController、@RequestMapping 这三种注解。
@Controller: 修饰class,用来处理Http的请求,可以返回数据和视图
@RestController:Spring4之后加入的注解,原来在@Controller中返回json需要 @ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再 配置 @ResponseBody,默认返回json格式。
@RequestMapping:配置url映射
三、使用RESTful创建web控制器
用户实体设计:
package org.hjc.demo.reset.entity;
public class User {
private Long id;
private String name;
private Integer age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
}
用户控制器:
package org.hjc.demo.reset.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hjc.demo.reset.entity.User;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @project name : demo
* @author name : hanjincheng
* @create time : 2017-6-29 上午9:05:21
* @class name : org.hjc.demo.reset.controller.UserController
* @class comments: (用户信息控制器)
* @modify list : (modify by :modify date:modify content)
*
*/
@RestController
@RequestMapping(value="/users")
public class UserController {
//创建一个线程安全的Map集合
static Map<Long,User> userMap = Collections.synchronizedMap(new HashMap<Long,User>());
@RequestMapping("/index")
public ModelAndView index(){
ModelAndView mv = new ModelAndView();
// 加入一个属性,用来在模板中读取
User user1 = new User(1L,"张三",18);
userMap.put(1L, user1);
User user2 = new User(2L,"李四",20);
userMap.put(2L, user2);
mv.addObject("users", userMap.values());
mv.setViewName("index/index1");
return mv;
}
/**
*
* @author name : hanjincheng
* @create time : 2017-6-29 上午8:56:59
* @method comments: (所有用户信息)
* @modify list : (modify by :modify date:modify content)
* @return
* @throws
*/
@RequestMapping(path="/",method=RequestMethod.GET)
public List<User> getUserList(){
List<User> r = new ArrayList<User>(userMap.values());
return r;
}
/**
*
* @author name : hanjincheng
* @create time : 2017-6-29 上午8:58:32
* @method comments: 获取一个用户信息)
* @modify list : (modify by :modify date:modify content)
* @param id
* @return
* @throws
*/
@RequestMapping(path="/{id}",method=RequestMethod.GET)
public User getUserById(@PathVariable Long id){
return userMap.get(id);
}
/**
*
* @author name : hanjincheng
* @create time : 2017-6-29 上午9:01:32
* @method comments: (保存用户信息)
* @modify list : (modify by :modify date:modify content)
* @param user
* @return
* @throws
*/
@RequestMapping(path="/",method=RequestMethod.POST)
public String saveUser(@ModelAttribute User user){
userMap.put(user.getId(), user);
return "success";
}
/**
*
* @author name : hanjincheng
* @create time : 2017-6-29 上午9:03:30
* @method comments: (更新用户信息)
* @modify list : (modify by :modify date:modify content)
* @param id
* @param user
* @return
* @throws
*/
@RequestMapping(path="/{id}",method=RequestMethod.PUT)
public String updateUser(@PathVariable Long id,@ModelAttribute User user){
// 处理"/users/{id}"的PUT请求,用来更新User信息
User u = userMap.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
userMap.put(id, u);
return "success";
}
/**
*
* @author name : hanjincheng
* @create time : 2017-6-29 上午9:04:58
* @method comments: (删除用户信息)
* @modify list : (modify by :modify date:modify content)
* @param id
* @return
* @throws
*/
@RequestMapping(path="/{id}",method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id){
userMap.remove(id);
return "success";
}
}
加入webmvc支持
<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>org.hjc</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
静态资源访问
在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。
优先级顺序为:META/resources > resources > static > public
四、Web视图渲染
以前使用@RestController来返回信息,是json格式,在动态html显示spring-boot建议使用模板配置。
Spring Boot提供了默认配置的模板引擎主要有以下几种:
Thymeleaf、FreeMarker、Velocity、Groovy、Mustache
设置使用模板,默认模板配置路径
src/main/resources/templates
添加一个模板:
/demo/src/main/resources/templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>index.html</title>
</head>
<body>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</tbody>
</table>
</body>
</html>
可以修改application.properties文件,设置相关属性
# Enable template caching.
spring.thymeleaf.cache=true
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true
# Content-Type value.
spring.thymeleaf.content-type=text/html
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true