Springmvc构造RESTful详细讲解
Rest介绍
/blog/1 HTTP DELETE => 删除 id = 1的blog
/blog/1 HTTP PUT => 更新id = 1的blog
/blog HTTP POST => 新增BLOG
以下详细解一下spring rest使用.
首先,我们带着如下两个问题查看本文。
1.如何在java构造没有扩展名的RESTful url,如 /forms/1,而不是 /forms/1.do
2.浏览器的form标签不支持提交delete,put请求,如何曲线解决
springmvc rest 实现
springmvc的resturl是通过@RequestMapping 及@PathVariable annotation提供的,
通过如@RequestMapping(value="/blog /{id}",method=RequestMethod.DELETE)即可处理/blog/1 的delete请求.
2public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
3 blogManager.removeById(id);
4 return new ModelAndView(LIST_ACTION);
5}
@RequestMapping @PathVariable如果URL中带参数,则配合使用,如
2public ModelAndView delete(@PathVariable("blogId") Long blogId,@PathVariable("msgId") Long msgId,HttpServletRequest request,HttpServletResponse response) {
3}
1.springmvc web.xml配置
2 <servlet-mapping>
3 <servlet-name>default</servlet-name>
4 <url-pattern>/static/*</url-pattern>
5 </servlet-mapping>
6 <servlet>
7 <servlet-name>springmvc</servlet-name>
8 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
9 <load-on-startup>1</load-on-startup>
10 </servlet>
11
12 <!-- URL重写filter,用于将访问静态资源http://localhost/foo.css 转为http://localhost/static/foo.css -->
13 <filter>
14 <filter-name>UrlRewriteFilter</filter-name>
15 <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
16 <init-param>
17 <param-name>confReloadCheckInterval</param-name>
18 <param-value>60</param-value>
19 </init-param>
20 <init-param>
21 <param-name>logLevel</param-name>
22 <param-value>DEBUG</param-value>
23 </init-param>
24 </filter>
25 <filter-mapping>
26 <filter-name>UrlRewriteFilter</filter-name>
27 <url-pattern>/*</url-pattern>
28 </filter-mapping>
29
30 <!-- 覆盖default servlet的/, springmvc servlet将处理原来处理静态资源的映射 -->
31 <servlet-mapping>
32 <servlet-name>springmvc</servlet-name>
33 <url-pattern>/</url-pattern>
34 </servlet-mapping>
35
36 <!-- 浏览器不支持put,delete等method,由该filter将/blog?_method=delete转换为标准的http delete方法 -->
37 <filter>
38 <filter-name>HiddenHttpMethodFilter</filter-name>
39 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
40 </filter>
41
42 <filter-mapping>
43 <filter-name>HiddenHttpMethodFilter</filter-name>
44 <servlet-name>springmvc</servlet-name>
45 </filter-mapping>
2.webapp/WEB-INF/springmvc-servlet.xml配置,使用如下两个class激活@RequestMapping annotation
2<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
3
3.Controller编写
2 * @RequestMapping("/userinfo") 具有层次关系,方法级的将在类一级@RequestMapping之一,
3 * 如下面示例, 访问方法级别的@RequestMapping("/new"),则URL为 /userinfo/new
4 */
5@Controller
6@RequestMapping("/userinfo")
7public class UserInfoController extends BaseSpringController{
8 //默认多列排序,example: username desc,createTime asc
9 protected static final String DEFAULT_SORT_COLUMNS = null;
10
11 private UserInfoManager userInfoManager;
12
13 private final String LIST_ACTION = "redirect:/userinfo";
14
15 /**
16 * 通过spring自动注入
17 **/
18 public void setUserInfoManager(UserInfoManager manager) {
19 this.userInfoManager = manager;
20 }
21
22 /** 列表 */
23 @RequestMapping
24 public ModelAndView index(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) {
25 PageRequest<Map> pageRequest = newPageRequest(request,DEFAULT_SORT_COLUMNS);
26 //pageRequest.getFilters(); //add custom filters
27
28 Page page = this.userInfoManager.findByPageRequest(pageRequest);
29 savePage(page,pageRequest,request);
30 return new ModelAndView("/userinfo/list","userInfo",userInfo);
31 }
32
33 /** 进入新增 */
34 @RequestMapping(value="/new")
35 public ModelAndView _new(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
36 return new ModelAndView("/userinfo/new","userInfo",userInfo);
37 }
38
39 /** 显示 */
40 @RequestMapping(value="/{id}")
41 public ModelAndView show(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
42 UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
43 return new ModelAndView("/userinfo/show","userInfo",userInfo);
44 }
45
46 /** 编辑 */
47 @RequestMapping(value="/{id}/edit")
48 public ModelAndView edit(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
49 UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
50 return new ModelAndView("/userinfo/edit","userInfo",userInfo);
51 }
52
53 /** 保存新增 */
54 @RequestMapping(method=RequestMethod.POST)
55 public ModelAndView create(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
56 userInfoManager.save(userInfo);
57 return new ModelAndView(LIST_ACTION);
58 }
59
60 /** 保存更新 */
61 @RequestMapping(value="/{id}",method=RequestMethod.PUT)
62 public ModelAndView update(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
63 UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
64 bind(request,userInfo);
65 userInfoManager.update(userInfo);
66 return new ModelAndView(LIST_ACTION);
67 }
68
69 /** 删除 */
70 @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
71 public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
72 userInfoManager.removeById(id);
73 return new ModelAndView(LIST_ACTION);
74 }
75
76 /** 批量删除 */
77 @RequestMapping(method=RequestMethod.DELETE)
78 public ModelAndView batchDelete(HttpServletRequest request,HttpServletResponse response) {
79 String[] items = request.getParameterValues("items");
80 for(int i = 0; i < items.length; i++) {
81 java.lang.Long id = new java.lang.Long(items[i]);
82 userInfoManager.removeById(id);
83 }
84 return new ModelAndView(LIST_ACTION);
85 }
86
87}
88
2 /userinfo/new => _new()
3 /userinfo/{id} => show()
4 /userinfo/{id}/edit => edit()
5 /userinfo POST => create()
6 /userinfo/{id} PUT => update()
7 /userinfo/{id} DELETE => delete()
8 /userinfo DELETE => batchDelete()
9
注(不使用 /userinfo/add => add() 方法是由于add这个方法会被maxthon浏览器当做广告链接过滤掉,因为包含ad字符)
4.jsp 编写
2</form:form>
生成的html内容如下, 生成一个hidden的_method=put,并于web.xml中的HiddenHttpMethodFilter配合使用,在服务端将post请求改为put请求
2 <input type="hidden" name="_method" value="put"/>
3</form>
另外一种方法是你可以使用ajax发送put,delete请求.
5.静态资源的URL重写
如上我们描述,现因为将default servlet映射至/static/的子目录,现我们访问静态资源将会带一个/static/前缀.
如 /foo.gif, 现在访问该文件将是 /static/foo.gif.
那如何避免这个前缀呢,那就是应用URL rewrite,现我们使用 http://tuckey.org/urlrewrite/, 重写规则如下
2 <!-- 访问jsp及jspx将不rewrite url,其它.js,.css,.gif等将重写,如 /foo.gif => /static/foo.gif -->
3 <rule>
4 <condition operator="notequal" next="and" type="request-uri">.*.jsp</condition>
5 <condition operator="notequal" next="and" type="request-uri">.*.jspx</condition>
6 <from>^(/.*\..*)$</from>
7 <to>/static$1</to>
8 </rule>
9</urlrewrite>
Springmvc构造RESTful详细讲解的更多相关文章
- spring 3.0 应用springmvc 构造RESTful URL 详细讲解
在线springmvc_rest demo 由于下一版本的rapid-framwork需要集成spring RESTful URL,所以研究了一下怎么搭建. 并碰到了一下问题. springmvc 3 ...
- Restful 介绍及SpringMVC+restful 实例讲解
restful不是一个框架,称为一种编码更烦更贴切吧,其核心类位于spring-web.jar中,即RestTemplate.class restful是rpc通过http协议的一种实现方式,和web ...
- 数据结构与算法(九):AVL树详细讲解
数据结构与算法(一):基础简介 数据结构与算法(二):基于数组的实现ArrayList源码彻底分析 数据结构与算法(三):基于链表的实现LinkedList源码彻底分析 数据结构与算法(四):基于哈希 ...
- python format函数/print 函数详细讲解(4)
在python开发过程中,print函数和format函数使用场景特别多,下面分别详细讲解两个函数的用法. 一.print函数 print翻译为中文指打印,在python中能直接输出到控制台,我们可以 ...
- C++语言堆栈的详细讲解
本文主要向大家介绍了C++语言堆栈的详细讲解,通过具体的内容向大家展示,希望对大家学习C++语言有所帮助. 一.预备知识—程序的内存分配 一个由c/C++编译的程序占用的内存分为以下几个部分 1.栈区 ...
- (转)springMVC+mybatis+ehcache详细配置
一. Mybatis+Ehcache配置 为了提高MyBatis的性能,有时候我们需要加入缓存支持,目前用的比较多的缓存莫过于ehcache缓存了,ehcache性能强大,而且位各种应用都提供了解决方 ...
- head标签详细讲解
head标签详细讲解 head位于html网页的头部,后前的标签,并以开始以结束的一html标签. Head标签位置如图: head标签示意图 head包含标签 meta,title,link,bas ...
- 详细讲解nodejs中使用socket的私聊的方式
详细讲解nodejs中使用socket的私聊的方式 在上一次我使用nodejs+express+socketio+mysql搭建聊天室,这基本上就是从socket.io的官网上的一份教程式复制学习,然 ...
- iOS KVC详细讲解
iOS KVC详细讲解 什么是KVC? KVC即NSKeyValueCoding,就是键-值编码的意思.一个非正式的 Protocol,是一种间接访问对象的属性使用字符串来标识属性,而不是通过调用存取 ...
随机推荐
- 一个例子说明如何在DataSnap中使用FireDAC
一.FireDAC调用DataSnap远程方法查询数据示例 1.服务端使用FDQUERY查询数据并返回TDATASET: function TServerMethods1.GetData(var sq ...
- spring接收参数
public class LogonModel { private String UserName; private String Password; public String getUserNam ...
- linux下使用sqlplus使用上下键显示历史命令
在linux下使用sqlplus没有在windows下方便,既不好用习惯的退格键,也无法通过上键来显示上一条的命令,这里我们使用rlwrap来解决. 1.安装rlwrap [root@toughhou ...
- 运行windows系统工具命令
appwiz.cpl 卸载/安装程序 wscui.cpl 操作中心 inetcpl.cpl 查看Internet属性 eventvwr 查看监视消息和疑难解答消息 taskmgr 任 ...
- java后台SSH框架之Hibernate心得一
双向关联和单向关联 双向关联:这两个表无论哪一个更新另外一个表都更新 单向关联:就是只有一个主表更新从表才更新 从表更新主表不管 双向关联配置 表1配置 <set name="对象名称 ...
- asp.net web api 开发时应当注意的事项
Self referencing when returning chain of objects. This can be solved using a design pattern called t ...
- IntelliJ IDEA 进行js Debug调试
idea的js调试目前看来不同给力,一是玩转它需要安装谷歌插件支持,二是貌似存在一些bug... 一.新建一个jsp并打上断点 二.调试 idea出现提示: 安装JetBrains IDE Suppo ...
- c#保留小数点后两位
double d = 23423.24234234d; Response.Write(d.ToString("0.00"));
- PHP运算符及php取整函数
ceil -- 进一法取整 说明 float ceil ( float value ) 返回不小于 value 的下一个整数,value 如果有小数部分则进一位.ceil() 返回的类型仍然是 flo ...
- C++开发必看 四种强制类型转换的总结
C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是: TYPE b = (TYPE)a C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用. const_cast ...