最近在项目中要做http api,要求提供的url是 http://***.domain.com/api/rest?sign={签名}&method={namespace}.{action名}.{调用方法名}&......
类似淘宝的top api url 风格,一个url,根据参数不同,映射到不同的控制器。
实现方法详细:
1、实现自己的ActionMapper,通过method参数将请求转发到具体的action
- public class RestActionMapper extends DefaultActionMapper {
- private static final Pattern p = Pattern
- .compile("([^\\.]+?)\\.([^\\.]+?)\\.([^\\.]+?)$");
- @Override
- public ActionMapping getMapping(HttpServletRequest request,
- ConfigurationManager configManager) {
- ActionMapping mapping = new ActionMapping();
- final String method = request.getParameter("method");
- if (method == null) {
- throw new IllegalArgumentException("param method can not be null");
- }
- Matcher m = p.matcher(method);
- if (!m.matches()) {
- throw new RuntimeException("method" + method + " unmatch pattern:"
- + p);
- }
- mapping.setNamespace("/" + m.group(1));
- mapping.setName(m.group(2));
- mapping.setMethod(m.group(3));
- return mapping;
- }
- }
2、在struts.xml增加配置,将默认的actionmapper换成自定义的
- <bean type="org.apache.struts2.dispatcher.mapper.ActionMapper"
- name="api_rest" class="com.my.profile.struts.RestActionMapper" />
- <constant name="struts.mapper.class" value="api_rest" />
3、在web.xml中,这样将接收/api/rest 的所有请求
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/api/rest</url-pattern>
- </filter-mapping>