【问题标题】:Session management in jsp projectjsp项目中的会话管理
【发布时间】:2018-02-01 08:25:20
【问题描述】:

我正在开发一个大学项目,我将尝试用一个小例子来解释我的问题。 下面有 3 个 jsp 页面(index.jsptest.jsplogged.jsp),如果用户尝试访问,我希望logged.jsp 直接输入 url http://localhost:8080/sessionTest/logged.jsp 然后他将被重定向到 index.jsp

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action ="test.jsp" method="post">
            enter user id :<input type="text" name="user">
            Enter password:<input type="password" name="pass">
            <input type="submit" value="submit">
        </form>
    </body>
</html>

test.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
     String user= request.getParameter("user");
     String pass= request.getParameter("pass");
     if(user.equals("snow")&& pass.equals("123"))
     {
         session.setAttribute("user", user);
         RequestDispatcher r = request.getRequestDispatcher("logged.jsp");
         r.forward(request, response);
     }
     else {
         out.println("wrong pass or id");
     }
             %>
    </body>
</html>

logged.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <% session = request.getSession(false);
           if(session==null)
           {
               response.sendRedirect("index.jsp");
           }
           else{
               out.println("welcome its old session");
           }
        %>
    </body>
</html>

请帮我写一些代码并解释它是如何工作的

【问题讨论】:

  • 方法错误。您需要检查会话中的会话属性(如 userid)以检查用户是否已登录,并且需要在每个页面中执行此操作,如果不满足该条件,则在每个页面中重定向到登录屏幕。您可以通过将此代码放在每个页面的顶部,或使用 servlet 过滤器来做到这一点。但是,如果您只签入登录页面而不签入您想要保护的索引和其他页面,那么有人可以直接进入 index.jsp 并绕过您假定的安全性。
  • 你能用一些代码解释一下吗@developerwjk。
  • 实际上,很像下面 Maulik Bhatt 的回答,除了相反。在每个应保护的页面的开头:if(session.getAttribute("username")==null) { response.sendRedirect("login_form.jsp"); return; },以便如果用户未登录,他们将被重定向到登录表单。

标签: html jsp session redirect session-management


【解决方案1】:

试试这个可能对你有帮助:

<%
HttpSession session = request.getSession();

if(null!=session.getAttribute("username")){
    out.write("username is "+session.getAttribute("username").toString());

    }
else{
    response.sendRedirect("/index.jsp");
    }
%>

【讨论】:

    猜你喜欢
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    相关资源
    最近更新 更多