【问题标题】:forward(request, response) reveals user data in the address barforward(request, response) 在地址栏中显示用户数据
【发布时间】:2013-08-07 06:58:15
【问题描述】:


我有一个登录表单和一个用于登录的 servlet。如果用户有效,我将他重定向到下一页

response.sendRedirect("welcome.jsp");

我还想向这个页面发送一个对象,所以我用这个替换了 sendRedirect

request.setAttribute("notes", notesObject)
disp = getServletContext().getRequestDispatcher("/welcome.jsp");
disp.forward(request, response);

现在的问题是,现在,当用户登录时(例如用户/111),在地址栏中我有这个:

localhost:8084/WebApplication2/loginServlet?username=user&password=111&action=LOGIN

但是当我使用 Sendredirect 时,我只有 localhost:8084/WebApplication2/welcome.jsp

登录Servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
//code...

jsp文件:

 <form action="loginServlet">
//code...

【问题讨论】:

    标签: jsp servlets response.redirect forward


    【解决方案1】:

    问题不在于forward()sendRedirect(),而在于您如何从HTML 表单发送数据。

    请记住,&lt;form&gt; 标签使用GET 方法作为默认 HTTP 方法。由于您没有明确给出任何方法,它将使用GET 方法。

    this link:

    <!ATTLIST FORM
      %attrs;                              -- %coreattrs, %i18n, %events --
      action      %URI;          #REQUIRED -- server-side form handler --
      method      (GET|POST)     GET       -- HTTP method used to submit the form--
      enctype     %ContentType;  "application/x-www-form-urlencoded"
      accept      %ContentTypes; #IMPLIED  -- list of MIME types for file upload --
      name        CDATA          #IMPLIED  -- name of form for scripting --
      onsubmit    %Script;       #IMPLIED  -- the form was submitted --
      onreset     %Script;       #IMPLIED  -- the form was reset --
      accept-charset %Charsets;  #IMPLIED  -- list of supported charsets --
      >
    

    现在,通过GET 请求,您的所有表单数据都将作为您的查询字符串 的一部分,这就是您在那里看到这些数据的原因。您应该将方法更改为POST

    <form action="loginServlet" method = "POST">
    

    您在使用sendRedirect() 时没有看到数据的原因是,使用response.sendRedirect(),客户端创建并发送了一个新请求。因此,您的旧请求 URI 不再存在。对于forward(),情况并非如此。 URI 没有改变,您会看到原始 URI 和查询字符串。

    当我使用 Sendredirect 时,我只有 localhost:8084/WebApplication2/welcome.jsp

    正如我所说,URI 发生了变化,你可以看到。因此,您看不到原始 URI 附带的查询字符串。

    另请参阅:

    【讨论】:

    • 为了工作,我不得不删除这个代码if(request.getQueryString().equals("logoute"))。否则我有一个错误 HTTP 500,抛出异常 java.lang.NullPointerException。你知道为什么吗? @Rohitjain
    • @yaylitzis。好吧,现在由于您使用的是POST,因此您将无法在查询字符串中获取参数。因此你得到NPE。您现在应该使用request.getParameter({form-element-name}) 获取参数
    猜你喜欢
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2013-12-20
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    相关资源
    最近更新 更多