做外单都有什么网站,海盐市网站建设,三门网站制作,李连杰做的功夫网站一、简介
REST#xff08;Representational State Transfer#xff09;#xff0c;表现形式状态转换,它是一种软件架构风格 当我们想表示一个网络资源的时候#xff0c;可以使用两种方式:
传统风格资源描述形式
http://localhost/user/getById?id1 查询id为1的用户信息…一、简介
RESTRepresentational State Transfer表现形式状态转换,它是一种软件架构风格 当我们想表示一个网络资源的时候可以使用两种方式:
传统风格资源描述形式
http://localhost/user/getById?id1 查询id为1的用户信息http://localhost/user/saveUser 保存用户信息
REST风格描述形式
http://localhost/user/1http://localhost/user
所以REST的优点有:
隐藏资源的访问行为无法通过地址得知对资源是何种操作书写简化
常用的请求GET , POST , PUT , DELETE。
发送GET请求是用来做查询发送POST请求是用来做新增发送PUT请求是用来做修改发送DELETE请求是用来做删除
二、具体代码
原始实现
//Controller
//ResponseBody配置在类上可以简化配置表示设置当前每个方法的返回值都作为响应体
//ResponseBody
RestController //使用RestController注解替换Controller与ResponseBody注解简化书写
RequestMapping(/books)
public class BookController {// RequestMapping( method RequestMethod.POST)
PostMapping //使用PostMapping简化Post请求方法对应的映射配置
public String save(RequestBody Book book){
System.out.println(book save... book);
return {module:book save};
}// RequestMapping(value /{id} ,method RequestMethod.DELETE)
DeleteMapping(/{id}) //使用DeleteMapping简化DELETE请求方法对应的映射配置
public String delete(PathVariable Integer id){
System.out.println(book delete... id);
return {module:book delete};
}// RequestMapping(method RequestMethod.PUT)
PutMapping //使用PutMapping简化Put请求方法对应的映射配置
public String update(RequestBody Book book){
System.out.println(book update...book);
return {module:book update};
}// RequestMapping(value /{id} ,method RequestMethod.GET)
GetMapping(/{id}) //使用GetMapping简化GET请求方法对应的映射配置
public String getById(PathVariable Integer id){
System.out.println(book getById...id);
return {module:book getById};
}// RequestMapping(method RequestMethod.GET)
GetMapping //使用GetMapping简化GET请求方法对应的映射配置
public String getAll(){
System.out.println(book getAll...);
return {module:book getAll};
}
}
更新后
//标准REST风格控制器开发
RestController
RequestMapping(/books)
public class BookController2 {PostMapping //添加public String save(RequestBody Book book){System.out.println(book save... book);return {module:book save};}DeleteMapping(/{id})public String delete(PathVariable Integer id){System.out.println(book delete... id);return {module:book delete};}PutMapping //修改public String update(RequestBody Book book){System.out.println(book update...book);return {module:book update};}GetMapping(/{id}) //get是查询public String getById(PathVariable Integer id){System.out.println(book getById...id);return {module:book getById};}GetMappingpublic String getAll(){System.out.println(book getAll...);return {module:book getAll};}
}
注意要在SpringConfig配置类中加上 EnableWebMvc 注解目前用来解析json格式此注解功能很多 Configuration
ComponentScan(com.itheima.controller)
EnableWebMvc
public class SpringMvcConfig {
}