当前位置: 代码迷 >> Web前端 >> 运用Map参数的Webx3扩展
  详细解决方案

运用Map参数的Webx3扩展

热度:181   发布时间:2012-08-29 08:40:14.0
使用Map参数的Webx3扩展
因Webx3是开源的,所以把这个简单的Webx3扩展发在博客上。

很久没弄Web框架,因要将服务框架的控制台换成Webx3,就折腾一下,

一种使用Webx3的方式如下:

1. 注入HttpServletRequest

public class ProvidersAction extends BaseAction {

    @Autowired
    private ProviderDAO providerDAO; // 注入DAO依赖

    @Autowired
    private HttpServletRequest request; // 注入HTTP请求

    public void execute(Context context, Navigator navigator) throws Exception { // 传入模板变量上下文,跳转导航器
        String serviceName = request.getParameter("serviceName"); // 从请求中获取参数
        List<Provider> providers = providerDAO.findProvidersByServiceName(serviceName); // 从数据库查询数据
        context.put("providers", providers); // 输出模板变量
    }

}


这样写没有问题,但感觉不是很优雅,过多的强依赖于Request等容器对象。

Webx3还提供另外一种写法:

2. 基于注解自动从请求中获取参数

public class ProvidersAction extends BaseAction {

    @Autowired
    private ProviderDAO providerDAO; 

    // 基于注解自动从请求中获取参数,可以减少对Request的依赖
    public void execute(@Param(“serviceName”) String serviceName, Context context, Navigator navigator) throws Exception {
        List<Provider> providers = providerDAO.findProvidersByServiceName(serviceName);
        context.put("providers", providers);
    }

}


但感觉这样写,注解一大把,看起来也很复杂,而且依赖Param,Context,Navigator等框架类。

因为webx3提供了DataResolver扩展点,基于扩展点将写法改成了:

3. 使用标准Map接口封装所有输入输出

public class ProvidersAction extends BaseAction {

    @Autowired
    private ProviderDAO providerDAO; // 注入DAO依赖

    // 使用标准Map接口封装所有输入输出,get为输入,put为输出
    public void execute(Map<String, Object> context) throws Exception {
        String serviceName = (String) context.get("serviceName");
        List<Provider> providers = providerDAO.findProvidersByServiceName(serviceName);
        context.put("providers", providers);
    }

}


在webx3中配置:
<services:data-resolver xmlns="http://www.alibaba.com/schema/services/data-resolver/factories">
    <dr-factories:factory class="com.alibaba.citrus.extension.resolver.MapDataResolverFactory" />
</services:data-resolver>


扩展点实现类如下:
package com.alibaba.citrus.extension.resolver;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.dataresolver.DataResolver;
import com.alibaba.citrus.service.dataresolver.DataResolverContext;
import com.alibaba.citrus.service.dataresolver.DataResolverFactory;
import com.alibaba.citrus.service.moduleloader.ModuleInfo;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.TurbineRunDataInternal;
import com.alibaba.citrus.turbine.util.TurbineUtil;

/**
 * MapDataResolverFactory
 * 
 * @author william.liangf
 */
public class MapDataResolverFactory implements DataResolverFactory {

    @Autowired
    private HttpServletRequest request;

    public DataResolver getDataResolver(DataResolverContext context) {
        if (Map.class == context.getTypeInfo().getRawType()) {
            return new MapDataResolver(context);
        }
        return null;
    }
    
    public class MapDataResolver implements DataResolver {
        
        public final DataResolverContext context;

        public MapDataResolver(DataResolverContext context){
            this.context = context;
        }

        public Object resolve() {
            TurbineRunDataInternal rundata = (TurbineRunDataInternal) TurbineUtil.getTurbineRunData(request);
            return new ParameterMap(request, rundata.getContext(), rundata);
        }

    }
    
}


package com.alibaba.citrus.extension.resolver;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.TurbineRunDataInternal;

/**
 * ParameterMap
 * 
 * @author william.liangf
 */
public class ParameterMap implements Map<String, Object> {
    
    private static final String CONTEXT_PREFIX = "context.";

    private static final String PARAMETER_PREFIX = "parameter.";
    
    private static final String REQUEST_PREFIX = "request.";
    
    private static final String SESSION_PREFIX = "session.";
    
    private static final String COOKIE_PREFIX = "cookie.";
    
    private static final String APPLICATION_PREFIX = "application.";

    private static final String NAVIGATOR_PREFIX = "navigator.";

    private static final String TARGET_KEY = "target";

    private static final String FORWARD_KEY = "forward";

    private static final String REDIRECT_KEY = "redirect";

    private static final String REDIRECTED_KEY = "redirected";

    private final HttpServletRequest request;
    
    private final Context context;
    
    private final TurbineRunDataInternal navigator;

    public ParameterMap(HttpServletRequest request, Context context, TurbineRunDataInternal navigator){
        super();
        this.request = request;
        this.context = context;
        this.navigator = navigator;
    }

    public int size() {
        return 0;
    }

    public boolean isEmpty() {
        return false;
    }

    public boolean containsValue(Object value) {
        if (value == null) {
            return false;
        }
        Set<String> keys = context.keySet();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                if (value.equals(context.get(key))) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean containsKey(Object key) {
        String k = (String) key;
        if (k == null || k.length() == 0) {
            return false;
        }
        return context.containsKey(k) || request.getParameter(k) != null;
    }

    public Object get(Object key) {
        String k = (String) key;
        if (k == null || k.length() == 0) {
            return null;
        }
        if (k.startsWith(CONTEXT_PREFIX)) {
            return context.get(k.substring(CONTEXT_PREFIX.length()));
        } else if (k.startsWith(PARAMETER_PREFIX)) {
            return getParameterValue(k.substring(PARAMETER_PREFIX.length()));
        } else if (k.startsWith(REQUEST_PREFIX)) {
            return request.getAttribute(k.substring(REQUEST_PREFIX.length()));
        } else if (k.startsWith(SESSION_PREFIX)) {
            return request.getSession().getAttribute(k.substring(SESSION_PREFIX.length()));
        } else if (k.startsWith(COOKIE_PREFIX)) {
            return getCookieValue(k.substring(COOKIE_PREFIX.length()));
        } else if (k.startsWith(APPLICATION_PREFIX)) {
            return request.getSession().getServletContext().getAttribute(k.substring(APPLICATION_PREFIX.length()));
        } else if (TARGET_KEY.equals(k) || (NAVIGATOR_PREFIX + TARGET_KEY).equals(k)) {
            return navigator.getTarget();
        } else if (FORWARD_KEY.equals(k) || (NAVIGATOR_PREFIX + FORWARD_KEY).equals(k)) {
            return navigator.getRedirectTarget();
        } else if (REDIRECT_KEY.equals(k) || (NAVIGATOR_PREFIX + REDIRECT_KEY).equals(k)) {
            return navigator.getRedirectLocation();
        } else if (REDIRECTED_KEY.equals(k) || (NAVIGATOR_PREFIX + REDIRECTED_KEY).equals(k)) {
            return navigator.isRedirected();
        } else {
            Object value = context.get(k);
            if (value == null) {
                value = getParameterValue(k);
                if (value == null) {
                    value = request.getAttribute(k);
                    if (value == null) {
                        value = request.getSession().getAttribute(k);
                        if (value == null) {
                            value = getCookieValue(k);
                            if (value == null) {
                                value = request.getSession().getServletContext().getAttribute(k);
                            }
                        }
                    }
                }
            }
            return value;
        }
    }
    
    private Object getParameterValue(String key) {
        String[] values = request.getParameterValues(key);
        if (values == null || values.length == 0) {
            return null;
        } else if (values.length == 1) {
            return values[0];
        } else  {
            return values;
        }
    }
    
    private Object getCookieValue(String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (key.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public Object put(String key, Object value) {
        if (key == null || key.length() == 0) {
            return null;
        }
        if (TARGET_KEY.equals(key) || (NAVIGATOR_PREFIX + TARGET_KEY).equals(key)) {
            navigator.setTarget((String) value);
            return null;
        } else if (FORWARD_KEY.equals(key) || (NAVIGATOR_PREFIX + FORWARD_KEY).equals(key)) {
            navigator.setRedirectTarget((String) value);
            return null;
        } else if (REDIRECT_KEY.equals(key) || (NAVIGATOR_PREFIX + REDIRECT_KEY).equals(key)) {
            navigator.setRedirectLocation((String) value);
            return null;
        } else {
            if (key.startsWith(REQUEST_PREFIX)) {
                key = key.substring(APPLICATION_PREFIX.length());
                Object old = request.getAttribute(key);
                if (value == null) {
                    request.removeAttribute(key);
                } else {
                    request.setAttribute(key, value);
                }
                return old;
            } else if (key.startsWith(SESSION_PREFIX)) {
                key = key.substring(APPLICATION_PREFIX.length());
                Object old = request.getSession().getAttribute(key);
                if (value == null) {
                    request.getSession().removeAttribute(key);
                } else {
                    request.getSession().setAttribute(key, value);
                }
                return old;
            } else if (key.startsWith(COOKIE_PREFIX)) {
                key = key.substring(APPLICATION_PREFIX.length());
                Object old = null;
                Cookie[] cookies = request.getCookies();
                if (cookies != null && cookies.length > 0) {
                    for (Cookie cookie : cookies) {
                        if (key.equals(cookie.getName())) {
                            old = cookie.getValue();
                            if (value == null) {
                                cookie.setMaxAge(-1);
                            } else {
                                cookie.setValue((String) value);
                            }
                            break;
                        }
                    }
                }
                return old;
            } else if (key.startsWith(APPLICATION_PREFIX)) {
                key = key.substring(APPLICATION_PREFIX.length());
                Object old = request.getSession().getServletContext().getAttribute(key);
                if (value == null) {
                    request.getSession().getServletContext().removeAttribute(key);
                } else {
                    request.getSession().getServletContext().setAttribute(key, value);
                }
                return old;
            } else {
                if (key.startsWith(APPLICATION_PREFIX)) {
                    key = key.substring(APPLICATION_PREFIX.length());
                }
                Object old = context.get(key);
                if (value == null) {
                    context.remove(key);
                } else {
                    context.put(key, value);
                }
                return old;
            }
        }
    }

    public Object remove(Object key) {
        return put((String) key, null);
    }

    public void putAll(Map<? extends String, ? extends Object> map) {
        if (map != null && map.size() > 0) {
            for (Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
                put(entry.getKey(), entry.getValue());
            }
        }
    }

    public void clear() {
        Set<String> keys = context.keySet();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                context.remove(key);
            }
        }
    }

    public Set<String> keySet() {
        return context.keySet();
    }

    public Collection<Object> values() {
        Set<String> keys = context.keySet();
        Set<Object> values = new HashSet<Object>();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                values.add(context.get(key));
            }
        }
        return values;
    }

    public Set<Entry<String, Object>> entrySet() {
        Set<String> keys = context.keySet();
        Set<Entry<String, Object>> entries = new HashSet<Entry<String, Object>>();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                entries.add(new ParameterEntry(key));
            }
        }
        return entries;
    }
    
    private class ParameterEntry implements Entry<String, Object> {

        private final String key;
        
        private volatile Object value;

        public ParameterEntry(String key){
            this.key = key;
            this.value = ParameterMap.this.get(key);
        }

        public String getKey() {
            return key;
        }

        public Object getValue() {
            return value;
        }

        public Object setValue(Object value) {
            this.value = value;
            return ParameterMap.this.put(key, value);
        }

    }

}


另外,还有一种办法是,

4. 通过asm字节码分析参数名称,去掉上面第二种写法的注解

public class ProvidersAction extends BaseAction {

    @Autowired
    private ProviderDAO providerDAO; 

         // 基于asm字节码分析,自动获取参数的名称为serviceName,但感觉有点奇技淫巧,
// 因为该Action为实现类,而非接口,所以其参数名,在字节码的code区,作为局部变量名有记录
    public void execute(String serviceName, Context context, Navigator navigator) throws Exception {
                   List<Provider> providers = providerDAO.findProvidersByServiceName(serviceName);
                   context.put("providers", providers);
         }

}
1 楼 haty01 2012-02-28  
菜鸟入门中,多谢 
  相关解决方案