繁体   English   中英

Java servlet HttpSession似乎无法立即工作

[英]The Java servlet HttpSession does not seem to work immediately

在我的登录servlet中, doPost的最后一个代码如下:

HttpSession session = request.getSession();
session.setAttribute(Config.CURRENT_USER_PARAMETER, user);
request.getRequestDispatcher("app.jsp").forward(request, response);

关于app.jsp ,它如下:

<%@page import="fi.vakuutustiedot.controllers.Config"%>
<%@page import="fi.vakuutustiedot.model.User"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
    if (session == null) {
        request.getRequestDispatcher("index.html").forward(request, response);
        return;
    }

    User user = (User) session.getAttribute(Config.CURRENT_USER_PARAMETER);

    if (user == null) {
        session.invalidate();
        request.getRequestDispatcher("index.html").forward(request, response);
        return;    
    }
%>
<!DOCTYPE html>
...

我的问题是以下情形:

  1. 我通过连接到我的登录servlet的HTML表单登录。
  2. 登录Servlet创建一个HttpSession并为该对象添加一个描述所讨论用户的属性。
  3. 最后,它转发到app.jsp

问题是,当我登录并转发到app.jsp ,可以看到所有内容, 但是如果我在位置栏中键入.../app.jsp并按Enter,它将重定向到index.html 但是,当我第二,第三,.etc次访问app.jsp时,一切都很好,并且不会发生虚假的重定向到index.html情况。

从安全角度来看,此解决方案是否足够?

我通过在登录servlet中添加以下行解决了该问题:

HttpSession session = request.getSession();
request.setAttribute(Config.CURRENT_USER_PARAMETER, user); // <- The new added line.
session.setAttribute(Config.CURRENT_USER_PARAMETER, user);
request.getRequestDispatcher("app.jsp").forward(request, response);

app.jsp我有:

<%@page import="fi.vakuutustiedot.controllers.Config"%>
<%@page import="fi.vakuutustiedot.model.User"%>
<%@page import="fi.vakuutustiedot.model.UserType"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%! User user = null; %>
<%
    if (session == null) {
        request.getRequestDispatcher("no_session.html").forward(request, response);
        return;
    }

    user = (User) session.getAttribute(Config.CURRENT_USER_PARAMETER);

    if (user == null) {
        user = (User) request.getAttribute(Config.CURRENT_USER_PARAMETER);
    }

    if (user == null) {
        request.getRequestDispatcher("test.jsp").forward(request, response);
        return;
    }
%>
<!DOCTYPE html>
...

回答我自己的问题

在登录servlet中,我要做的就是:

HttpSession session = request.getSession();
session.setAttribute(Config.CURRENT_USER_PARAMETER, user);
response.sendRedirect("app.jsp");

这样,用户对象可以直接从session而我不需要将该用户放到请求对象中。

似乎您正在尝试进入上下文之外的页面。

根据您的问题,我只猜您的目录是:/index.html /app.jsp

在运行应用程序时,您可能会插入一个URI,例如: http:// [my_server] / [my_app] /index.html或仅仅是: http:// [my_server] / [my_app] /

当您键入../app.jsp时,您正在尝试获取不存在的内容。 您的服务器可能设置为发送默认页面index.html,而没有默认错误页面。

我猜您由于不正确的URI而只是返回index.html页面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM