`
jindw
  • 浏览: 501436 次
  • 性别: Icon_minigender_1
  • 来自: 初到北京
社区版块
存档分类
最新评论

简化一下struts1的Action---把苍蝇包起来咽:(

阅读更多
非常讨厌Struts1 Action的设计,一堆花俏的概念,没必要的复杂度.
但是工作关系,还非要使用这个垃圾,没办法,只好把苍蝇包起来咽下去.

做一个Action基类,SimpleAction ,把它封装的更像webwork.
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


/**
 * @author jindw
 * @xwork.package name = ""
 */
public final class SimpleAction extends AbstractAction {
    /**
     * Commons Logging instance.
     */
    protected static Log log = LogFactory.getLog(SimpleAction.class);

    /**
     * common result name define
     */
    public static final String SUCCESS = "success";

    public static final String ERROR = "error";

    public static final String INPUT = "input";

    /**
     * method cache
     */
    protected Map executeMap = new HashMap();

    protected Map executeArgumentTypesMap = new HashMap();

    public SimpleAction() {
        super();
        Method[] methods = this.getClass().getMethods();
        for (int i = 0; i < methods.length; i++) {

            Method method = methods[i];
            if (String.class != method.getReturnType()) {
                continue;
            }
            Class[] params = method.getParameterTypes();
            int argCount = 0;
            for (int j = 0; j < params.length; j++) {
                if (ActionForm.class.isAssignableFrom(params[j])) {
                    argCount++;
                } else if (HttpServletRequest.class.isAssignableFrom(params[j])) {
                    argCount++;
                } else if (HttpServletResponse.class
                        .isAssignableFrom(params[j])) {
                    argCount++;
                } else if (ActionMapping.class.isAssignableFrom(params[j])) {
                    argCount++;
                } else {
                    argCount = -1;
                    break;
                }
            }
            if (argCount >= 0) {
                executeMap.put(method.getName(), method);
                executeArgumentTypesMap.put(method.getName(), params);
            }
        }
        initialize();
    }

    protected void initialize() {
        Method[] methods = this.getClass().getMethods();
        for (int i = 0; i < methods.length; i++) {
            Class[] paramTypes = methods[i].getParameterTypes();
            if (paramTypes.length == 1) {
                String name = methods[i].getName();
                if (name.startsWith("set")) {
                    name = name.substring(3);
                    if (name.length() > 0) {
                        char fc = name.charAt(0);
                        if (Character.isUpperCase(fc)) {
                            name = Character.toLowerCase(fc)
                                    + name.substring(1);
                            //implement it eg:get from Spring Context
                            Object value = getBean(name);
                            if (value != null) {
                                try {
                                    methods[i].invoke(this,
                                            new Object[] { value });
                                } catch (Exception e) {
                                    log.info("set property error:", e);
                                }
                            }
                        }
                    }
                }
            }
        }
    }



    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // Get the method's name. This could be overridden in subclasses.
        String methodName = getMethodName(mapping, form);
        // Invoke the named method, and return the result
        String result = dispatchMethod(mapping, form, request, response,
                methodName);
        request.setAttribute("actionForm", form);
        if(result == null){
            return null;
        }else{
            return transformForward(mapping.findForward(result), request);
        }
    }

    /**
     * @param forward
     * @param request
     * @return
     */
    protected ActionForward transformForward(ActionForward forward,
            HttpServletRequest request) {
        if (forward == null) {
            return null;
        } else {
            StringBuffer buf = new StringBuffer(forward.getPath());
            boolean containsVariable = false;
            for (int k = 0, i = buf.indexOf("${", k); i >= 0; i = buf.indexOf(
                    "${", k), k = i) {
                int j = buf.indexOf("}", i);
                if (j > 0) {
                    containsVariable = true;
                    k = j;
                    String key = buf.substring(i + 2, j);
                    Object o = null;
                    if(key.indexOf('.')<0){
                        o=request.getAttribute(key);
                    }else{
                        String[] keys = key.split("[.]");
                        o=request.getAttribute(keys[0]);
                        for(int l = 1;l<keys.length;l++){
                            try
                            {
                                o = BeanUtilsBean.getInstance().getPropertyUtils().getProperty(o, keys[l].trim());
                            }
                            catch (Exception e)
                            {
                                log.debug("find property error:", e);
                                o = null;
                                break;
                            }
                            
                        }
                    }
                    buf.replace(i, j + 1, String.valueOf(o));
                }
            }
            if (containsVariable) {
                forward = new ActionForward(forward);
                forward.setPath(buf.toString());
                return forward;
            } else {
                return forward;
            }
        }
    }

    public static void main(String[] args) {
        StringBuffer buf = new StringBuffer("http://sdssfs${123}&{123}&${sd}");
        for (int k = 0, i = buf.indexOf("${", k); i >= 0; i = buf.indexOf("${",
                k), k = i) {
            int j = buf.indexOf("}", i);
            if (j > 0) {
                k = j;
                String key = buf.substring(i + 2, j);
                buf.replace(i, j + 1, "%" + key + "%");
            }
        }
        System.out.println(buf);
    }

    protected String dispatchMethod(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response,
            String methodName) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException {
        Method method = (Method) executeMap.get(methodName);
        Class[] argumentTypes = (Class[]) executeArgumentTypesMap
                .get(methodName);
        Object[] params = new Object[argumentTypes.length];
        for (int i = 0; i < params.length; i++) {
            Class type = argumentTypes[i];
            if (ActionForm.class.isAssignableFrom(type)) {
                if(type.isAssignableFrom(form.getClass())){
                    params[i] = form;
                }else{
                    throw new ClassCastException("action form type is:"+form.getClass()+";but required:"+type+";");
                }
            } else if (HttpServletRequest.class.isAssignableFrom(type)) {
                params[i] = request;
            } else if (HttpServletResponse.class.isAssignableFrom(type)) {
                params[i] = response;
            } else if (ActionMapping.class.isAssignableFrom(type)) {
                params[i] = mapping;
            }
        }
        return (String) method.invoke(this, params);
    }

    protected String getMethodName(ActionMapping mapping, ActionForm form) {
        String param = mapping.getParameter();
        if (param != null) {
            int i = param.indexOf("method=");
            if (i > 0) {
                int j = param.indexOf(i, ';');
                if (j >= 0) {
                    return param.substring(i + ("method=".length()), j).trim();
                } else {
                    return param.substring(i + ("method=".length())).trim();
                }
            } else {
                if (this.executeMap.containsKey(param)) {
                    return param;
                }
            }
        }
        return "execute";
    }


}


分享到:
评论

相关推荐

    struts-core-1.3.8-API文档-中文版.zip

    赠送jar包:struts-core-1.3.8.jar; 赠送原API文档:struts-core-1.3.8-javadoc.jar; 赠送源代码:struts-core-1.3.8-sources.jar; 赠送Maven依赖信息文件:struts-core-1.3.8.pom; 包含翻译后的API文档:struts...

    struts-spring-other-lib 等jar包

    struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-...

    struts2-json-plugin-2.3.24-API文档-中文版.zip

    赠送jar包:struts2-json-plugin-2.3.24.jar; 赠送原API文档:struts2-json-plugin-2.3.24-javadoc.jar; 赠送源代码:struts2-json-plugin-2.3.24-sources.jar; 赠送Maven依赖信息文件:struts2-json-plugin-...

    struts-2.0.14-lib Struts2开发包

    包含Struts2框架的核心类库,以及Struts2的第三方插件类库 struts2-core-2.0.14 xwork-2.0.7 ognl-2.6.11 commons-logging-1.0.4 freemarker-2.3.8 等等。

    struts-taglib-1.3.8.jar

    struts-taglib-1.3.8.jar struts-taglib-1.3.8.jar

    struts-2.3.30-all所有jar包

    struts-core-1.3.10.jar, struts2-cdi-plugin-2.3.30.jar, struts2-codebehind-plugin-2.3.30.jar, struts2-config-browser-plugin-2.3.30.jar, struts2-convention-plugin-2.3.30.jar, struts2-core-2.3.30.jar, ...

    struts2-core.jar

    struts2-core-2.0.1.jar, struts2-core-2.0.11.1.jar, struts2-core-2.0.11.2.jar, struts2-core-2.0.11.jar, struts2-core-2.0.12.jar, struts2-core-2.0.14.jar, struts2-core-2.0.5.jar, struts2-core-2.0.6.jar,...

    struts-2.3.24-apps.zip包测试Struts2 S2-048高危漏洞

    2017年7月7日,Apache Struts发布最新的安全公告,Apache Struts2-strus1-plugin插件存在远程代码执行的高危漏洞,漏洞编号为CVE-2017-9791(S2-048),主要受影响的Struts版本为:2.3.x。 攻击者可以构造恶意的字段值...

    struts1.38包,struts-core-1.3.8.jar

    struts1.38包,struts-core-1.3.8.jarstruts1.38包,struts-core-1.3.8.jar

    官网最新struts的jar包:struts-2.3.3-all.zip

    绝对是官网最新版本2012年5月9日下载的,方便大家使用,很不错的资源,期待大家分享,只因我们都是ssh人~(所有相关jar包在:struts-2.3.3-all.zip\struts-2.3.3\lib)docs中都有相应的例子,会告诉你怎么用!...

    struts-2.5.2-all所有jar包

    struts2-bean-validation-plugin-2.5.2.jar, struts2-cdi-plugin-2.5.2.jar, struts2-config-browser-plugin-2.5.2.jar, struts2-convention-plugin-2.5.2.jar, struts2-core-2.5.2.jar, struts2-dwr-plugin-2.5.2....

    struts2-2.5源码包含jar包

    struts2-2.5源码包含jar包struts2-2.5源码包含jar包struts2-2.5源码包含jar包struts2-2.5源码包含jar包struts2-2.5源码包含jar包struts2-2.5源码包含jar包struts2-2.5源码包含jar包struts2-2.5源码包含jar包struts2-...

    struts-2.3.7-all

    struts-2.3.7-all jar包

    Struts2开发常用jar包

    包含struts2-core-2.5.10.1.jar,struts2-jfreechart-plugin-2.5.10.1.jar,struts2-json-plugin-2.5.10.1.jar,struts2-junit-plugin-2.5.10.1.jar,struts2-bean-validation-plugin-2.5.10.1.jar,struts2-cdi-...

    struts2-core-2.5.18.jar包下载

    struts2-core-2.5.18.jar包下载,支持struts2的类库下载

    struts-1.3.8-all.zip

    struts-1.3.8-all.zip 官方完整包

    struts-2.3.34-all.part2.rar

    struts-2.3.34-all.rar,包括app,docs,lib,src

    struts-2.5.2-all.zip

    struts-2.5.2-all 所包含的所有jar包

    struts2-spring-plugin-2.3.15.2.jar ; struts2-json-plugin-2.3.16.3.jar

    struts2-spring-plugin-2.3.15.2.jar ; struts2-json-plugin-2.3.16.3.jarstruts2-spring-plugin-2.3.15.2.jar ; struts2-json-plugin-2.3.16.3.jar

    【Struts2】〖所有依赖jar包〗struts-2.3.37-lib

    【Struts2】〖所有依赖jar包〗struts-2.3.37-lib 我寻见一片海 碧蓝且耀着光 大片船只航行其上 都向着远方 Shared by Foriver_江河 © 1997-8023 江河 All Rights Reserved.

Global site tag (gtag.js) - Google Analytics