Search code examples
javajspsessionservletsservlet-listeners

i need to redirect page after particular session count


I am creating one web application, in that application im creating sessionlistener. In that session listener if condition is not working how to redirect page to another page after reaching particular session count.

import java.awt.Window;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.xml.ws.Response;


public class SessionListener implements HttpSessionListener {
    private int sessionCount = 0;
    HttpServletResponse response;

    public void sessionCreated(HttpSessionEvent event) {
        synchronized (this) {

            sessionCount++; 

            if(sessionCount>=2)
            {

                response.sendRedirect("Error.jsp");
            }

        }

        System.out.println("Session Created1: " + event.getSession().getId());



        System.out.println("Total Sessions1: " + sessionCount);



    }

    public void sessionDestroyed(HttpSessionEvent event) {
        synchronized (this) {
            sessionCount--;
        }
        System.out.println("Session Destroyed: " + event.getSession().getId());
        System.out.println("Total Sessions: " + sessionCount);
    }
}

i map this class file in xml.


Solution

  • You can not redirect from your Listener,for redirection you'll have to write redirection code in servelet , jsp and filter.

    Here's the solution.

    Store Session_Count inside application scope and check the value of Session_count on every web page ,by these two ways.

    a.) Creating a Filter with \* url-pattern and add redirection code inside it.

    OR

    b.) Including a common jsp(that would contains the code for redirection) at top of every other web pages . Or add the redirection code manually in every web page.

    • Update you Listener

      public class SessionListener implements HttpSessionListener { private Integer sessionCount;

      public void sessionCreated(HttpSessionEvent event) {
          synchronized (this) {
              ServletContext application = event.getSession().getServletContext();
              sessionCount = (Integer) application.getAttribute("SESSION_COUNT");
              if (sessionCount == null) {
                  application.setAttribute("SESSION_COUNT", (sessionCount = 1));//setting sessioncount inside application scope
              } else {
                  application.setAttribute("SESSION_COUNT", sessionCount + 1);
              }
              System.out.println("Session Created1: "+ event.getSession().getId());
              System.out.println("Total Sessions1: " + sessionCount);
          }
      }
      
      public void sessionDestroyed(HttpSessionEvent event) {
          synchronized (this) {
              ServletContext application = event.getSession().getServletContext();
              sessionCount = (Integer) application.getAttribute("SESSION_COUNT");
              application.setAttribute("SESSION_COUNT", sessionCount - 1);
          }
          System.out.println("Session Destroyed: " + event.getSession().getId());
          System.out.println("Total Sessions: " + sessionCount);
      }
      

      }

    • Create a filter with <url-pattern>/*</url-pattern> as follows.

          @WebFilter("/*")
          public class redirectOnSessionCount implements Filter {
          public void destroy() {
              // TODO Auto-generated method stub
          }
          public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              HttpServletResponse httpResponse = (HttpServletResponse) response;
              HttpServletRequest httpRequest = (HttpServletRequest)request;
              Integer sessionCount = (Integer) request.getServletContext().getAttribute("SESSION_COUNT");//fetching session count from application scope
                  if(sessionCount!=null && sessionCount>2 && ! httpRequest.getRequestURL().toString().contains("Error.jsp")){
                   //httpRequest.getRequestURL().toString().contains("Error.jsp") - > if it's already redirecting to error.jsp then no redirection 
                      httpResponse.sendRedirect("Error.jsp");//redirection code
                  }
              chain.doFilter(request, response);
          }
      
          public void init(FilterConfig fConfig) throws ServletException {
              // TODO Auto-generated method stub
          }
      
      }
      
    • Mapping inside web.xml for filter.

      <filter>
          <filter-name>redirectOnSessionCount</filter-name>
          <filter-class>redirectOnSessionCount</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>redirectOnSessionCount</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>
      

    Update :-

    • Without using filter

    Create a redirectOnSessionCount.jsp as follows and include this in your all pages at the top or add this code to each web page.

    <%
    Integer sessionCount = (Integer) application.getAttribute("SESSION_COUNT");//fetching session count from application scope
    if(sessionCount!=null && sessionCount>2){
        response.sendRedirect("Error.jsp");//redirection code
    }
    %>