Java servlet HttpSession似乎不能立即工作

问题描述 投票:0回答:1

在我的登录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!然而,当我访问app.jsp第二,第三,。等时间时,一切都很好,没有虚假的重定向到index.html发生。

Is this solution adequate from the security standpoint?

我通过在登录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>
...

Answering my own question

在登录servlet中,我所做的只是:

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

这样,用户对象可直接从session获得,我不需要将该用户放入请求对象。

java jsp redirect servlets
1个回答
0
投票

您似乎正试图访问上下文之外的页面。

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

当您运行应用程序时,您可能会使用以下URI:http://[my_server]/[my_app]/index.html或仅:http://[my_server]/[my_app]/

当你输入../app.jsp时,你正试图得到一些不存在的东西。您的服务器可能设置为发送index.html的默认页面,没有默认错误页面。

我猜你刚刚回到index.html页面,因为URI不正确。

© www.soinside.com 2019 - 2024. All rights reserved.