strurts2 中的 ActionMapper的 作用

最近在项目中要做http api,要求提供的url是 http://***.domain.com/api/rest?sign={签名}&method={namespace}.{action名}.{调用方法名}&......

 

类似淘宝的top api url 风格,一个url,根据参数不同,映射到不同的控制器。

 

实现方法详细:

 

1、实现自己的ActionMapper,通过method参数将请求转发到具体的action

Java代码   收藏代码
  1. public class RestActionMapper extends DefaultActionMapper {  
  2.   
  3.     private static final Pattern p = Pattern  
  4.             .compile("([^\\.]+?)\\.([^\\.]+?)\\.([^\\.]+?)$");  
  5.   
  6.     @Override  
  7.     public ActionMapping getMapping(HttpServletRequest request,  
  8.             ConfigurationManager configManager) {  
  9.   
  10.         ActionMapping mapping = new ActionMapping();  
  11.   
  12.         final String method = request.getParameter("method");  
  13.         if (method == null) {  
  14.             throw new IllegalArgumentException("param method can not be null");  
  15.         }  
  16.         Matcher m = p.matcher(method);  
  17.         if (!m.matches()) {  
  18.             throw new RuntimeException("method" + method + " unmatch pattern:"  
  19.                     + p);  
  20.         }  
  21.   
  22.         mapping.setNamespace("/" + m.group(1));  
  23.         mapping.setName(m.group(2));  
  24.         mapping.setMethod(m.group(3));  
  25.   
  26.         return mapping;  
  27.     }  
  28.   
  29. }  

 2、在struts.xml增加配置,将默认的actionmapper换成自定义的

Java代码   收藏代码
  1. <bean type="org.apache.struts2.dispatcher.mapper.ActionMapper"  
  2.         name="api_rest" class="com.my.profile.struts.RestActionMapper" />  
  3. <constant name="struts.mapper.class" value="api_rest" />  

 

3、在web.xml中,这样将接收/api/rest 的所有请求

Java代码   收藏代码
  1. <filter>  
  2.         <filter-name>struts2</filter-name>  
  3.         <filter-class>  
  4.             org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  5.     </filter>  
  6.   
  7.     <filter-mapping>  
  8.         <filter-name>struts2</filter-name>  
  9.         <url-pattern>/api/rest</url-pattern>  
  10.     </filter-mapping>  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值