浅析struts2源码中对requset的封装

 

 当前台发送来HttpServletRequest的请求的时候,struts2是用StrutsPrepareAndExecuteFilter的doFilter来接收并处理的.

(现在web.xml的配置都是StrutsPrepareAndExecuteFilter了吧)

而struts2刚开始就对request和response进行了封装

 

prepare.setEncodingAndLocale(request, response);
prepare.createActionContext(request, response);

 设置编码:

        if (defaultEncoding != null) {
            encoding = defaultEncoding;
        }

 

       if (encoding != null) {
            try {
                request.setCharacterEncoding(encoding);
            } catch (Exception e) {
                LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e);
            }
        }

 

        Locale locale = null;
        if (defaultLocale != null) {
            locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());
        }

 

       if (locale != null) {
            response.setLocale(locale);
        }

 

而默认编码defaultEncoding,在初始化Dispatcher的时候被设置如下:

    @Inject(StrutsConstants.STRUTS_I18N_ENCODING)
    public void setDefaultEncoding(String val) {
        defaultEncoding = val;
    }

 STRUTS_I18N_ENCODING就是"struts.i18n.encoding"

在default.properties中struts.i18n.encoding=UTF-8

所以set request默认的编码是UTF-8

 

Locale默认是null,貌似是因为required=false(仅是推断,没有验证)

    @Inject(value=StrutsConstants.STRUTS_LOCALE, required=false)
    public void setDefaultLocale(String val) {
        defaultLocale = val;
    }

 

 

继续回到StrutsPrepareAndExecuteFilter的doFilter

开始生成新的request (StrutsRequestWrapper类型) 

request = prepare.wrapRequest(request);

 在Dispatcher中,直接返回StrutsRequestWrapper:

else {
            request = new StrutsRequestWrapper(request);
        }

        return request;

 

那么原先从前台传来的HttpServletrequest在哪呢

 

回到:

prepare.createActionContext(request, response);
 ActionContext ctx;
 ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
 stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext));
 ctx = new ActionContext(stack.getContext());
ActionContext.setContext(ctx);

 在方法里生成了一个新的ActionContext 而HttpServletRequest就存放ActionContext 中,

首HttpServletRequest由RequestMap接收

其次RequestMap ApplicationMap 又经过一次put放在Map<String,Object> extraContext中:

extraContext.put(StrutsStatics.HTTP_REQUEST, request);

而extraContext被putAll进ValueStack 的Map中,最终被ActionContext接收

 

 
 

 

获取HttpServletrequest的方法:

1)
ActionContext context = ActionContext.getContext();   
HttpServletRequest request=(HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST);   
HttpServletResponse response = (HttpServletResponse)context.get(ServletActionContext.HTTP_RESPONSE);   
2)
HttpServletRequest request = ServletActionContext.getRequest();

 

两种方法实际是相同 的:

 

    public static HttpServletRequest getRequest() {
        return (HttpServletRequest) ActionContext.getContext().get(HTTP_REQUEST);
    }

 

 

 

以上,不知道有哪点理解的不对  希望大家指出

你可能感兴趣的:(struts2)