发表于: 2017-08-20 16:26:25
2 1022
今天完成的事情:
和老大还有师兄们爬山
Restful风格接口的问题
之前看了get(select),post(create),put(update),delete这些请求方式,在url中,这些怎么用呢?
比如一个url:http://localhost:8080/student
用户发送这样的请求来实现增删改查
http://localhost:8080/student?_method=get&id=1 查询student表里的id为1的用户信息
http://localhost:8080/student?_method=post&id=2&name=xiaoming 这个是插入
http://localhost:8080/student?_method=put&id=1&name=lilei 这个是更改,把id为1的改名为lilei
http://localhost:8080/student?_method=delete&id=3 删除id是3的信息
这样通过一个url来实现操作的就可以成为restful风格api接口
但是好像java web对put和delete请求并不支持,有点莫名其妙..
解决办法是用post来请求,具体怎么弄。在web.xml里添加一个过滤器filter
<!-- 浏览器不支持put,delete等method,由该filter将/xxx?_method=delete转换为标准的http delete方法 -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping><!--这段代码如果不用上面的的话是可以实现put的-->
18 <!--<filter>
19 <filter-name>HttpMethodPutFilter</filter-name>
20 <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
21 </filter>
22 <filter-mapping>
23 <filter-name>HttpMethodPutFilter</filter-name>
24 <url-pattern>/*</url-pattern>
25 </filter-mapping>-->
这个具体行不行我还没试,明天有时间写一个rest风格接口
一些新的注解,之前只用了@Controller,@RequestMapping
@RequestHerder 请求头,可以把Request请求header部分的值绑定到方法的参数上
@RequestBody 读取Request请求的body部分数据。它接受的应该是一个json对象的字符串,而不是json对象,至于json刚看了一点
@ResponseBody 用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区
@PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中。
试了一下这个,在之前写过的helloworld项目里,在控制器里写一个
@RequestMapping("/pathVariable/id")
public String pathVariable(@PathVariable("id")Integer id){
System.out.println("hello "+id);
return SUCCESS;
}
在jsp里再写一下
<a href="/myRequest/pathVariable/1">测试一下</a>
好了,jetty一下
点一下
尴尬了,我把之前那个jsp删了,先这样吧,上边url已经显示转到了这个pathRariable/1
明天计划的事情:
看看RESTful风格接口怎么写,看了这么久还没上手写过,不知从哪下手,json类型数据也看一看
遇到的问题:
就是REST风格接口到底怎么实现吧,要参考一下师兄们的代码了
收获:
爬的有点虚。。晚上就弄了这么点东西,希望明天能多学点
禅道链接:http://task.ptteng.com/zentao/project-task-286.html 还是炸着的,进不去
评论