使用response.sendRedirect()传递隐藏参数 [英] Pass Hidden parameters using response.sendRedirect()

查看:4641
本文介绍了使用response.sendRedirect()传递隐藏参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何传递隐藏参数?我想调用一个页面(test.jsp),但也传递2个隐藏参数,如帖子。

How would I pass hidden parameters? I want to call a page (test.jsp) but also pass 2 hidden parameters like a post.

response.sendRedirect("/content/test.jsp");


推荐答案

TheNewIdiot的答案成功地解释了问题以及无法通过重定向在请求中发送属性的原因。可能的解决方案:

TheNewIdiot's answer successfully explains the problem and the reason why you can't send attributes in request through a redirect. Possible solutions:


  1. 使用转发。这将使请求属性可以传递给视图,您可以以 ServletRequest#getAttribute 或使用表达语言 JSTL 。简短的例子(重用TheNewIdiot的答案)代码。)

  1. Using forwarding. This will enable that request attributes could be passed to the view and you can use them in form of ServletRequest#getAttribute or by using Expression Language and JSTL. Short example (reusing TheNewIdiot's answer] code).

控制器(你的servlet)

request.setAttribute("message", "Hello world");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);

查看(您的JSP)

使用scriptlet:

Using scriptlets:

<%
    out.println(request.getAttribute("message"));
%>

这仅用于信息目的。必须避免使用的Scriptlet 如何避免JSP文件中的Java代码?。下面是使用EL和JSTL的示例。

This is just for information purposes. Scriptlets usage must be avoided: How to avoid Java code in JSP files?. Below there is the example using EL and JSTL.

<c:out value="${message}" />


  • 如果您不能使用转发(因为您不喜欢或不喜欢)感觉不是这样,或者因为你必须使用重定向,然后选项会将消息保存为会话属性,然后重定向到您的视图,恢复视图中的会话属性并删除它来自会议。请记住始终只使用相关数据进行用户会话。代码示例

  • If you can't use forwarding (because you don't like it or you don't feel it that way or because you must use a redirect) then an option would be saving a message as a session attribute, then redirect to your view, recover the session attribute in your view and remove it from session. Remember to always have your user session with only relevant data. Code example

    控制器

    //if request is not from HttpServletRequest, you should do a typecast before
    HttpSession session = request.getSession(false);
    //save message in session
    session.setAttribute("helloWorld", "Hello world");
    response.sendRedirect("/content/test.jsp");
    

    查看

    再次,使用scriptlets然后EL + JSTL显示:

    Again, showing this using scriptlets and then EL + JSTL:

    <%
        out.println(session.getAttribute("message"));
        session.removeAttribute("message");
    %>
    
    <c:out value="${sessionScope.message}" />
    <c:remove var="message" scope="session" />
    


  • 这篇关于使用response.sendRedirect()传递隐藏参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆