【问题标题】:i need to restrict users to access my web application我需要限制用户访问我的 Web 应用程序
【发布时间】:2014-09-11 07:11:10
【问题描述】:

您好,我正在创建一个 Web 应用程序,在该应用程序中我想限制访问用户的数量。例如:如果超过 4 个用户,则只有 4 个用户可以访问该应用程序,它会显示错误消息,如限制超出,直到 4 个用户中的任何一个都将注销。如果 4 个用户中的任何一个注销意味着计数将为 3,因此其他 1 个用户可以访问该应用程序。另一个最好的例子:stackoverflow 页面中的声誉如果有人给一个减分,它将反映在每个人的页面中。

索引页面:

<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<html>
<body>

    <form method="get" action="PageHitCounter">
        <input type="submit" value="Add User" />
    </form>

</body>

<%

 if(session.getAttribute("ht")!=null)
    {

    String Aht= session.getAttribute("ht").toString();
    int hitCount=Integer.parseInt(Aht); 
    System.out.println("hit count in login"+hitCount);

    session.setAttribute("hitCount",hitCount);

    }

else {
    int hitCount = 0;

    session.setAttribute("hitCount",hitCount);
    System.out.println("new session count"+hitCount);
}



%>


</html>

servlet 页面:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import java.sql.Date;
//import java.sql.SQLException;
//import java.util.*;
//import java.sql.*;

public class PageHitCounter extends HttpServlet{

  private int hitCount; 

  public void init() 
  { 
     // Reset hit counter.
    hitCount = 0;
  } 

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {

      HttpSession session = request.getSession();
      // Set response content type

      response.setContentType("text/html");
      // This method executes whenever the servlet is hit 
      // increment hitCount 


      if(session.getAttribute("hitCount")!= null){

          String Aht= session.getAttribute("hitCount").toString();
          int hitCount=Integer.parseInt(Aht); 

          System.out.println(hitCount);
          hitCount++; 
          System.out.println("after increment"+hitCount++);


          if(hitCount <= 5)
          {
          System.out.println("if");
          PrintWriter out = response.getWriter();
          String title = "Total Number of Hits";
          String docType =
          "<!doctype html public \"-//w3c//dtd html 4.0 " +
          "transitional//en\">\n";
          out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor=\"#f0f0f0\">\n" +
            "<form action='Logout.jsp'>"+
            "<h1 align=\"center\">" + title + "</h1>\n" +
            "<h2 align=\"center\">" + hitCount + "</h2>\n" +
           "<input type='submit' value='logout'/>"+
            "</body></html>"); 
           }

      }

      else 
          {

        System.out.println("else");
        hitCount++; 
        session.setAttribute("ht", hitCount);


      if(hitCount <= 4)
      {
      System.out.println("aa");
      PrintWriter out = response.getWriter();
      String title = "Total Number of Hits";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<form action='Logout.jsp'>"+
        "<h1 align=\"center\">" + title + "</h1>\n" +
        "<h2 align=\"center\">" + hitCount + "</h2>\n" +
       "<input type='submit' value='logout'/>"+
        "</body></html>");


      }

      }

/*      else
      {
          destroy(); 
          response.sendRedirect("Logout.jsp");

      }*/

  }



  public void destroy() 
  { 

     // hitCount -= 1;
      // This is optional step but if you like you
      // can write hitCount value in your database.
  } 
} 

退出页面:

<%
session.removeAttribute("hitCount");
//session.invalidate(); 

   String ht1=session.getAttribute("ht").toString();
int ht2=Integer.parseInt(ht1);
System.out.println("hit count before"+ht1);
if(ht2 != 0)
{
    ht2 -= 1;
    System.out.println("hit count after"+ht2);
}

session.setAttribute("ht", ht2);  


%>
<h2>Session Destroyed successfully.. </h2>


<a href="index1.jsp">Click here to go Back</a>

现在面临的问题是计数不会减少,因为计数将在会话中,但在注销页面中我需要使会话无效,因此我无法正确获得该计数。所以请有人帮助我。

【问题讨论】:

  • 不要使用对每个用户都是新的会话,在应用程序范围内使用ServletContext 在所有用户之间共享hitCount
  • @Arvind 是的,我也认为只有一个特定用户注销意味着计数希望成为 3 个用户,而对于另一个用户,计数将显示为 3 个用户
  • 实现一个处理传入请求的过滤器,如果计数小于 10,则在登录时增加计数器,在注销时减少计数器,重定向到登录页面或重定向到某个错误页面
  • @SparkOn 是的,谢谢。我不知道过滤器可以发送任何链接以供明确参考。谢谢。

标签: jsp session servlets


【解决方案1】:

因此,您希望将应用程序限制为最多 4 个会话。您应该将活动会话数保留在 ServletContext 属性中。您可以从 servlet (getServletContext()) 或 JSP (${application.attrName}) 轻松访问它

您必须在登录时使用它,但不能依赖注销页面,因为如果用户忘记注销,会话将简单地过期。您必须设置会话侦听器以正确维护会话计数。

会话监听器可能如下所示:

@WebListener
public class SessionCountListener implements HttpSessionListener, ServletContextListener {
    private ServletContext ctx;
    private int sessionCount = 0;
    private static final String DEFAULT_ATTR = "sessionCount";
    private String attr;
    private static final String PARAM_NAME = "session_count.attr_name";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // store servletContext
        ctx = sce.getServletContext();
        // try to get attribute name in config
        attr = ctx.getInitParameter(PARAM_NAME);
        if ((attr == null) || attr.isEmpty()) {
            attr = DEFAULT_ATTR;
        }
        sessionCount = 0;
        ctx.setAttribute(attr, sessionCount);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ctx.removeAttribute(attr);
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        countUpdate(1);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        countUpdate(-1);
    }

    synchronized private void countUpdate(int delta) {
        sessionCount += delta;
        ctx.setAttribute(attr, sessionCount);
    }
}

使用此侦听器,会话计数默认存储在属性名称sessionCount 下,但可以使用名称session_count.attr_name 的上下文参数进行配置。并且对变量sessionCount 的所有访问都正确同步,因为多个请求可以同时创建或关闭会话。

您将在Java EE 6 Javadoc 上找到所有参考资料

【讨论】:

  • 我了解,但我对上下文和听众一无所知,您可以发送任何链接以供明确参考。谢谢。
  • ©Anand servlet 上下文是单个服务器上的单个 (java) Web 应用程序或更准确地说是容器)。我会在明天之前添加更多细节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-22
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
相关资源
最近更新 更多