Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jsp 我需要限制用户访问我的web应用程序_Jsp_Session_Servlets - Fatal编程技术网

Jsp 我需要限制用户访问我的web应用程序

Jsp 我需要限制用户访问我的web应用程序,jsp,session,servlets,Jsp,Session,Servlets,您好,我正在创建一个web应用程序,在该应用程序中,我希望限制访问用户的数量。例如:只有4个用户可以访问应用程序,如果超过4个用户,则会显示错误消息,如“限制超过”,直到4个用户中的任何一个注销。如果有4个用户中的任何一个注销,则意味着计数将为3,因此其他1个用户可以访问该应用程序。另一个最好的示例:stackoverflow页面中的声誉如果有人给出一个减分,它将反映在每个人的页面中 索引页: <%@page import="java.util.List"%> <%@page

您好,我正在创建一个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.
  } 
} 
import java.io.*;
导入javax.servlet.*;
导入javax.servlet.http.*;
//导入java.sql.Date;
//导入java.sql.SQLException;
//导入java.util.*;
//导入java.sql.*;
公共类PageHitCounter扩展了HttpServlet{
私人整数命中率;
公共void init()
{ 
//重置命中计数器。
命中率=0;
} 
公共无效数据集(HttpServletRequest请求,
HttpServletResponse(响应)
抛出ServletException、IOException
{
HttpSession session=request.getSession();
//设置响应内容类型
response.setContentType(“text/html”);
//每当命中servlet时,就会执行此方法
//递增命中率
if(session.getAttribute(“hitCount”)!=null){
字符串Aht=session.getAttribute(“hitCount”).toString();
int hitCount=Integer.parseInt(Aht);
系统输出打印项次(命中率);
命中率++;
System.out.println(“增量后”+hitCount++);

如果(命中率那么您希望将应用程序限制为最多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);
    }
}
使用此侦听器,会话计数默认存储在属性name
sessionCount
下,但它可以配置一个上下文参数name
session\u count.attr\u name
。并且对变量
sessionCount
的所有访问都正确同步,因为多个请求可以创建或关闭会话不是同一时间


您将在

不使用会话上找到所有引用。这对每个用户都是新的,请使用所有用户共享的
ServletContext在应用程序范围内保持
hitCount
users@Arvind是的,我也认为只有一个特定的用户注销意味着计数应该是3个用户,而对于另一个用户,计数将显示为3个用户实现处理传入请求的过滤器有一个计数器,在登录时递增,如果计数小于10,则在注销时递减。重定向到登录页面或重定向到某个错误page@SparkOn是的,谢谢。我不知道过滤器。你可以发送任何链接以供明确参考。谢谢。我理解,但我不知道t Context和listener您可以发送任何链接以供明确参考。谢谢。©Anand servlet Context是单个服务器或更确切地说是容器上的单个(java)web应用程序)。我将在明天之前添加更多详细信息。
@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);
    }
}