spring 3.0 应用springmvc 构造RESTful URL 详细讲解
由于下一版本的rapid-framwork需要集成spring RESTful URL,所以研究了一下怎么搭建. 并碰到了一下问题。
springmvc 3.0 中增加 RESTful URL功能,构造出类似javaeye现在的URL。 rest介绍 , 这里还有struts2 rest构造的一篇文章: 使用 Struts 2 开发 RESTful 服务
简单例子如下,比如如下URL
- /blog/1 HTTP GET => 得到id = 1的blog
- /blog/1 HTTP DELETE => 删除 id = 1的blog
- /blog/1 HTTP PUT => 更新id = 1的blog
- /blog HTTP POST => 新增BLOG
/blog/1 HTTP GET => 得到id = 1的blog
/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. 由于我们要构造没有扩展名的url本来是处理静态资源的容器映射的,现在被我们的spring占用了,冲突怎么解决?
3. 浏览器的form标签不支持提交delete,put请求,如何曲线解决?
springmvc rest 实现
springmvc的resturl是通过@RequestMapping 及@PathVariable annotation提供的,通过如@RequestMapping(value="/blog/{id}",method=RequestMethod.DELETE)即可处理/blog/1 的delete请求.
- @RequestMapping(value="/blog/{id}",method=RequestMethod.DELETE)
- public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
- blogManager.removeById(id);
- return new ModelAndView(LIST_ACTION);
- }
@RequestMapping(value="/blog/{id}",method=RequestMethod.DELETE)
public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
blogManager.removeById(id);
return new ModelAndView(LIST_ACTION);
}
@RequestMapping @PathVariable如果URL中带参数,则配合使用,如
- @RequestMapping(value="/blog/{blogId}/message/{msgId}",method=RequestMethod.DELETE)
- public ModelAndView delete(@PathVariable("blogId") Long blogId,@PathVariable("msgId") Long msgId,HttpServletRequest request,HttpServletResponse response) {
- }
@RequestMapping(value="/blog/{blogId}/message/{msgId}",method=RequestMethod.DELETE)
public ModelAndView delete(@PathVariable("blogId") Long blogId,@PathVariable("msgId") Long msgId,HttpServletRequest request,HttpServletResponse response) {
}
spring rest配置指南
1. springmvc web.xml配置
- <!-- 该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问 http://localhost/foo.css ,现在http://localhost/static/foo.css -->
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>/static/*</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <!-- URL重写filter,用于将访问静态资源http://localhost/foo.css 转为http://localhost/static/foo.css -->
- <filter>
- <filter-name>UrlRewriteFilter</filter-name>
- <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
- <init-param>
- <param-name>confReloadCheckInterval</param-name>
- <param-value>60</param-value>
- </init-param>
- <init-param>
- <param-name>logLevel</param-name>
- <param-value>DEBUG</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>UrlRewriteFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- 覆盖default servlet的/, springmvc servlet将处理原来处理静态资源的映射 -->
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <!-- 浏览器不支持put,delete等method,由该filter将/blog?_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>
- <servlet-name>springmvc</servlet-name>
- </filter-mapping>
<!-- 该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问 http://localhost/foo.css ,现在http://localhost/static/foo.css -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <!-- URL重写filter,用于将访问静态资源http://localhost/foo.css 转为http://localhost/static/foo.css -->
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>confReloadCheckInterval</param-name>
<param-value>60</param-value>
</init-param>
<init-param>
<param-name>logLevel</param-name>
<param-value>DEBUG</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 覆盖default servlet的/, springmvc servlet将处理原来处理静态资源的映射 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 浏览器不支持put,delete等method,由该filter将/blog?_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>
<servlet-name>springmvc</servlet-name>
</filter-mapping>
2. webapp/WEB-INF/springmvc-servlet.xml配置,使用如下两个class激活@RequestMapping annotation
- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
完整配置
- <beans default-autowire="byName" >
- <!-- 自动搜索@Controller标注的类 -->
- <context:component-scan base-package="com.**.controller"/>
- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
- <!-- Default ViewResolver -->
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
- <property name="prefix" value="/pages"/>
- <property name="suffix" value=".jsp"></property>
- </bean>
- <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="i18n/messages"/>
- <!-- Mapping exception to the handler view -->
- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <!-- to /commons/error.jsp -->
- <property name="defaultErrorView" value="/commons/error"/>
- <property name="exceptionMappings">
- <props>
- </props>
- </property>
- </bean>
- </beans>
<beans default-autowire="byName" > <!-- 自动搜索@Controller标注的类 -->
<context:component-scan base-package="com.**.controller"/> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- Default ViewResolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/pages"/>
<property name="suffix" value=".jsp"></property>
</bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="i18n/messages"/> <!-- Mapping exception to the handler view -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- to /commons/error.jsp -->
<property name="defaultErrorView" value="/commons/error"/>
<property name="exceptionMappings">
<props>
</props>
</property>
</bean> </beans>
3. Controller编写
- /**
- * @RequestMapping("/userinfo") 具有层次关系,方法级的将在类一级@RequestMapping之一,
- * 如下面示例, 访问方法级别的@RequestMapping("/new"),则URL为 /userinfo/new
- */
- @Controller
- @RequestMapping("/userinfo")
- public class UserInfoController extends BaseSpringController{
- //默认多列排序,example: username desc,createTime asc
- protected static final String DEFAULT_SORT_COLUMNS = null;
- private UserInfoManager userInfoManager;
- private final String LIST_ACTION = "redirect:/userinfo";
- /**
- * 通过spring自动注入
- **/
- public void setUserInfoManager(UserInfoManager manager) {
- this.userInfoManager = manager;
- }
- /** 列表 */
- @RequestMapping
- public ModelAndView index(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) {
- PageRequest<Map> pageRequest = newPageRequest(request,DEFAULT_SORT_COLUMNS);
- //pageRequest.getFilters(); //add custom filters
- Page page = this.userInfoManager.findByPageRequest(pageRequest);
- savePage(page,pageRequest,request);
- return new ModelAndView("/userinfo/list","userInfo",userInfo);
- }
- /** 进入新增 */
- @RequestMapping(value="/new")
- public ModelAndView _new(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
- return new ModelAndView("/userinfo/new","userInfo",userInfo);
- }
- /** 显示 */
- @RequestMapping(value="/{id}")
- public ModelAndView show(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
- UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
- return new ModelAndView("/userinfo/show","userInfo",userInfo);
- }
- /** 编辑 */
- @RequestMapping(value="/{id}/edit")
- public ModelAndView edit(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
- UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
- return new ModelAndView("/userinfo/edit","userInfo",userInfo);
- }
- /** 保存新增 */
- @RequestMapping(method=RequestMethod.POST)
- public ModelAndView create(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
- userInfoManager.save(userInfo);
- return new ModelAndView(LIST_ACTION);
- }
- /** 保存更新 */
- @RequestMapping(value="/{id}",method=RequestMethod.PUT)
- public ModelAndView update(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
- UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
- bind(request,userInfo);
- userInfoManager.update(userInfo);
- return new ModelAndView(LIST_ACTION);
- }
- /** 删除 */
- @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
- public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
- userInfoManager.removeById(id);
- return new ModelAndView(LIST_ACTION);
- }
- /** 批量删除 */
- @RequestMapping(method=RequestMethod.DELETE)
- public ModelAndView batchDelete(@RequestParam("items") Long[] items,HttpServletRequest request,HttpServletResponse response) {
- for(int i = 0; i < items.length; i++) {
- userInfoManager.removeById(items[i]);
- }
- return new ModelAndView(LIST_ACTION);
- }
- }
/**
* @RequestMapping("/userinfo") 具有层次关系,方法级的将在类一级@RequestMapping之一,
* 如下面示例, 访问方法级别的@RequestMapping("/new"),则URL为 /userinfo/new
*/
@Controller
@RequestMapping("/userinfo")
public class UserInfoController extends BaseSpringController{
//默认多列排序,example: username desc,createTime asc
protected static final String DEFAULT_SORT_COLUMNS = null; private UserInfoManager userInfoManager; private final String LIST_ACTION = "redirect:/userinfo"; /**
* 通过spring自动注入
**/
public void setUserInfoManager(UserInfoManager manager) {
this.userInfoManager = manager;
} /** 列表 */
@RequestMapping
public ModelAndView index(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) {
PageRequest<Map> pageRequest = newPageRequest(request,DEFAULT_SORT_COLUMNS);
//pageRequest.getFilters(); //add custom filters Page page = this.userInfoManager.findByPageRequest(pageRequest);
savePage(page,pageRequest,request);
return new ModelAndView("/userinfo/list","userInfo",userInfo);
} /** 进入新增 */
@RequestMapping(value="/new")
public ModelAndView _new(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
return new ModelAndView("/userinfo/new","userInfo",userInfo);
} /** 显示 */
@RequestMapping(value="/{id}")
public ModelAndView show(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
return new ModelAndView("/userinfo/show","userInfo",userInfo);
} /** 编辑 */
@RequestMapping(value="/{id}/edit")
public ModelAndView edit(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
return new ModelAndView("/userinfo/edit","userInfo",userInfo);
} /** 保存新增 */
@RequestMapping(method=RequestMethod.POST)
public ModelAndView create(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
userInfoManager.save(userInfo);
return new ModelAndView(LIST_ACTION);
} /** 保存更新 */
@RequestMapping(value="/{id}",method=RequestMethod.PUT)
public ModelAndView update(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
bind(request,userInfo);
userInfoManager.update(userInfo);
return new ModelAndView(LIST_ACTION);
} /** 删除 */
@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
userInfoManager.removeById(id);
return new ModelAndView(LIST_ACTION);
} /** 批量删除 */
@RequestMapping(method=RequestMethod.DELETE)
public ModelAndView batchDelete(@RequestParam("items") Long[] items,HttpServletRequest request,HttpServletResponse response) { for(int i = 0; i < items.length; i++) { userInfoManager.removeById(items[i]);
}
return new ModelAndView(LIST_ACTION);
} }
上面是rapid-framework新版本生成器生成的代码,以后也将应用此规则,rest url中增删改查等基本方法与Controller的方法映射规则
- /userinfo => index()
- /userinfo/new => _new()
- /userinfo/{id} => show()
- /userinfo/{id}/edit => edit()
- /userinfo POST => create()
- /userinfo/{id} PUT => update()
- /userinfo/{id} DELETE => delete()
- /userinfo DELETE => batchDelete()
/userinfo => index()
/userinfo/new => _new()
/userinfo/{id} => show()
/userinfo/{id}/edit => edit()
/userinfo POST => create()
/userinfo/{id} PUT => update()
/userinfo/{id} DELETE => delete()
/userinfo DELETE => batchDelete()
注(不使用 /userinfo/add => add() 方法是由于add这个方法会被maxthon浏览器当做广告链接过滤掉,因为包含ad字符)
4. jsp 编写
- <form:form action="${ctx}/userinfo/${userInfo.userId}" method="put">
- </form:form>
<form:form action="${ctx}/userinfo/${userInfo.userId}" method="put">
</form:form>
生成的html内容如下, 生成一个hidden的_method=put,并于web.xml中的HiddenHttpMethodFilter配合使用,在服务端将post请求改为put请求
- <form id="userInfo" action="/springmvc_rest_demo/userinfo/2" method="post">
- <input type="hidden" name="_method" value="put"/>
- </form>
<form id="userInfo" action="/springmvc_rest_demo/userinfo/2" method="post">
<input type="hidden" name="_method" value="put"/>
</form>
另外一种方法是你可以使用ajax发送put,delete请求.
5. 静态资源的URL重写
如上我们描述,现因为将default servlet映射至/static/的子目录,现我们访问静态资源将会带一个/static/前缀.
如 /foo.gif, 现在访问该文件将是 /static/foo.gif.
那如何避免这个前缀呢,那就是应用URL rewrite,现我们使用 http://tuckey.org/urlrewrite/, 重写规则如下
- <urlrewrite>
- <!-- 访问jsp及jspx将不rewrite url,其它.js,.css,.gif等将重写,如 /foo.gif => /static/foo.gif -->
- <rule>
- <condition operator="notequal" next="and" type="request-uri">.*.jsp</condition>
- <condition operator="notequal" next="and" type="request-uri">.*.jspx</condition>
- <from>^(/.*\..*)$</from>
- <to>/static$1</to>
- </rule>
- </urlrewrite>
<urlrewrite>
<!-- 访问jsp及jspx将不rewrite url,其它.js,.css,.gif等将重写,如 /foo.gif => /static/foo.gif -->
<rule>
<condition operator="notequal" next="and" type="request-uri">.*.jsp</condition>
<condition operator="notequal" next="and" type="request-uri">.*.jspx</condition>
<from>^(/.*\..*)$</from>
<to>/static$1</to>
</rule>
</urlrewrite>
另笔者专门写了一个 RestUrlRewriteFilter来做同样的事件,以后会随着rapid-framework一起发布. 比这个更加轻量级.
并且该代码已经贡献给spring,不知会不会在下一版本发布
在线DEMO地址: http://demo.rapid-framework.org.cn:8080/springmvc_rest_demo/userinfo
spring 3.0 应用springmvc 构造RESTful URL 详细讲解的更多相关文章
- Springmvc构造RESTful详细讲解
Rest介绍 /blog/1 HTTP GET => 得到id = 1的blog/blog/1 HTTP DELETE => 删除 id = 1的blog/blog/1 HTTP PUT ...
- Spring MVC 3.0 深入及对注解的详细讲解
核心原理 1. 用户发送请求给服务器.url:user.do 2. 服务器收到请求.发现Dispatchservlet可以处理.于是调用DispatchServlet. 3. ...
- Spring MVC 3.0 深入及对注解的详细讲解[转载]
http://blog.csdn.net/jzhf2012/article/details/8463783 核心原理 1. 用户发送请求给服务器.url:user.do 2. ...
- SSM实战——秒杀系统之Web层Restful url设计、SpringMVC整合、页面设计
一:Spring整合SpringMVC 1:编写web.xml,配置DispatcherServlet <web-app xmlns="http://java.sun.com/xml/ ...
- Spring Boot2.0+中,自定义配置类扩展springMVC的功能
在spring boot1.0+,我们可以使用WebMvcConfigurerAdapter来扩展springMVC的功能,其中自定义的拦截器并不会拦截静态资源(js.css等). @Configur ...
- Spring注解驱动开发(七)-----servlet3.0、springmvc
ServletContainerInitializer Shared libraries(共享库) / runtimes pluggability(运行时插件能力) 1.Servlet容器启动会扫描, ...
- 浅尝Spring注解开发_Servlet3.0与SpringMVC
浅尝Spring注解开发_Servlet 3.0 与 SpringMVC 浅尝Spring注解开发,基于Spring 4.3.12 Servlet3.0新增了注解支持.异步处理,可以省去web.xml ...
- SSH(Struts,Spring,Hibernate)和SSM(SpringMVC,Spring,MyBatis)的区别
SSH 通常指的是 Struts2 做前端控制器,Spring 管理各层的组件,Hibernate 负责持久化层. SSM 则指的是 SpringMVC 做前端控制器,Spring 管理各层的组件,M ...
- 基于springMVC的RESTful服务实现
一,什么是RESTful RESTful(RESTful Web Services)一种架构风格,表述性状态转移,它不是一个软件,也不是一个标准,而是一种思想,不依赖于任何通信协议,但是开发时要成功映 ...
随机推荐
- UDP的connect函数
UDP的connect没有三次握手过程,内核只是检测是否存在立即可知的错误(如一个显然不可达的目的地), 记录对端的的IP地址和端口号,然后立即返回调用进程. 未连接UDP套接字(unconnecte ...
- SAP连接电脑串口读数(电子称,磅等数据读取)
这是几年前做的了,一直都不想分享出来,后来想想为了能够给大家点想法,献出来了... 这是一个电脑读称的方法,一般用COMM口连接的电子设备都可参考. 如果是对串口参数不确定的,可以网上找个串口测试工具 ...
- HTML 教程延伸阅读:改变文本的外观和含义
很多标签都可以用来改变文本的外观,并为文本关联其隐藏的含义.总地来说,这些标签可以分成两类:基于内容的样式(content-based style)和物理样式(physical style). 基于内 ...
- C# List泛型集合中的GroupBy<>用法
//根据子项目id得到flowjump实体类 flowJumps = this.FlowJumps; //按工序groupby flowjumps IEnumerable<IGrouping&l ...
- MVC5+EF6 入门完整教程七
本篇我们针对表格显示添加一些新功能. 前面我们已经讲解过表格显示数据了,现在我们添加三个常用功能: 对显示结果进行排序.过滤.分页. 文章提纲 理论基础/前置准备 详细步骤 总结 前置准备 – 应用之 ...
- github改local用户名和email
github改local用户名和email 进入cd ~/.ssh 修改git config --global user.name “用户名” config --global user.email 电 ...
- 安装LoadRunner提示缺少vc2005_sp1_with_atl..
装自动化负载测试工具LoadRunner前,需要预先安装其运行的基础环境.如:安装LoadRunner 11时就需要先安装Micrsoft Visual C++ 2005 SP1.C++ 2008运行 ...
- github使用
1.首先登录到https://github.com注册Github帐号,并且创建一个repository. 例如:注册的github帐号名为whu-zhangmin,创建的repository名称为w ...
- C# 技巧(3) C# 操作 JSON
RestAPI中, 经常需要操作json字符串, 需要把json字符串"反序列化"成一个对象, 也需要把一个对象"序列化"成一字符串. C# 操作json, ...
- git 忽略提交某个指定的文件(不从版本库中删除)
执行指令: 1 2 [Sun@webserver2 demo]$ git update-index --assume-unchanged config.conf [Sun@webserver2 dem ...