Struts2学习笔记4

Struts2将Result列为一个独立的层次,可以说是整个Struts2的Action层架构设计中的另外一个精华所在。Result之所以成为一个层次,其实是为了解决MVC框架中,如何从Control层转向View层这样一个问题而存在的。所以,接下来我们详细讨论一下Result的方方面面。

Result的职责

Result作为一个独立的层次存在,必然有其存在的价值,它也必须完成它所在的层次的职责。Result是为了解决如何从Control层转向View层这样一个问题而存在的,那么Result最大的职责,就是架起Action到View的桥梁。具体来说,我把这些职责大概分成以下几个方面:

封装跳转逻辑

Result的首要职责,是封装Action层到View层的跳转逻辑。之前我们已经反复提到,Struts2的Action是一个与Web容器无关的POJO。所以,在Action执行完毕之后,框架需要把代码的执行权重新交还给Web容器,并转向到相应的页面或者其他类型的View层。
而这个跳转逻辑,就由Result来完成。这样,好处也是显而易见的,对Action屏蔽任何Web容器的相关信息,使得每个层次更加清晰。

View层的显示类型非常多,有最常见的JSP、当下非常流行的Freemarker/Velocity模板、Redirect到一个新的地址、文本流、图片流、甚至是JSON对象等等。所以Result层的独立存在,就能够对这些显示类型进行区分,并封装合理的跳转逻辑。

以JSP转向为例,在Struts2自带的ServletDispatcherResult中就存在着核心的JSP跳转逻辑:

Java代码 复制代码
  1. HttpServletRequest request = ServletActionContext.getRequest();   
  2. RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);   
  3.   
  4. ....   
  5.   
  6. dispatcher.forward(request, response);  
HttpServletRequest request = ServletActionContext.getRequest();
RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

....

dispatcher.forward(request, response);



再以Redirect重定向为例,在Struts2自带的ServletRedirectResult中,也同样存在着重定向的核心代码:

Java代码 复制代码
  1. HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);   
  2.   
  3. ....   
  4.   
  5. response.sendRedirect(finalLocation);  
HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);

....

response.sendRedirect(finalLocation);



由此可见,绝大多数的Result,都封装了与Web容器相关的跳转逻辑,由于这些逻辑往往需要和Servlet对象打交道,所以,遵循Struts2的基本原则,将它作为一个独立的层次,从而将Action从Web容器中解放出来。

准备显示数据

之前提到,View层的展现方式很多,除了传统的JSP以外,还有类似Freemarker/Velocity这样的模板。根据模板显示的基本原理,需要将预先定义好的模板(Template)和需要展示的数据(Model)组织起来,交给模板引擎,才能够正确显示。而这部分工作,就由Result层来完成。

以Struts2自带的FreemarkerResult为例,在Result中,就存在着为模板准备数据的逻辑代码:

Java代码 复制代码
  1. protected TemplateModel createModel() throws TemplateModelException {   
  2.     ServletContext servletContext = ServletActionContext.getServletContext();   
  3.     HttpServletRequest request = ServletActionContext.getRequest();   
  4.     HttpServletResponse response = ServletActionContext.getResponse();   
  5.     ValueStack stack = ServletActionContext.getContext().getValueStack();   
  6.   
  7.     Object action = null;   
  8.     if(invocation!= null ) action = invocation.getAction(); //Added for NullPointException   
  9.     return freemarkerManager.buildTemplateModel(stack, action, servletContext, request, response, wrapper);   
  10. }  
protected TemplateModel createModel() throws TemplateModelException {
    ServletContext servletContext = ServletActionContext.getServletContext();
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    ValueStack stack = ServletActionContext.getContext().getValueStack();

    Object action = null;
    if(invocation!= null ) action = invocation.getAction(); //Added for NullPointException
    return freemarkerManager.buildTemplateModel(stack, action, servletContext, request, response, wrapper);
}



有兴趣的读者可以顺着思路去看源码,看看这些Result到底是如何获取各种对象的值的。

控制输出行为

有的时候,针对同一种类型的View展示,我们可能会有不同的输出行为。具体来说,可能有时候,我们需要对输出流指定特定的BufferSize、Encoding等等。Result层,作为一个独立的层次,可以提供极大的扩展性,从而保证我们能够定义自己期望的输出类型。

以Struts2自带的HttpHeaderResult为例:

Java代码 复制代码
  1. public void execute(ActionInvocation invocation) throws Exception {   
  2.     HttpServletResponse response = ServletActionContext.getResponse();   
  3.   
  4.     if (status != -1) {   
  5.         response.setStatus(status);   
  6.     }   
  7.   
  8.     if (headers != null) {   
  9.         ValueStack stack = ActionContext.getContext().getValueStack();   
  10.   
  11.         for (Iterator iterator = headers.entrySet().iterator();   
  12.              iterator.hasNext();) {   
  13.             Map.Entry entry = (Map.Entry) iterator.next();   
  14.             String value = (String) entry.getValue();   
  15.             String finalValue = parse ? TextParseUtil.translateVariables(value, stack) : value;   
  16.             response.addHeader((String) entry.getKey(), finalValue);   
  17.         }   
  18.     }   
  19. }  
public void execute(ActionInvocation invocation) throws Exception {
    HttpServletResponse response = ServletActionContext.getResponse();

    if (status != -1) {
        response.setStatus(status);
    }

    if (headers != null) {
        ValueStack stack = ActionContext.getContext().getValueStack();

        for (Iterator iterator = headers.entrySet().iterator();
             iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String value = (String) entry.getValue();
            String finalValue = parse ? TextParseUtil.translateVariables(value, stack) : value;
            response.addHeader((String) entry.getKey(), finalValue);
        }
    }
}



我们可以在这里添加我们自定义的内容到HttpHeader中去,从而控制Http的输出。

Result的定义

让我们来看看Result的接口定义:

Java代码 复制代码
  1. public interface Result extends Serializable {   
  2.   
  3.     /**  
  4.      * Represents a generic interface for all action execution results, whether that be displaying a webpage, generating  
  5.      * an email, sending a JMS message, etc.  
  6.      */  
  7.     public void execute(ActionInvocation invocation) throws Exception;   
  8. }  
public interface Result extends Serializable {

    /**
     * Represents a generic interface for all action execution results, whether that be displaying a webpage, generating
     * an email, sending a JMS message, etc.
     */
    public void execute(ActionInvocation invocation) throws Exception;
}



这个接口定义非常简单,通过传入ActionInvocation,执行一段逻辑。我们来看看Struts2针对这个接口实现的一个抽象类,它规定了许多默认实现:

Java代码 复制代码
  1. public abstract class StrutsResultSupport implements Result, StrutsStatics {   
  2.   
  3.     private static final Log _log = LogFactory.getLog(StrutsResultSupport.class);   
  4.   
  5.     /** The default parameter */  
  6.     public static final String DEFAULT_PARAM = "location";   
  7.   
  8.     private boolean parse;   
  9.     private boolean encode;   
  10.     private String location;   
  11.     private String lastFinalLocation;   
  12.   
  13.     public StrutsResultSupport() {   
  14.         this(null, true, false);   
  15.     }   
  16.   
  17.     public StrutsResultSupport(String location) {   
  18.         this(location, true, false);   
  19.     }   
  20.   
  21.     public StrutsResultSupport(String location, boolean parse, boolean encode) {   
  22.         this.location = location;   
  23.         this.parse = parse;   
  24.         this.encode = encode;   
  25.     }   
  26.   
  27.     // setter method 省略   
  28.     
  29.     /**  
  30.      * Implementation of the <tt>execute</tt> method from the <tt>Result</tt> interface. This will call  
  31.      * the abstract method {@link #doExecute(String, ActionInvocation)} after optionally evaluating the  
  32.      * location as an OGNL evaluation.  
  33.      *  
  34.      * @param invocation the execution state of the action.  
  35.      * @throws Exception if an error occurs while executing the result.  
  36.      */  
  37.     public void execute(ActionInvocation invocation) throws Exception {   
  38.         lastFinalLocation = conditionalParse(location, invocation);   
  39.         doExecute(lastFinalLocation, invocation);   
  40.     }   
  41.   
  42.     /**  
  43.      * Parses the parameter for OGNL expressions against the valuestack  
  44.      *  
  45.      * @param param The parameter value  
  46.      * @param invocation The action invocation instance  
  47.      * @return The resulting string  
  48.      */  
  49.     protected String conditionalParse(String param, ActionInvocation invocation) {   
  50.         if (parse && param != null && invocation != null) {   
  51.             return TextParseUtil.translateVariables(param, invocation.getStack(),   
  52.                     new TextParseUtil.ParsedValueEvaluator() {   
  53.                         public Object evaluate(Object parsedValue) {   
  54.                             if (encode) {   
  55.                                 if (parsedValue != null) {   
  56.                                     try {   
  57.                                         // use UTF-8 as this is the recommended encoding by W3C to   
  58.                                         // avoid incompatibilities.   
  59.                                         return URLEncoder.encode(parsedValue.toString(), "UTF-8");   
  60.                                     }   
  61.                                     catch(UnsupportedEncodingException e) {   
  62.                                         _log.warn("error while trying to encode ["+parsedValue+"]", e);   
  63.                                     }   
  64.                                 }   
  65.                             }   
  66.                             return parsedValue;   
  67.                         }   
  68.             });   
  69.         } else {   
  70.             return param;   
  71.         }   
  72.     }   
  73.   
  74.     /**  
  75.      * Executes the result given a final location (jsp page, action, etc) and the action invocation  
  76.      * (the state in which the action was executed). Subclasses must implement this class to handle  
  77.      * custom logic for result handling.  
  78.      *  
  79.      * @param finalLocation the location (jsp page, action, etc) to go to.  
  80.      * @param invocation    the execution state of the action.  
  81.      * @throws Exception if an error occurs while executing the result.  
  82.      */  
  83.     protected abstract void doExecute(String finalLocation, ActionInvocation invocation) throws Exception;   
  84. }  
public abstract class StrutsResultSupport implements Result, StrutsStatics {

    private static final Log _log = LogFactory.getLog(StrutsResultSupport.class);

    /** The default parameter */
    public static final String DEFAULT_PARAM = "location";

    private boolean parse;
    private boolean encode;
    private String location;
    private String lastFinalLocation;

    public StrutsResultSupport() {
        this(null, true, false);
    }

    public StrutsResultSupport(String location) {
        this(location, true, false);
    }

    public StrutsResultSupport(String location, boolean parse, boolean encode) {
        this.location = location;
        this.parse = parse;
        this.encode = encode;
    }

    // setter method 省略
 
    /**
     * Implementation of the <tt>execute</tt> method from the <tt>Result</tt> interface. This will call
     * the abstract method {@link #doExecute(String, ActionInvocation)} after optionally evaluating the
     * location as an OGNL evaluation.
     *
     * @param invocation the execution state of the action.
     * @throws Exception if an error occurs while executing the result.
     */
    public void execute(ActionInvocation invocation) throws Exception {
        lastFinalLocation = conditionalParse(location, invocation);
        doExecute(lastFinalLocation, invocation);
    }

    /**
     * Parses the parameter for OGNL expressions against the valuestack
     *
     * @param param The parameter value
     * @param invocation The action invocation instance
     * @return The resulting string
     */
    protected String conditionalParse(String param, ActionInvocation invocation) {
        if (parse && param != null && invocation != null) {
            return TextParseUtil.translateVariables(param, invocation.getStack(),
                    new TextParseUtil.ParsedValueEvaluator() {
                        public Object evaluate(Object parsedValue) {
                            if (encode) {
                                if (parsedValue != null) {
                                    try {
                                        // use UTF-8 as this is the recommended encoding by W3C to
                                        // avoid incompatibilities.
                                        return URLEncoder.encode(parsedValue.toString(), "UTF-8");
                                    }
                                    catch(UnsupportedEncodingException e) {
                                        _log.warn("error while trying to encode ["+parsedValue+"]", e);
                                    }
                                }
                            }
                            return parsedValue;
                        }
            });
        } else {
            return param;
        }
    }

    /**
     * Executes the result given a final location (jsp page, action, etc) and the action invocation
     * (the state in which the action was executed). Subclasses must implement this class to handle
     * custom logic for result handling.
     *
     * @param finalLocation the location (jsp page, action, etc) to go to.
     * @param invocation    the execution state of the action.
     * @throws Exception if an error occurs while executing the result.
     */
    protected abstract void doExecute(String finalLocation, ActionInvocation invocation) throws Exception;
}



很显然,这个默认实现是为那些类似JSP,Freemarker或者Redirect这样的页面跳转的Result而准备的一个基类,它规定了Result将要跳转到的具体页面的位置、是否需要解析参数,等等。

如果我们试图编写自定义的Result,我们可以实现Result接口,并在struts.xml中进行声明:

Java代码 复制代码
  1. public class CustomerResult implements Result {   
  2.   
  3.     public void execute(ActionInvocation invocation) throws Exception {   
  4.     // write your code here   
  5. }   
  6. }  
public class CustomerResult implements Result {

    public void execute(ActionInvocation invocation) throws Exception {
    // write your code here
}
}


Xml代码 复制代码
  1. <result-type name="customerResult" class="com.javaeye.struts2.CustomerResult"/>  
<result-type name="customerResult" class="com.javaeye.struts2.CustomerResult"/>



常用的Result

接下来,大致介绍一下Struts2内部已经实现的Result,并看看他们是如何工作的。

dispatcher

Xml代码 复制代码
  1. <result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>  
<result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>



dispatcher主要用于返回JSP,HTML等以页面为基础View视图,这个也是Struts2默认的Result类型。

在使用dispatcher时,唯一需要指定的,是JSP或者HTML页面的位置,这个位置将被用于定位返回的页面:

Xml代码 复制代码
  1. <result name="success">/index.jsp</result>  
<result name="success">/index.jsp</result>



而Struts2本身也没有对dispatcher做出什么特殊的处理,只是简单的使用Servlet API进行forward。

freemarker / velocity

Xml代码 复制代码
  1. <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>  
  2. <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>  
<result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
<result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>



随着模板技术的越来越流行,使用Freemarker或者Velocity模板进行View层展示的开发者越来越多。Struts2同样为模板作为Result做出了支持。由于模板的显示需要模板(Template)与数据(Model)的紧密配合,所以在Struts2中,这两个Result的主要工作是为模板准备数据。

以Freemarker为例,我们来看看它是如何为模板准备数据的:

Java代码 复制代码
  1. public void doExecute(String location, ActionInvocation invocation) throws IOException, TemplateException {   
  2.     this.location = location;   
  3.     this.invocation = invocation;   
  4.     this.configuration = getConfiguration();   
  5.     this.wrapper = getObjectWrapper();   
  6.   
  7.     // 获取模板的位置   
  8.     if (!location.startsWith("/")) {   
  9.         ActionContext ctx = invocation.getInvocationContext();   
  10.         HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);   
  11.         String base = ResourceUtil.getResourceBase(req);   
  12.         location = base + "/" + location;   
  13.     }   
  14.   
  15.     // 得到模板   
  16.     Template template = configuration.getTemplate(location, deduceLocale());   
  17.     // 为模板准备数据   
  18.     TemplateModel model = createModel();   
  19.   
  20.     // 根据模板和数据进行输出   
  21.     // Give subclasses a chance to hook into preprocessing   
  22.     if (preTemplateProcess(template, model)) {   
  23.         try {   
  24.             // Process the template   
  25.             template.process(model, getWriter());   
  26.         } finally {   
  27.             // Give subclasses a chance to hook into postprocessing   
  28.             postTemplateProcess(template, model);   
  29.         }   
  30.     }   
  31. }  
public void doExecute(String location, ActionInvocation invocation) throws IOException, TemplateException {
    this.location = location;
    this.invocation = invocation;
    this.configuration = getConfiguration();
    this.wrapper = getObjectWrapper();

    // 获取模板的位置
    if (!location.startsWith("/")) {
        ActionContext ctx = invocation.getInvocationContext();
        HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
        String base = ResourceUtil.getResourceBase(req);
        location = base + "/" + location;
    }

    // 得到模板
    Template template = configuration.getTemplate(location, deduceLocale());
    // 为模板准备数据
    TemplateModel model = createModel();

    // 根据模板和数据进行输出
    // Give subclasses a chance to hook into preprocessing
    if (preTemplateProcess(template, model)) {
        try {
            // Process the template
            template.process(model, getWriter());
        } finally {
            // Give subclasses a chance to hook into postprocessing
            postTemplateProcess(template, model);
        }
    }
}



从源码中,我们可以看到,createModel()方法真正为模板准备需要显示的数据。而之前,我们已经看到过这个方法的源码,这个方法所准备的数据不仅包含ValueStack中的数据,还包含了被封装过的HttpServletRequest,HttpSession等对象的数据。从而使得模板能够以它特定的语法输出这些数据。

Velocity的Result也是类似,有兴趣的读者可以顺着思路继续深究源码。

redirect

Xml代码 复制代码
  1. <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>  
  2. <result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>  
  3. <result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>  
<result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>
<result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>
<result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>



如果你在Action执行完毕后,希望执行另一个Action,有2种方式可供选择。一种是forward,另外一种是redirect。有关forward和redirect的区别,这里我就不再展开,这应该属于Java程序员的基本知识。在Struts2中,分别对应这两种方式的Result,就是chain和redirect。

先来谈谈redirect,既然是重定向,那么源地址与目标地址之间是2个不同的HttpServletRequest。所以目标地址将无法通过ValueStack等Struts2的特性来获取源Action中的数据。如果你需要对目标地址传递参数,那么需要在目标地址url或者配置文件中指出:

Xml代码 复制代码
  1. <!--   
  2.    The redirect-action url generated will be :   
  3.    /genReport/generateReport.jsp?reportType=pie&width=100&height=100  
  4.    -->  
  5.    <action name="gatherReportInfo" class="...">  
  6.       <result name="showReportResult" type="redirect">  
  7.          <param name="location">generateReport.jsp</param>  
  8.          <param name="namespace">/genReport</param>  
  9.          <param name="reportType">pie</param>  
  10.          <param name="width">${width}</param>  
  11.          <param name="height">${height}</param>  
  12.       </result>  
  13.    </action>  
<!--
   The redirect-action url generated will be :
   /genReport/generateReport.jsp?reportType=pie&width=100&height=100
   -->
   <action name="gatherReportInfo" class="...">
      <result name="showReportResult" type="redirect">
         <param name="location">generateReport.jsp</param>
         <param name="namespace">/genReport</param>
         <param name="reportType">pie</param>
         <param name="width">${width}</param>
         <param name="height">${height}</param>
      </result>
   </action>



同时,Redirect的Result支持在配置文件中,读取并解析源Action中ValueStack的值,并成为参数传递到Redirect的地址中。上面给出的例子中,width和height就是ValueStack中的值。

chain

Xml代码 复制代码
  1. <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>  
<result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>



再来谈谈chain,之前提到,chain其实只是在一个action执行完毕之后,forward到另外一个action,所以他们之间是共享HttpServletRequest的。在使用chain作为Result时,往往会配合使用ChainingInterceptor。有关ChainingInterceptor,Struts2的Reference说明了其作用:

Struts2 Reference 写道
If you need to copy the properties from your previous Actions in the chain to the current action, you should apply the ChainingInterceptor. The Interceptor will copy the original parameters from the request, and the ValueStack is passed in to the target Action. The source Action is remembered by the ValueStack, allowing the target Action to access the properties of the preceding Action(s) using the ValueStack, and also makes these properties available to the final result of the chain, such as the JSP or Velocity page.



也就是说,ChainingInterceptor的作用是在Action直接传递数据。事实上,源Action中ValueStack的数据会被做一次Copy,这样,2个Action中的数据都在ValueStack中,使得对于前台来说,通过ValueStack来取数据,是透明而共享的。

chain这个Result有一些常用的使用情景,这点在Struts2的Reference中也有说明:

Struts2 Reference 写道

One common use of Action chaining is to provide lookup lists (like for a dropdown list of states). Since these Actions get put on the ValueStack, their properties will be available in the view. This functionality can also be done using the ActionTag to execute an Action from the display page.



比如说,一张页面中,你可能有许多数据要显示,而某些数据的获取方式可能被很多不同的页面共享(典型来说,“推荐文章”这个小栏目的数据获取,可能会被很多页面所共享)。这种情况下,可以把这部分逻辑抽取到一个独立Action中,并使用chain,将这个Action与主Action串联起来。这样,最后到达页面的时候,页面始终可以得到每个Action中的数据。

不过chain这种Result,是在使用时需要慎重考虑的一种Result:

Struts2 Reference 写道
As a rule, Action Chaining is not recommended. First explore other options, such as the Redirect After Post technique.



而Struts2也做出了理由上的说明:

Struts2 Reference 写道
Experience shows that chaining should be used with care. If chaining is overused, an application can turn into "spaghetti code". Actions should be treated as a Transaction Script, rather than as methods in a Business Facade. Be sure to ask yourself why you need to chain from one Action to another. Is a navigational issue, or could the logic in Action2 be pushed back to a support class or business facade so that Action1 can call it too?

Ideally, Action classes should be as short as possible. All the core logic should be pushed back to a support class or a business facade, so that Actions only call methods. Actions are best used as adapters, rather than as a class where coding logic is defined.



从实战上将,使用chain作为Result也的确存在着上面所说的许多问题,我个人也是非常不推崇滥用这种Result。尤其是,对于使用Spring和Hibernate的朋友来说,如果你开启OpenSessionInView模式,那么Hibernate的session是跟随HttpServletRequest的,所以session在整个action链中共享。这会为我们的编程带来极大的麻烦。因为我们知道Hibernate的session会保留一份一级缓存,在action链中,共享一级缓存无疑会为你的调试工作带来很大的不方便。

所以,谨慎使用chain作为你的Result,应该成为一条最佳实践。

stream

Xml代码 复制代码
  1. <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>  
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>



StreamResult等价于在Servlet中直接输出Stream流。这种Result被经常使用于输出图片、文档等二进制流到客户端。通过使用StreamResult,我们只需要在Action中准备好需要输出的InputStream即可。

Xml代码 复制代码
  1. <result name="success" type="stream">  
  2.   <param name="contentType">image/jpeg</param>  
  3.   <param name="inputName">imageStream</param>  
  4.   <param name="contentDisposition">filename="document.pdf"</param>  
  5.   <param name="bufferSize">1024</param>  
  6. </result>  
<result name="success" type="stream">
  <param name="contentType">image/jpeg</param>
  <param name="inputName">imageStream</param>
  <param name="contentDisposition">filename="document.pdf"</param>
  <param name="bufferSize">1024</param>
</result>



同时,StreamResult支持许多参数,对输出的Stream流进行参数控制。具体每个参数的作用,可以参考:http://struts.apache.org/2.0.14/docs/stream-result.html

其他

Struts2的高度可扩展性保证了许多自定义的Result可以通过插件的形式发布出来。比较著名的有JSONResult,JFreeChartResult等等。有兴趣的读者可以在Struts2的官方网站上找到它们,并选择合适的加入到你的项目中去。

关于Result配置简化的思考

Struts2的Result,解决了“如何从Control层转向View层”的问题。不过看了上面介绍的这些由框架本身实现的Result,我们可以发现Result所涉及到的,基本上还停留在为Control层到View层搭建桥梁。

传统的,我们需要通过配置文件,来指定Action执行完毕之后,到底执行什么样的Result。不过在这样一个到处呼吁简化配置的年代,存在着许多方式,可以省略配置:

1. 使用Annotation

Struts2的一些插件提供了@Result和@Results的Annotation,可以通过Annotation来省略XML配置。具体请参考相关的文档。

2. Codebehind插件

Struts2自带了一个Codebehind插件(Struts2.1以后被合并到了其他的插件中)。Codebehind的基本思想是通过CoC的方式,使用

FPGA实战:用DDR3和乒乓操作解决视频帧撕裂问题(附Verilog代码) 本文详细介绍了如何利用DDR3内存和乒乓操作架构解决FPGA视频处理中的帧撕裂问题。通过多帧缓存原理、AXI接口配置和自适应乒乓操作设计,有效隔离读写操作,确保视频流稳定传输。文章包含Verilog代码实现和性能优化技巧,适用于工业相机、医疗影像等高速视频处理场景。 阅读详情

相关推荐

SAP Workflow 工作流开发步骤总结

SAP WORKFLOW

qq_36952606的博客 5115

Struts2学习笔记4 ――国际化

Struts2学习笔记4 ――国际化  1.建立国际化资源文件LoginAction_zh_CN.properties : ## login.jsplogin.title = 用户登录login.username = 用户名login.password = 密码login.submit = 登录## login.jsp validationrequiredst

楓雨人生 5689

EEGLAB+ERPLAB实战:从.cnt文件到情绪ERP差异波,一份避坑指南

本文详细介绍了使用EEGLAB和ERPLAB处理Neuroscan的.cnt格式脑电数据的全流程,从数据导入、预处理到情绪ERP差异波生成。重点解决了采样率验证、事件标记检查、重参考选择、滤波策略与ICA组合等实操难题,并提供了情绪图片ERP研究中P1、EPN和LPP成分的分析技巧,帮助研究者避免常见错误,提升数据处理效率。

weixin_26795617的博客 276

Struts2学习笔记(4)——struts2的Action详解

Struts2的action采用了低侵入式,不要求实现任何类,也不需要去实现任何接口,Action类完全是一个普通的POJO类,有很好的复用性。 Struts2通常直接使用Action来封装HTTP请求参数,因此我们需要为Action中的属性添加setter()和getter()方法。并添加一个execute()方法。 其次,可以实现Action接口以规范Action类开发。

xxxknight 455

深入解析STM32F103R6的USB OTG_FS双重角色设备(DRD)设计与应用

本文深入解析了STM32F103R6的USB OTG_FS双重角色设备(DRD)设计与应用。详细阐述了其作为USB主机和设备双重角色的硬件设计要点,包括VBUS电源管理与ID引脚配置,并提供了设备模式(如虚拟串口CDC)与主机模式(如读取U盘文件)的软件实现实战指南,帮助开发者充分发挥该芯片的OTG潜力。

weixin_29195615的博客 277

安卓中蓝牙免提HFP的一些分析

最近看了一些大牛的博客,无不提到了技术分享的重要性,的确,分享自己的知识不仅仅是与他人讨论并相互提高的过程,更是对自己知识的梳理。希望自己能以此为契机,形成周期性博客分享的习惯。 文章标题为HFP的一些分析,HFP(Hand Free Profile)主要定义了安卓中与接打电话相关的一些功能的实现。本文主要介绍这其中对于HFP非常重要的Service Level Connection的建立。首先...

底层码农 776

struts2学习笔记4

3.所有定义的其他命名空间 是否真是如此呢? 第一个方案是在我指定的命名空间中寻找了/mystruts,姑且如此理解。 第二个方案,我虽然指定了命名空间,但是action="mystruts/mulInput"如此定义,可能过滤器理解为到/mystruts命名空间下去寻找了mulInput,所以可以找到。这时是否可认为后面的namespace属性未其作用? ...

知行天下 127

Python实战项目2:b站评论采集

本文不对数据采集的过程做探讨,直接上代码。

lyccomcn的博客 3207

Struts2 学习笔记 4

1.Strurs2 DMI (动态方法调用) /User.jsp 比如调用UserAction中的add方法,不需要在struts.xml对应Action中配置method方法,在JSP调用Action属性中用 action="user!add",此时调用的为UserAction中的add方法 2.Strut

结婚兔的专栏 386

基于STM32L4XX的环境光传感器(LTR-303ALS-01)应用程序设计

/ 状态寄存器的位[2:0]表示数据状态,例如位2为1表示新数据就绪[citation:6]#define LTR303_REG_DATA_CH0_LOW 0x8D // CH0数据低字节。#define LTR303_REG_DATA_CH0_HIGH 0x8E // CH0数据高字节。#define LTR303_REG_DATA_CH1_LOW 0x8F // CH1数据低字节。#define LTR303_REG_DATA_CH1_HIGH 0x90 // CH1数据高字节。

myron6688的博客 421

图神经网络学习笔记-点云数据处理(专题七)

本教程解释了如何利用图神经网络(Graph Neural Networks,GNNs)来处理和训练点云数据。尽管点云默认情况下不具有图结构,但我们可以利用 PyG 的转换工具,将其转化为适合 PyG 所提供的全套 GNN 模型的形式。关键思想是从点云数据中创建一个,通过 GNN 的消息传递机制,从中学习有意义的局部几何结构。这些点的表示可以被用于例如点云分类或分割等任务。

359

Struts2学习笔记--(4)

第十章:OGNL表达式中的符号 10.1 # “#”作用有二: 获取ognl上下文数据,如#key可以获得ContextMap中的对应数据 可以借助struts2标签,在页面创建集合,如&amp;lt;s:radio list=”#{key:value,……}”/&amp;gt; ** - 10.2 % ** “%”作用有二: 1 将ognl表达式转变成字符串,如%{‘’} 2 将字符串转变成ognl...

Before30的博客 390

PNETLab 镜像包官方下载太慢?不急,最新版本PNET_4.2.10分享!

你好,这里是网络技术联盟站,我是瑞哥。PNETLab是一个强大的网络仿真工具平台,全称Packet Network Emulator Tool Lab。它不仅允许用户进行深入的网络实验,还支持社区成员之间的实验室共享。PNETLab致力于为学习者、教师以及网络工程师提供一个全面的实验环境,以便于他们能够在实际部署前测试和验证网络配置和协议。和。这两个部分相辅相成,共同构成了一个全面且灵活的网络仿真生态系统。

网络技术联盟站 4519

Struts2学习笔记(4)

七、ActionSupport 1)在struts.xml文件中,action标签如果未使用class属性,则默认class值为ActionSupport。 2)实现Action接口。可以调用execute方法及五个常量。 3)实现Validateable接口。手工实现验证时使用。 4)实现ValidationAware接口。用来接收和显示错误的消息。 5)实现TextProvider和

Hai_Eason的博客 405

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Struts2学习笔记4:Struts2的类型转换【2】

 遗留任务:www.opensymphony.com/ognl下载ognl-2.6.11.jar文件的源代码1.建立converter.PointConverter.java文件,以下是源代码import java.util.Map;import model.Point;import ognl.DefaultTypeConverter;pub

风达的专栏 1237

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Struts2的学习笔记(4)

Struts2的一些高级应用,在这段时间,深入地学习了Struts2的一些常用方法,但是这仅仅是一些表面的,多做项目多积累,多发现问题才是王道!各位前辈们,望多请教!   1、定义拦截器时可以直接继承AbstractInterceptor抽象类(该类实现了Interceptor接口,并且对init和destroy方法进行了空实现),然后实现其抽象方法intercept即可。   2、方法拦

专注JAVA EE、jQuery等等的学习 249

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

struts2学习笔记4:拦截器

struts2学习笔记4黑马视频的学习笔记4:struts2拦截器概述1.struts2是框架,封装了很多的功能,都封装在拦截器中。2.struts2封装了很多功能,有很多拦截器,每次只执行默认的拦截器3.struts2默认拦截器的位置 =============&gt;=================&gt;4.拦截器在什么时候执行:在action对象创建之后,action里面的方法执行之前。...

shanshuisheng的博客 294

JavaEE学习笔记之SSH—Struts2(4)

这篇文章讲讲 Struts2 的核心所在——拦截器一、strut2框架中的拦截器(interceptor)1.什么是拦截器(interceptor) 拦截器是strut2框架中提供的一种java类。 作用: 1.可以拦截访问action的请求 2.给这个action加入新的丰富功能(上传、参数自动接收、类型自动转换等等)需要配置之后,指明哪一个拦截器去拦截哪一个action或者哪一些ac

minigeek的博客 3815

JAVA EE 学习笔记[V4 Struts 2框架试水]

Going on 在有前面一些基础的时候可以把目光放向更远的地方了。Java EE 开发框架(刚开始接触有大佬告诉我这个是用来偷懒的,但既然存在,不可能只为偷懒)在一定程度上框架减轻了维护和开发压力,而Struts作为三大框架(还有SpringHibernate)之一,也发展到了Struts2。要说起框架在Java EE开发过程中的地位,那如图: 若把Web应用看作是...

171

【Struts2学习笔记(4)】指定需要Struts 2处理的请求后缀和细说常量定义

前面我们都是默认使用.action后缀访问Action。其实默认后缀是可以通过常量”struts.action.extension“进行修改的,例如:我们可以配置Struts 2只处理以.do为后缀的请求路径: <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//

徐刘根的博客 3007

struts2学习笔记4-验证

Struts2 • ActionSupport • validate验证 • 获取Session、request、response和Application对象 • 拦截器 ActionSupport • 使用ActionSupport可以完成以下工作: – 验证 – 国际化 – 获取本地信息 – … 验证 public class TypeAction ex

hihiprince的专栏 445

struts2.3.4 学习笔记(1)

  structs2.3.4 学习笔记   1.在myeclipse7.0中创建web project项目 2.添加 struts2.3.4 所需要的lib文件,具体要用到的jar文件如下:         asm-3.3.jar asm-commons-3.3.jar asm-tree-3.3.jar commons-fileupload-1.2.2.jar commo...

zxsqi的博客 249

【Struts2学习笔记(4)】指定需要Struts 2请求后缀的常量定义复杂的过程

一、指定需要Struts 2请求后缀处理 我们是在违约前.action后缀访问Action。事实上默认后缀是通过不断”struts.action.extension“进行更改。例如:我们可以配置Struts 2仅仅处理以.do为后缀的请求路径: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE struts ...

weixin_33805743的博客 92

Struts2学习笔记(4) - OGNL

通过OGNL实现表单数据的获取,并自动类型转换,以及编写自定义类型转换器 1.自定义类型 User.java [code="java"]public class User { private String name; private Map pets; ... Setter and Getter ... }[/code] [code="java...

Fight for MyLife 103

J2EE系列之Spring4学习笔记(十四)--Spring4整合Struts2和Hibernate4

上一篇博客搭建了S2SH框架,这一篇博客讲述一个实例。 Spring支持泛型注入,所以DAO层变得非常简化。 1.在com.test.dao包中新建接口BaseDao: package com.test.dao; import java.io.Serializable; import java.util.List; /** * 基础数据库操作类 * * @author www.t

feidie436的专栏 432
上一篇: Struts2学习笔记3
下一篇: Struts2学习笔记5
cppmayi
博客等级 码龄19年 0粉丝 13原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址