首先解释一下几个名词:

request.getRequestDispatcher()是请求转发,前后页面共享一个request ;

response.sendRedirect()是重新定向,前后页面不是一个request。

RequestDispatcher.forward()是在服务器端运行;

HttpServletResponse.sendRedirect()是通过向客户浏览器发送命令来完成.

所以RequestDispatcher.forward()对于浏览器来说是“透明的”;

而HttpServletResponse.sendRedirect()则不是。

这么光说,一定很难理解,看一个例子。

情景:qq登录上,你直接点击邮箱他就会直接登录邮箱。

假如请求路径:http://localhost:8080/test/web/skiplogin.action?url=/mail/productManage.action&sessionid=1000111&&phoneId=100000

action中会把url,sessionid,phoneId解析出来,然后跳转到url,假如你是用的是

1
2
3
RequestDispatcher dispatcher = request.getRequestDispatcher(url_pa);
//          dispatcher.forward(request, response);
//          使用这个方法转发,地址不变,这是在服务器端完成的

浏览器上的地址栏里的路径是不会变的。

假如使用response.sendRedirect(basePath+finalLocation);

浏览器上的路径就会变成:http://localhost:8080/test/mail/productManage.action。

struts2 result返回类型type="redirect"时,查看它的源代码其实就是做了一次重新跳转。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
* $Id: ServletRedirectResult.java 1188965 2011-10-25 23:19:48Z mcucchiara $
 
package org.apache.struts2.dispatcher;
 
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import com.opensymphony.xwork2.util.reflection.ReflectionException;
import com.opensymphony.xwork2.util.reflection.ReflectionExceptionHandler;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.views.util.UrlHelper;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
 
import static javax.servlet.http.HttpServletResponse.SC_FOUND;
 
/**
 * <!-- START SNIPPET: description -->
 *
 * Calls the {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a>  HttpServletResponse#sendRedirect(String) sendRedirect}
 * method to the location specified. The response is told to redirect the
 * browser to the specified location (a new request from the client). The
 * consequence of doing this means that the action (action instance, action
 * errors, field errors, etc) that was just executed is lost and no longer
 * available. This is because actions are built on a single-thread model. The
 * only way to pass data is through the session or with web parameters
 * (url?name=value) which can be OGNL expressions.
 *
 * <!-- END SNIPPET: description -->
 * <p/>
 * <b>This result type takes the following parameters:</b>
 *
 * <!-- START SNIPPET: params -->
 *
 * <ul>
 *
 * <li><b>location (default)</b> - the location to go to after execution.</li>
 *
 * <li><b>parse</b> - true by default. If set to false, the location param will
 * not be parsed for Ognl expressions.</li>
 *
 * <li><b>anchor</b> - Optional.  Also known as "fragment" or colloquially as
 * "hash".  You can specify an anchor for a result.</li>
 * </ul>
 *
 * <p>
 * This result follows the same rules from {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a>  StrutsResultSupport}.
 * </p>
 *
 * <!-- END SNIPPET: params -->
 *
 * <b>Example:</b>
 *
 * <pre>
 * <!-- START SNIPPET: example -->
 * &lt;!--
 *   The redirect URL generated will be:
 *   /foo.jsp#FRAGMENT
 * --&gt;
 * &lt;result name="success" type="redirect"&gt;
 *   &lt;param name="location"&gt;foo.jsp&lt;/param&gt;
 *   &lt;param name="parse"&gt;false&lt;/param&gt;
 *   &lt;param name="anchor"&gt;FRAGMENT&lt;/param&gt;
 * &lt;/result&gt;
 * <!-- END SNIPPET: example -->
 * </pre>
 *
 */
public class ServletRedirectResult extends StrutsResultSupport implements ReflectionExceptionHandler {
 
    private static final long serialVersionUID = 6316947346435301270L;
 
    private static final Logger LOG = LoggerFactory.getLogger(ServletRedirectResult.class);
 
    protected boolean prependServletContext = true;
 
    protected ActionMapper actionMapper;
 
    protected int statusCode = SC_FOUND;
 
    protected boolean suppressEmptyParameters = false;
 
    protected Map<String, String> requestParameters = new LinkedHashMap<String, String>();
 
    protected String anchor;
 
    public ServletRedirectResult() {
        super();
    }
 
    public ServletRedirectResult(String location) {
        this(location, null);
    }
 
    public ServletRedirectResult(String location, String anchor) {
        super(location);
        this.anchor = anchor;
    }
 
    @Inject
    public void setActionMapper(ActionMapper mapper)
    {
        this.actionMapper = mapper;
    }
 
    public void setStatusCode(int code)
    {
        this.statusCode = code;
    }
 
    /**
     * Set the optional anchor value.
     *
     * @param anchor
     */
    public void setAnchor(String anchor)
    {
        this.anchor = anchor;
    }
 
    /**
     * 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;
    }
 
    public void execute(ActionInvocation invocation) throws Exception
    {
        if (anchor != null)
        {
            anchor = conditionalParse(anchor, invocation);
        }
 
        super.execute(invocation);
    }
 
    /**
     * Redirects to the location specified by calling
     * {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a>  HttpServletResponse#sendRedirect(String)}.
     *
     * @param finalLocation
     *            the location to redirect to.
     * @param invocation
     *            an encapsulation of the action execution state.
     * @throws Exception
     *             if an error occurs when redirecting.
     */
    protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception
    {
        ActionContext ctx = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
        HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);
 
        if (isPathUrl(finalLocation))
        {
            if (!finalLocation.startsWith("/"))
            {
                ActionMapping mapping = actionMapper.getMapping(request, Dispatcher.getInstance().getConfigurationManager());
                String namespace = null;
                if (mapping != null)
                {
                    namespace = mapping.getNamespace();
                }
 
                if ((namespace != null) && (namespace.length() > 0) && (!"/".equals(namespace)))
                {
                    finalLocation = namespace + "/" + finalLocation;
                }
                else
                {
                    finalLocation = "/" + finalLocation;
                }
            }
 
            // if the URL's are relative to the servlet context, append the servlet context path
            if (prependServletContext && (request.getContextPath() != null) && (request.getContextPath().length() > 0))
            {
                finalLocation = request.getContextPath() + finalLocation;
            }
 
            ResultConfig resultConfig = invocation.getProxy().getConfig().getResults().get(invocation.getResultCode());
            if (resultConfig != null)
            {
                Map<String, String> resultConfigParams = resultConfig.getParams();
 
                for (Map.Entry<String, String> e : resultConfigParams.entrySet())
                {
                    if (!getProhibitedResultParams().contains(e.getKey()))
                    {
                        String potentialValue = e.getValue() == null ? "" : conditionalParse(e.getValue(), invocation);
                        if (!suppressEmptyParameters || ((potentialValue != null) && (potentialValue.length() > 0)))
                        {
                            requestParameters.put(e.getKey(), potentialValue);
                        }
                    }
                }
            }
 
            StringBuilder tmpLocation = new StringBuilder(finalLocation);
            UrlHelper.buildParametersString(requestParameters, tmpLocation, "&");
 
            // add the anchor
            if (anchor != null)
            {
                tmpLocation.append('#').append(anchor);
            }
 
            finalLocation = response.encodeRedirectURL(tmpLocation.toString());
        }
 
        if (LOG.isDebugEnabled())
        {
            LOG.debug("Redirecting to finalLocation " + finalLocation);
        }
 
        sendRedirect(response, finalLocation);//////看这个方法
    }
 
    protected List<String> getProhibitedResultParams()
    {
        return Arrays.asList(DEFAULT_PARAM, "namespace", "method", "encode", "parse", "location", "prependServletContext", "suppressEmptyParameters", "anchor");
    }
 
    /**
     * Sends the redirection. Can be overridden to customize how the redirect is
     * handled (i.e. to use a different status code)
     *
     * @param response
     *            The response
     * @param finalLocation
     *            The location URI
     * @throws IOException
     */
    protected void sendRedirect(HttpServletResponse response, String finalLocation) throws IOException
    {
        if (SC_FOUND == statusCode)
        {
            response.sendRedirect(finalLocation);//就是做了一个这样的事情
        }
        else
        {
            response.setStatus(statusCode);
            response.setHeader("Location", finalLocation);
            response.getWriter().write(finalLocation);
            response.getWriter().close();
        }
 
    }
 
    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);
    }
 
    /**
     * Sets the suppressEmptyParameters option
     *
     * @param suppressEmptyParameters
     *            The new value for this option
     */
    public void setSuppressEmptyParameters(boolean suppressEmptyParameters)
    {
        this.suppressEmptyParameters = suppressEmptyParameters;
    }
 
    /**
     * Adds a request parameter to be added to the redirect url
     *
     * @param key
     *            The parameter name
     * @param value
     *            The parameter value
     */
    public ServletRedirectResult addParameter(String key, Object value)
    {
        requestParameters.put(key, String.valueOf(value));
        return this;
    }
 
    public void handle(ReflectionException ex)
    {
        // Only log as debug as they are probably parameters to be appended to the url
        LOG.debug(ex.getMessage(), ex);
    }
}

我action中写的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
 
@SuppressWarnings("serial")
public class SkipLoginAction extends Action {
     
    @Inject
    private PhoneService phoneService;
    /**
     * <a href="http://my.oschina.net/u/556800" target="_blank" rel="nofollow">@return</a>
     * @throws ActionException
     */
    public void index() throws ActionException {
        try {
            HttpServletRequest request =getRequest();
            HttpServletResponse response =  getResponse();
            AuthBean authBean = null;
//          RequestDispatcher dispatcher = request.getRequestDispatcher(url_pa);
//          dispatcher.forward(request, response);
//          使用这个方法转发,地址不变,这是在服务器端完成的
             
            //客户端传来的参数
            String sessionid =  request.getParameter("sessionid");
            String finalLocation = request.getParameter("url");
            String phoneId =  request.getParameter("phoneId");
             
            String contextpath = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextpath;
 
            if(!StringUtils.isBlank(finalLocation) && !StringUtils.isBlank(sessionid) ){
                 
                if(!finalLocation.startsWith("/")){
                    finalLocation = "/" + finalLocation;
                }
                 
                HttpSession session = request.getSession();
                authBean = getAuthBean();
                if(authBean!=null){
                    if(phoneId.equals(authBean.getPhoneId())){
                        response.sendRedirect(basePath+finalLocation);
                        return;
                    }
                }
                ////获得数据库中的user中的sessionid字段
                Phone phone = phoneService.findPhoneByPhoneId(phoneId);
                if(phone!=null){
                    if( sessionid.equals(phone.getSessionid())){
                        // 用户登陆成功
                        authBean = null;
                        authBean = new AuthBean();
                        。。。。
                        response.sendRedirect(basePath+finalLocation);
                        return;
                    }
                }
            }
            //最后不符合条件统一跳到登陆界面
            finalLocation = "/web/login.index";
            response.sendRedirect(basePath+finalLocation);
        } catch (Exception e) {
            throw new ActionException("失败");
        }
    }
}

struts2 type="redirect"源码解析的更多相关文章

  1. Gin框架源码解析

    Gin框架源码解析 Gin框架是golang的一个常用的web框架,最近一个项目中需要使用到它,所以对这个框架进行了学习.gin包非常短小精悍,不过主要包含的路由,中间件,日志都有了.我们可以追着代码 ...

  2. spring 源码解析

    1. [文件] spring源码.txt ~ 15B     下载(167) ? 1 springн┤┬вио╬Ш: 2. [文件] spring源码分析之AOP.txt ~ 15KB     下载( ...

  3. Okhttp3源码解析(5)-拦截器RetryAndFollowUpInterceptor

    ### 前言 回顾: [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源码解析(1)-OkHttpClient分析](htt ...

  4. 深入学习 esp8266 wifimanager源码解析(打造专属自己的web配网)

    QQ技术互动交流群:ESP8266&32 物联网开发 群号622368884,不喜勿喷 单片机菜鸟博哥CSDN 1.前言 废话少说,本篇博文的目的就是深入学习 WifiManager 这个gi ...

  5. Spring Security 解析(七) —— Spring Security Oauth2 源码解析

    Spring Security 解析(七) -- Spring Security Oauth2 源码解析   在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因 ...

  6. .Net Core 认证系统之Cookie认证源码解析

    接着上文.Net Core 认证系统源码解析,Cookie认证算是常用的认证模式,但是目前主流都是前后端分离,有点鸡肋但是,不考虑移动端的站点或者纯管理后台网站可以使用这种认证方式.注意:基于浏览器且 ...

  7. AspNetCore3.1_Secutiry源码解析_3_Authentication_Cookies

    系列文章目录 AspNetCore3.1_Secutiry源码解析_1_目录 AspNetCore3.1_Secutiry源码解析_2_Authentication_核心流程 AspNetCore3. ...

  8. AspNetCore3.1_Secutiry源码解析_6_Authentication_OpenIdConnect

    title: "AspNetCore3.1_Secutiry源码解析_6_Authentication_OpenIdConnect" date: 2020-03-25T21:33: ...

  9. identityserver4源码解析_3_认证接口

    目录 identityserver4源码解析_1_项目结构 identityserver4源码解析_2_元数据接口 identityserver4源码解析_3_认证接口 identityserver4 ...

随机推荐

  1. python编码encode和decode

    计算机里面,编码方法有很多种,英文的一般用ascii,而中文有unicode,utf-8,gbk,utf-16等等. unicode是 utf-8,gbk,utf-16这些的父编码,这些子编码都能转换 ...

  2. Windows 之 win10快捷键

    1.Windows10系统常用快捷键: 1)贴靠窗口(窗口可以变为1/4大小放置在屏幕4个角落):Win +左/右 或 Win +上/下 2)切换窗口:Alt + Tab 3)任务视图(松开键盘界面不 ...

  3. 属性通知之INotifyPropertyChanged

    为什么后台绑定的值改变了前台不发生变化了? 针对这个初学者很容易弄错的问题,这里介绍一下INotifyPropertyChanged的用法 INotifyPropertyChanged:用于绑定属性更 ...

  4. Android进阶笔记19:onInterceptTouchEvent、onTouchEvent与onTouch

    1.onTouch方法:onTouch方法是View的 OnTouchListener借口中定义的方法,处理View及其子类被touch是的事件处理.当一个View绑定了OnTouchLister后, ...

  5. 【Android 界面效果28】Android应用中五种常用的menu

    Android Menu在手机的应用中起着导航的作用,作者总结了5种常用的Menu. 1.左右推出的Menu 前段时间比较流行,我最早是在海豚浏览器中看到的,当时耳目一新.最早使用左右推出菜单的,听说 ...

  6. ASUS K751笔记本电脑使用U盘启动

    ASUS K751笔记本电脑缺省是不能使用U盘启动的.即使开机按ESC键出现启动设备选项菜单,选择了U盘也一样会从硬盘启动. 为此需进行如下步骤: 开机按F2进入bios如下设置: Security- ...

  7. [课程相关]附加题——stack的理解

    一.stack的三种解释 stack有三种解释,我个人理解如下. 1.用户自定义的stack 用户自定义的stack就是一般意义上的后进先出队列,从名字上就能理解了,stack由下向上增长,有一个顶指 ...

  8. FastJson的使用方法总结

    本文参考:http://www.tuicool.com/articles/zUbQfa 还可参考:https://www.iflym.com/index.php/code/alibaba-fastjs ...

  9. missing required architecture x86_64 in file 不支持64位

    ( slices) 解决方法:

  10. Linux 内核模块可选信号

    一 . 内核模块可选信号 1 . 模块申明 (1). MODULE_LICENSE(遵守的协议) 申明该模块遵守的许可证协议,如:“GPL”."GPL V2" (2). MODUL ...