1 @RestController
作用:标明此 Controller 提供 RestAPI
2 @RequestMapping
作用:映射 http 请求 URL 到java 方法
常用参数:
value:请求的url
method:请求方式,GET、POST、PUT、DELETE等
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html
produces: 指定返回的内容类型,仅当request请求头中的类型中包含该指定类型才返回
params:指定request中必须包含某些参数值时,才让该方法处理
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求
2.1 @GetMappring
此注解是 @RequestMapping 的变体,相当于 @RequestMapping(method=RequestMethod.GET)
2.2 @PostMapping
相当于 @RequestMapping(method=RequestMethod.POST)
2.3 @DeleteMapping
相当于 @RequestMapping(method=RequestMethod.DELETE)
2.4 @PutMapping
相当于 @RequestMapping(method=RequestMethod.PUT)
3 @RequestParam
作用:映射请求参数到 java 方法的参数
常用参数:
defaultValue:设置默认值
required:设置是否是必须要传入的参数
value:表示接受的传入的参数类型
4 @Autowired
作用:用于 Bean 的注入,为 Spring 提供的注解,需要导入包 org.springframework.beans.factory.annotation.Autowired
@Autowired 只按照 byType 注入
5 @PathVariable
作用:用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数
常用参数:
value:要绑定到的路径变量的名称
required:设置是否是必须要传入的参数
6 @ResponseBody
作用:该注解用于将Controller的方法返回的对象,写入到Response对象的body数据区
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用
7 @PageableDefault
作用:设置分页信息
常用参数:
sort:排序方式
size:每一页默认的条数
page:默认查询的页数
8 @JsonView
作用:用于控制输出的 json 的显示视图
用法:
1、使用接口声明多个视图
2、在 getter 方法上指定视图
3、在 controller 方法上指定视图
例子:
package com.llangzh.bean;
import com.fasterxml.jackson.annotation.JsonView;
public class User {
public interface UserSimpleView{};
public interface UserDetailView extends UserSimpleView {};
private String username;
private String password;
public User() {
super();
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
@JsonView(UserSimpleView.class)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.llangzh.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.annotation.JsonView;
import com.llangzh.bean.User;
@RestController()
public class UserController {
@Autowired
private IUserService userService;
@GetMapping
@JsonView(User.UserSimpleView.class)
public List<User> query() {
List<User> users = userService.query();
return users;
}
}