1. Controller, RestController的共同点
都是用来表示Spring某个类的是否可以接收HTTP请求
2. Controller, RestController的不同点
@Controller标识一个Spring类是Spring MVC controller处理器
@RestController: a convenience annotation that does nothing more than adding the@Controller
and @ResponseBody
annotations。 @RestController是@Controller和@ResponseBody的结合体,两个标注合并起来的作用。
下面是一个例子,例子无请求参数,通过@RequestMapping设置了请求的路由路径和请求方法。路由路由由类的mapping和方法的mapping组成,在后面的例子中,我就不再写出RestApiRequestDemoController类的mapping了。记住,url里面有个demo在前面。
@RestController
@RequestMapping("/demo")
public class RestApiRequestDemoController {
///方法说明: 普通查询
///示例请求:http://localhost:8091/demo/list
@RequestMapping(value="/searchList",method = RequestMethod.POST)
@ResponseBody
public List searchList() {
List list = new list();
return list;
}
}
下面是使用查询字符串的例子,required可以设置请求的字符串是否必填
///方法说明:url参数的使用-查询字符串 ,且name必填
///示例请求:http://localhost:8091/demo/searchListByName?name=liuyanwei
@RequestMapping(value="/listByName",method = RequestMethod.POST)
@ResponseBody
public List searchList(@RequestParam(value="name",required = true) String name) {
Session context = DatabaseHelper.context();
String sql = "select * from tb_user where name ='"+ name+"'" ;
List list = context.createSQLQuery(sql)
.setResultTransformer(Transformers.aliasToBean(TbUserModel.class))
.list();
return list;
}
注意,需要设置application/json 否则数据库会返回。hibernate操作数据库代码暂时可以不用去管他。
/*
* 方法说明:添加数据
* 1:使用json数据提交,直接使用实体对象接收
* 2:hibernate 添加数据
* 请求参数: {"id":1,"userId":1,"pwd":"123","name":"123","pwd":"123","headPortait":"123","isEnable":"123","createDate":"2015-05-12","lastLogin":"2015-05-12"}
* 请求头:Content-Type : application/json
* 请求ur:http://localhost:8091/demo/addUser
* */
@RequestMapping(value="/addUser",method = RequestMethod.POST)
@ResponseBody
public TbUserModel addUser(@RequestBody TbUserModel user) {
Session context = DatabaseHelper.context();
Transaction tran = context.beginTransaction();
context.save(user);
tran.commit();
user.setId(user.getId());
context.close();
return user;
}
路径参数不能设置是否必填,全部都是必须填,不能省略的
///方法说明:url参数的使用
///示例请求:http://localhost:8091/demo/searchListById/2
@RequestMapping(value="/searchListById/{id}",method = RequestMethod.POST)
@ResponseBody
public List searchList(@PathVariable("id") int id) {
Session context = DatabaseHelper.context();
// String sql = "select * from tb_user where id ="+ id ;
String sql = "select * from tb_user where tb_user.id = :id";
System.out.println(sql);
List list = context.createSQLQuery(sql).setInteger("id", id)
.setResultTransformer(Transformers.aliasToBean(TbUserModel.class))
.list();
return list;
}
高级用法:路径参数可以自由设置自己的规则,比如,你有个请求需要两个参数,月和日,你可以写成{month}-{day}
///方法说明:url参数的使用
///示例请求:http://localhost:8091/demo/searchListByDate/2-10
@RequestMapping(value="/searchListByDate/{month}-{day}",method = RequestMethod.POST)
@ResponseBody
public List searchList(@PathVariable("month") int month,
@PathVariable("day") int day) {
}
注意,
/*
* 方法说明:使用表单方式提交数据
* 请求参数:isEnable=1&name=cool
* 配置
* 请求头:Content-Type : application/x-www-form-urlencoded
* 请求url:http://localhost:8091/demo/findUsersByName
* */
@RequestMapping(value="/findUsersByName",method = RequestMethod.POST)
@ResponseBody
public void findUsersByName(boolean isEnable , String name)
{
System.out.println(isEnable);
System.out.println(name);
}
单个文件通过这种方式 @RequestParam(“file”) MultipartFile file获得,这里是简单的写法,相当于 MultipartFile file = ((MultipartHttpServletRequest) request).getFile(“file”); 多个文件使用@RequestParam(“files”) MultipartFile[] files)
例子:
@RequestMapping("upload")
public Resp upload(HttpServletRequest request,
HttpServletResponse response, @RequestParam("file") MultipartFile file){
try {
//MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
String filePath = FilesService.uploadFile(file, request);
return Resp.succeedResp(filePath);
}
catch (Exception e){
e.printStackTrace();
}
return Resp.failureResp("图片上传失败");
}
@RequestMapping("batchUpload")
public Resp batchUpload(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("files") MultipartFile[] files) throws IOException {
List list = new ArrayList();
try {
for (MultipartFile file :files) {
String filePath = FilesService.uploadFile(file, request);
list.add(filePath);
System.out.println("filePath:" + filePath);
}
return Resp.succeedResp(list);
}
catch (Exception e){
e.printStackTrace();
}
return Resp.failureResp("文件上传失败");
}
想要把Rest风格的api用好,合理利用参数是必须的。不同功能的api使用不同类型的参数接收方式。每个人有不同的习惯,我的习惯是: