ITeye博客

struts2零配置的方法

40020072 · 2008-08-18 09:48 · struts2 · Markdown

为Struts2增加了一种返回类型,直接通过action方法的返回值确定要返回的页面.


<result-types>
     <result-type name="direct" class="javacommon.struts2.dispatcher.DirectResult"/>
</result-types>
 

配合struts2通符符,实现零配置,以下为配置文件action配置的全部


<package name="default" namespace="/demo" extends="custom-default">  
    <action name="*/*" method="{2}" class="com.kingsoft.demo.action.{1}Action">  
       <result name="*" type="direct">通过Action直接返回</result>  
    </action>        
</package>
 

实现forward请求的java代码

/**进入更新页面*/  
public String edit() {   
    blog = (Blog)blogManager.getById(id);   
    return "/demo/Blog/edit.jsp";   
}
 

实现redirect的做法是,前面增加了一个"!"号

/**保存更新*/  
public String update() {   
    blogManager.update(this.blog);   
    return "!/demo/Blog/list.action";   
}
 

PS.forward redirect区别:

forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器,浏览器根本不知道服务器发送的内容是从哪儿来的,所以它的地址栏中还是原来的地址。还有,转发是在web应用程序之内进行的,可以访问web应用程序所设定的内部目录,像是WEB-INF目录,只能在Web应用程序中进行,不能指定至其它的Web应用程序的地址。
redirect就是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址,一般来说浏览器会用刚才请求的所有参数重新请求,所以session,request参数都可以获取。web应用程序会要求客户端浏览器重新发出请求地址,客户端会重新连接至所指定的地址,因此浏览器的地址会出现重新导向的信息,重新导向后的请求由浏览器发出,所以不能访问Web应用程序中的隐藏目录,像是WEB-INF,重新是由浏览器重新要求一个网页,可以指定至其他的Web应用程序地址。

1.从地址栏显示来说
forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器.浏览器根本不知道服务器发送的内容从哪里来的,所以它的地址栏还是原来的地址.
redirect是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址.所以地址栏显示的是新的URL.
2.从数据共享来说
forward:转发页面和转发到的页面可以共享request里面的数据.
redirect:不能共享数据.
3.从运用地方来说
forward:一般用于用户登陆的时候,根据角色转发到相应的模块.
redirect:一般用于用户注销登陆时返回主页面和跳转到其它的网站等.
4.从效率来说
forward:高.
redirect:低.

评论(2)

  1. #2 楼 · 40020072 · 2008-09-11 09:16
    /*
     * $Id: PlainTextResult.java 471756 2006-11-06 15:01:43Z husted $
     *
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     *
     *  http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing,
     * software distributed under the License is distributed on an
     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     * KIND, either express or implied.  See the License for the
     * specific language governing permissions and limitations
     * under the License.
     */
    
    
    package javacommon.struts2.dispatcher;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.jsp.PageContext;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.struts2.ServletActionContext;
    import org.apache.struts2.dispatcher.StrutsResultSupport;
    
    import com.opensymphony.xwork2.ActionInvocation;
    import com.opensymphony.xwork2.util.TextParseUtil;
    
    /**
     * <pre>
     *	直接使用Action执行方法的返回字符串作为Http请求的forward/redirect的转向,
     *  以感叹号开头(!)的为redirect转向,反之为forward转向.
     * </pre>
     *
     */
    public class DirectResult extends StrutsResultSupport {
    
        private static final Log _log = LogFactory.getLog(DirectResult.class);
    
        private static final long serialVersionUID = 3633371605905583950L;
    
    	private boolean prependServletContext = true;
    
        public DirectResult() {
            super();
        }
    
        public DirectResult(String location) {
            super(location);
        }
    
        /**
         * Sets whether or not to prepend the servlet context path to the redirected URL.
         *
         * @param prependServletContext <tt>true</tt> to prepend the location with the servlet context path,
         *                              <tt>false</tt> otherwise.
         */
        public void setPrependServletContext(boolean prependServletContext) {
            this.prependServletContext = prependServletContext;
        }
        
        /* (non-Javadoc)
         * @see org.apache.struts2.dispatcher.StrutsResultSupport#doExecute(java.lang.String, com.opensymphony.xwork2.ActionInvocation)
         */
        protected void doExecute(String finalLocation,ActionInvocation invocation) throws Exception {
            HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);
            HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(HTTP_REQUEST);
           
            String resultCodeAsLocation = invocation.getResultCode();
            if(resultCodeAsLocation == null) {
            	response.sendError(404, "result '" + resultCodeAsLocation + "' not found");
     		    return;
            }
            
            //proecss with ONGL expression
    		resultCodeAsLocation = TextParseUtil.translateVariables(resultCodeAsLocation,invocation.getStack());
            
            if(resultCodeAsLocation.startsWith("!")) {
            	doRedirect(invocation,request, response, resultCodeAsLocation.substring(1));
            }else {
            	doDispatcher(response, request, resultCodeAsLocation);
            }
        }
    
    	private void doDispatcher(HttpServletResponse response, HttpServletRequest request, String resultCodeAsLocation) throws IOException, ServletException {
    		if (_log.isInfoEnabled()) {
    		    _log.info("Forwarding to location:" + resultCodeAsLocation);
    		}
    		
    		PageContext pageContext = ServletActionContext.getPageContext();
    		if (pageContext != null) {
                pageContext.include(resultCodeAsLocation);
                return;
    		}
    		
    		RequestDispatcher dispatcher = request.getRequestDispatcher(resultCodeAsLocation);
    		if (dispatcher == null) {
    		    response.sendError(404, "result '" + resultCodeAsLocation + "' not found");
    		    return;
    		}
    		
    		if (!response.isCommitted() && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
    		    request.setAttribute("struts.view_uri", resultCodeAsLocation);
    		    request.setAttribute("struts.request_uri", request.getRequestURI());
    
    		    dispatcher.forward(request, response);
    		} else {
    		    dispatcher.include(request, response);
    		}
    	}
    
    	private void doRedirect(ActionInvocation invocation,HttpServletRequest request, HttpServletResponse response, String redirectLocation) throws IOException {
    		if(isPathUrl(redirectLocation)) {
    			if(!redirectLocation.startsWith("/")) {
    				String namespace = invocation.getProxy().getNamespace();
                    if ((namespace != null) && (namespace.length() > 0) && (!"/".equals(namespace))) {
                    	redirectLocation = namespace + "/" + redirectLocation;
                    } else {
                    	redirectLocation = "/" + redirectLocation;
                    }
    			}
    			if (prependServletContext  && (request.getContextPath() != null) && (request.getContextPath().length() > 0)) {
    				redirectLocation = request.getContextPath() + redirectLocation;
                }
    		}
    		
    		if(_log.isInfoEnabled())
    			_log.info("Redirect to location:"+redirectLocation);
    		response.sendRedirect(response.encodeRedirectURL(redirectLocation));
    	}
        
        private static boolean isPathUrl(String url) {
            // filter out "http:", "https:", "mailto:", "file:", "ftp:"
            // since the only valid places for : in URL's is before the path specification
            // either before the port, or after the protocol
            return (url.indexOf(':') == -1);
        }
    }
    
    
  2. #1 楼 · michael152630 · 2008-09-09 16:54

    老兄,今天看了你的这个方法,很精彩啊,能不能把“javacommon.struts2.dispatcher.DirectResult”这个jar包发我啊 我在网上找了好久都没找到, e-mail:michael152630@gmail.com 先谢谢了!

评论功能维护中,当前仅展示历史评论。