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

查看:82
本文介绍了使用 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's answer 成功说明问题及原因为什么不能通过重定向在请求中发送属性.可能的解决方案:

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)

使用脚本:

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

这仅用于信息目的.Scriptlets 使用必须避免:如何避免 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");
    

    查看

    再次使用 scriptlet 和 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天全站免登陆