Spring RestController 请求参数详解
在阅读之前,最好先了解http请求的get,post,以及各种head头类型,请求参数类型。
- 无参数,设置RestController请求路径
- 查询字符串参数,可选和必选参数
- json参数,RestController用实体类型接受
- 路径参数
- body参数
- 文件流参数
1 无参数,设置RestController请求路径
下面是一个例子,例子无请求参数,通过@RequestMapping设置了请求的路由路径和请求方法。路由路由由类的mapping和方法的mapping组成,在后面的例子中,我就不再写出RestApiRequestDemoController类的mapping了。记住,url里面有个demo在前面。
@RestController
@RequestMapping("/demo")
public class RestApiRequestDemoController {
<span class="c1">///方法说明: 普通查询</span>
<span class="c1">///示例请求:http://localhost:8091/demo/list</span>
<span class="nd">@RequestMapping</span><span class="o">(</span><span class="n">value</span><span class="o">=</span><span class="s">"/searchList"</span><span class="o">,</span><span class="n">method</span> <span class="o">=</span> <span class="n">RequestMethod</span><span class="o">.</span><span class="na">POST</span><span class="o">)</span>
<span class="nd">@ResponseBody</span>
<span class="kd">public</span> <span class="n">List</span><span class="o"><</span><span class="n">UserModel</span><span class="o">></span> <span class="nf">searchList</span><span class="o">()</span> <span class="o">{</span>
<span class="n">List</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">list</span><span class="o">();</span>
<span class="k">return</span> <span class="n">list</span><span class="o">;</span>
<span class="o">}</span>
}
2 查询字符串参数,可选和必选参数2. 查询字符串参数,可选和必选参数
下面是使用查询字符串的例子,required可以设置请求的字符串是否必填
///方法说明:url参数的使用-查询字符串 ,且name必填
///示例请求:http://localhost:8091/demo/searchListByName?name=liuyanwei
@RequestMapping(value="/listByName",method = RequestMethod.POST)
@ResponseBody
public List<TbUserModel> searchList(@RequestParam(value="name",required = true) String name) {
<span class="n">Session</span> <span class="n">context</span> <span class="o">=</span> <span class="n">DatabaseHelper</span><span class="o">.</span><span class="na">context</span><span class="o">();</span>
<span class="n">String</span> <span class="n">sql</span> <span class="o">=</span> <span class="s">"select * from tb_user where name ='"</span><span class="o">+</span> <span class="n">name</span><span class="o">+</span><span class="s">"'"</span> <span class="o">;</span>
<span class="n">List</span> <span class="n">list</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="na">createSQLQuery</span><span class="o">(</span><span class="n">sql</span><span class="o">)</span>
<span class="o">.</span><span class="na">setResultTransformer</span><span class="o">(</span><span class="n">Transformers</span><span class="o">.</span><span class="na">aliasToBean</span><span class="o">(</span><span class="n">TbUserModel</span><span class="o">.</span><span class="na">class</span><span class="o">))</span>
<span class="o">.</span><span class="na">list</span><span class="o">();</span>
<span class="k">return</span> <span class="n">list</span><span class="o">;</span>
}
3 json参数,RestController用实体类型接受
注意,需要设置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) {
<span class="n">Session</span> <span class="n">context</span> <span class="o">=</span> <span class="n">DatabaseHelper</span><span class="o">.</span><span class="na">context</span><span class="o">();</span>
<span class="n">Transaction</span> <span class="n">tran</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>
<span class="n">context</span><span class="o">.</span><span class="na">save</span><span class="o">(</span><span class="n">user</span><span class="o">);</span>
<span class="n">tran</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span>
<span class="n">user</span><span class="o">.</span><span class="na">setId</span><span class="o">(</span><span class="n">user</span><span class="o">.</span><span class="na">getId</span><span class="o">());</span>
<span class="n">context</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="k">return</span> <span class="n">user</span><span class="o">;</span>
}
4 路径参数
路径参数不能设置是否必填,全部都是必须填,不能省略的
///方法说明:url参数的使用
///示例请求:http://localhost:8091/demo/searchListById/2
@RequestMapping(value="/searchListById/{id}",method = RequestMethod.POST)
@ResponseBody
public List<TbUserModel> searchList(@PathVariable("id") int id) {
<span class="n">Session</span> <span class="n">context</span> <span class="o">=</span> <span class="n">DatabaseHelper</span><span class="o">.</span><span class="na">context</span><span class="o">();</span>
<span class="c1">// String sql = "select * from tb_user where id ="+ id ;</span>
<span class="n">String</span> <span class="n">sql</span> <span class="o">=</span> <span class="s">"select * from tb_user where tb_user.id = :id"</span><span class="o">;</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">sql</span><span class="o">);</span>
<span class="n">List</span> <span class="n">list</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="na">createSQLQuery</span><span class="o">(</span><span class="n">sql</span><span class="o">).</span><span class="na">setInteger</span><span class="o">(</span><span class="s">"id"</span><span class="o">,</span> <span class="n">id</span><span class="o">)</span>
<span class="o">.</span><span class="na">setResultTransformer</span><span class="o">(</span><span class="n">Transformers</span><span class="o">.</span><span class="na">aliasToBean</span><span class="o">(</span><span class="n">TbUserModel</span><span class="o">.</span><span class="na">class</span><span class="o">))</span>
<span class="o">.</span><span class="na">list</span><span class="o">();</span>
<span class="k">return</span> <span class="n">list</span><span class="o">;</span>
}
高级用法:路径参数可以自由设置自己的规则,比如,你有个请求需要两个参数,月和日,你可以写成{month}-{day}
///方法说明:url参数的使用
///示例请求:http://localhost:8091/demo/searchListByDate/2-10
@RequestMapping(value="/searchListByDate/{month}-{day}",method = RequestMethod.POST)
@ResponseBody
public List<TbUserModel> searchList(@PathVariable("month") int month,
@PathVariable("day") int day) {
}
5. 表单参数参数
注意,
- 这种方式传参数不能设置参数选填
- 注意,参数写在boby中,相当于表单参数,必须设置请求头为:application/x-www-form-urlencoded
- 若参数不正确,是无法进入控制器的。
/*
* 方法说明:使用表单方式提交数据
* 请求参数: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);
}
6. 文件流参数
-
单个文件通过这种方式 @RequestParam(“file”) MultipartFile file获得,这里是简单的写法,相当于 MultipartFile file = ((MultipartHttpServletRequest) request).getFile(“file”); 多个文件使用@RequestParam(“files”) MultipartFile[] files)
- 表单中文件的name属性必须设置file(注意,不是文件名),例如,html中 <input type="files" name="file" > </li>
- 这个是简单获取文件的方式,若不知道表单中文件的name属性,可以通过request获取文件
例子:
@RequestMapping("upload")
public Resp upload(HttpServletRequest request,
HttpServletResponse response, @RequestParam("file") MultipartFile file){
<span class="k">try</span> <span class="o">{</span>
<span class="c1">//MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;</span>
<span class="n">String</span> <span class="n">filePath</span> <span class="o">=</span> <span class="n">FilesService</span><span class="o">.</span><span class="na">uploadFile</span><span class="o">(</span><span class="n">file</span><span class="o">,</span> <span class="n">request</span><span class="o">);</span>
<span class="k">return</span> <span class="n">Resp</span><span class="o">.</span><span class="na">succeedResp</span><span class="o">(</span><span class="n">filePath</span><span class="o">);</span>
<span class="o">}</span>
<span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">){</span>
<span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
<span class="o">}</span>
<span class="k">return</span> <span class="n">Resp</span><span class="o">.</span><span class="na">failureResp</span><span class="o">(</span><span class="s">"图片上传失败"</span><span class="o">);</span>
}
@RequestMapping("batchUpload")
public Resp batchUpload(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("files") MultipartFile[] files) throws IOException {
List<String> list = new ArrayList<String>();
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使用不同类型的参数接收方式。每个人有不同的习惯,我的习惯是:
- 一般获取内容,不涉及加密的用get方法,设计加密的用post
- 提交内容,例如添加,删除,修改,使用post、delete、put方法
- 通过主键获取内容的,我习惯用url参数,例如:/news/details/1,参数不是很多,组合起来有意义的也会用url路径组合,例如前面的日期:/demo/searchListByDate/2-10
- 有时候接收参数组合起来用比较好,有的内容通过url参数,有的部分用表单内容。
- 所有的设计接收参数的原则就是,然你的api的url能读通,看起来合理。
好了,就到这了,后面有时间我会再写一些hibernate 数据操作的例子和hibernate获取实体参数验证的内容,有的问题我也还没完全搞清楚,后面在研究看看。
<div class="declare">
<div>
</div>
</div>