zoukankan      html  css  js  c++  java
  • How to test for a valid user session in a JSP

     

    Note: This approach is very old; Java/JSP scriptlets were deprecated a long time ago. I don't have time to update this article to the correct, modern approach, but I hope this JSP session example will point you in the right direction.

    Every once in a while I'm asked something like, "How can I tell if I have a valid user session in my JSP code?"

    According to the JSP specification, an implicit variable named session (which is an instance of anHttpSession) is made available to your JSP's automatically by your servlet container. So, all you have to do to determine if you have a valid user session in a JSP is to test whether this session reference isnull, or not, like this:

    if (session == null)
    {
      // the user *does not* have a valid session; handle this however you need to.
    }
    else
    {
      // the user *does* have a valid session.
      // do whatever you need to for logged in users.
     String username = (String)session.getValue("USERNAME");
    }
    

      

    One way to deal with a null user session

    If you're in a situation where a user needs to have a valid user session to access your JSP/servlet content, you can deal with the situation using JSP code like this:

    <%
      if (session == null)
      {
        String address = websiteContext + "/login.jsp";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
        dispatcher.forward(request,response);
      }
    %>
    

      

    In this example I've already set the variable websiteContext somewhere earlier in my JSP. For example, if this was a discussion forum, this variable might be set to the string "/forums".

    If you prefer the JSP forward tag, you can also forward to the login page like this:

    <%
      if (session == null)
      {
        %><jsp:forward page="login.jsp" /><%
      }
    %>
    

      

    Which one you choose is up to you.

  • 相关阅读:
    用pygame实现打飞机游戏-3-显示飞机和控制飞机移动
    用pygame实现打飞机游戏-2-检测键盘
    最好听的钢琴曲排行榜 世界上最好听的钢琴曲
    使用gulp构建nodejs,你只需要记住5个函数
    Linux删除文件夹命令
    前端构建工具gulpjs的使用介绍及技巧
    HTML5 LocalStorage 本地存储
    jquery新窗口打开链接
    Sublime text 3 如何格式化HTML代码
    jquery滚动条加载数据
  • 原文地址:https://www.cnblogs.com/hephec/p/4586788.html
Copyright © 2011-2022 走看看