/**
   * Deletes a meeting from the database
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    if (req.getMethod() == HttpMethod.Get) {

      // Get the meeting
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      MeetingManager meetingMan = new MeetingManager();
      Meeting meeting = meetingMan.get(meetingId);
      meetingMan.deleteMeeting(meetingId);

      // Update the User Session to remove meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      List<Meeting> adminMeetings = userSession.getUser().getMeetings();

      for (int i = 0; i < adminMeetings.size(); i++) {
        Meeting m = adminMeetings.get(i);
        if (m.getId() == meeting.getId()) {
          adminMeetings.remove(i);
          break;
        }
      }

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } else if (req.getMethod() == HttpMethod.Post) {
      httpNotFound(req, res);
    }
  }
Ejemplo n.º 2
1
  public static void showSession(HttpServletRequest req, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    out.println("Session id: " + session.getId());
    out.println(" session.isNew(): " + session.isNew());
    out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
    out.println(
        " session.getCreationTime(): "
            + session.getCreationTime()
            + " ("
            + new Date(session.getCreationTime())
            + ")");
    out.println(
        " session.getLastAccessedTime(): "
            + session.getLastAccessedTime()
            + " ("
            + new Date(session.getLastAccessedTime())
            + ")");
    out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
    out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
    out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());

    out.println("Saved session Attributes:");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
    }
  }
  /**
   * Creates a Discussion Post
   *
   * <p>- Requires a cookie for the session user - Requires a comment and threadId request parameter
   * for the POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void createPostAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<>();

    if (req.getMethod() == HttpMethod.Post) {
      DiscussionManager dm = new DiscussionManager();

      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");

      // Create the discussion post
      DiscussionPost post = new DiscussionPost();
      post.setUserId(userSession.getUserId());
      post.setMessage(req.getParameter("comment"));
      post.setThreadId(Integer.parseInt(req.getParameter("threadId")));

      dm.createPost(post);

      redirectToLocal(req, res, "/group/discussion/?threadId=" + req.getParameter("threadId"));
    } else {
      httpNotFound(req, res);
    }
  }
Ejemplo n.º 4
1
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {

      String target = ((HttpServletRequest) request).getRequestURI();

      HttpSession session = ((HttpServletRequest) request).getSession();

      if (session == null) {
        /* まだ認証されていない */
        session = ((HttpServletRequest) request).getSession(true);
        session.setAttribute("target", target);
        ((HttpServletResponse) response).sendRedirect("/refrigerator/LoginPage");
      } else {
        Object loginCheck = session.getAttribute("login");
        if (loginCheck == null) {
          /* まだ認証されていない */
          session.setAttribute("target", target);
          ((HttpServletResponse) response).sendRedirect("/refrigerator/LoginPage");
        }
      }

      chain.doFilter(request, response);

    } catch (ServletException se) {
    } catch (IOException e) {
    }
  }
Ejemplo n.º 5
1
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    HttpSession session = request.getSession();
    PrintWriter out = response.getWriter();
    StringBuilder sb = new StringBuilder();

    HashMap<String, String> userInfo = (HashMap<String, String>) session.getAttribute("userInfo");
    String ticket = request.getParameter("ticket");

    if (userInfo == null) {
      response.sendRedirect(response.encodeRedirectUrl(request.getContextPath() + "/SignIn"));
    } else {
      if (userInfo.get("role").equals("technician")) {
        sb.append(LayoutProvider.getInstance().getLoggedInHeader(userInfo.get("name")));
        sb.append("<div id=\"body\">");
        sb.append(
            "<h3>Schedule Confirmation</h3><p>You have scheduled <strong>ticket # "
                + ticket
                + "</strong></p>");
        if (ticket != null) {
          List<String> tickets;
          try {
            if (userInfo.get("tickets").equals("")) {
              tickets = null;
            } else {
              tickets = Arrays.asList(userInfo.get("tickets").split("\\,"));
            }
          } catch (Exception ex) {
            System.out.println("PayBill: error splitting tickets");
            tickets = null;
          }
          String remaining = "";
          if (tickets != null && tickets.size() > 0) {
            for (String t : tickets) {
              if (!t.equals(ticket)) {
                remaining += t + ",";
              }
            }
            if (remaining.length() > 0) remaining = remaining.substring(0, remaining.length() - 1);
          } else {
            remaining = "";
          }
          userInfo.put("tickets", remaining);
        }
        sb.append("</div>");
      } else {
        sb.append("<h2>Error</h2>");
        sb.append("<p>You do not have access to this page.</p>");
        sb.append("</div>");
      }
    }
    out.println(sb.toString());
    out.close();
  }
Ejemplo n.º 6
0
  public String getTokenValue(HttpServletRequest request, String uri) {
    String tokenValue = null;
    HttpSession session = request.getSession(false);

    if (session != null) {
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        if (pageTokens != null) {
          if (isTokenPerPagePrecreate()) {
            createPageToken(pageTokens, uri);
          }
          tokenValue = pageTokens.get(uri);
        }
      }

      if (tokenValue == null) {
        tokenValue = (String) session.getAttribute(getSessionKey());
      }
    }

    return tokenValue;
  }
Ejemplo n.º 7
0
  public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    // Increment the hit count for this page. The value is saved
    // in this client's session under the name "snoop.count".
    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null) {
      count = 1;
    } else count = count + 1;
    session.setAttribute("snoop.count", count);

    out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag());
    out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    // Display the hit count for this page
    out.println(
        "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println(
        "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
  }
 /**
  * Permet de repondre a une requete web En affichant la liste des Spectacles et representations :
  * Utiliste JQuery javascript pour la mise en forme
  *
  * @param HttpServletRequest request requete
  * @param HttpServletResponse response reponse
  * @throw IOException, ServletException
  * @return void
  */
 public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   // Get the session object
   HttpSession session = req.getSession(true);
   // Get the output stream
   ServletOutputStream out = res.getOutputStream();
   res.setContentType("text/html");
   out.println("<HEAD><TITLE>Reservation de tickets </TITLE></HEAD><BODY>");
   out.println("<h1> Reservations de tickets </h1>");
   out.println("<BODY bgproperties=\"fixed\" background=\"/images/rideau.JPG\">");
   out.println("<p align=\"Right\"><font face=\"Monotype Corsiva\"style=\"font-size: 16pt\">");
   try {
     // Open the file that is the first
     // command line parameter
     String relativeWebPath = "/WEB-INF/files/JAVASCRIPTPROG.txt";
     String absoluteDiskPath = this.getServletContext().getRealPath(relativeWebPath);
     File file = new File(absoluteDiskPath);
     FileInputStream fstream = new FileInputStream(file);
     // Get the object of DataInputStream
     DataInputStream in = new DataInputStream(fstream);
     BufferedReader br = new BufferedReader(new InputStreamReader(in));
     String strLine;
     // Read File Line By Line
     while ((strLine = br.readLine()) != null) {
       // Print the content on the console
       out.println(strLine);
     }
     // Close the input stream
     in.close();
   } catch (Exception e) { // Catch exception if any
     out.println("Error: " + e.getMessage());
   }
   if (session.isNew() || session.getAttribute("session.PanierListe") == null)
     out.println("<a href=\"admin/admin.html\">Caddie (vide)</a></font><br></p>");
   else if (session.getAttribute("session.PanierListe") != null)
     if (((PanierListe) session.getAttribute("session.PanierListe")).getSize() > 0)
       out.println(
           "<a href=\"admin/admin.html\">afficher caddie("
               + ((PanierListe) session.getAttribute("session.PanierListe")).Liste.size()
               + "Representations dans le panier)"
               + "</a></font><br></p>");
   try {
     Utilisateur user = Utilitaires.Identification(this);
     out.println(Utilitaires.AffichageAchat(user));
   } catch (Exception e) {
     out.println(e.getMessage());
   }
   out.println("</BODY>");
   out.close();
 }
Ejemplo n.º 9
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;

    Integer accessCount = (Integer) session.getAttribute("accessCount");

    if (accessCount == null) {
      accessCount = new Integer(0);
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      accessCount = new Integer(accessCount.intValue() + 1);
    }

    session.setAttribute("accessCount", accessCount);
    out.println(
        "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=\"CENTER\">"
            + heading
            + "</H1>\n"
            + "<H2>Information on Your Session:</H2>\n"
            + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "  <TH>Info Type<TH>Value\n"
            + "<TR>\n"
            + "  <TD>ID\n"
            + "  <TD>"
            + session.getId()
            + "\n"
            + "<TR>\n"
            + "  <TD>Creation Time\n"
            + "  <TD>"
            + new Date(session.getCreationTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Time of Last Access\n"
            + "  <TD>"
            + new Date(session.getLastAccessedTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Number of Previous Accesses\n"
            + "  <TD>"
            + accessCount
            + "\n"
            + "</TR>"
            + "</TABLE>\n");

    // the following two statements show how to retrieve parameters in
    // the request.  The URL format is something like:
    // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li
    String myname = request.getParameter("myname");
    if (myname != null) out.println("Hey " + myname + "<br><br>");

    out.println("</BODY></HTML>");
  }
  public Event perform(HttpServletRequest request) throws HTMLActionException {

    HttpSession session = request.getSession();
    // look up the adventure transportation
    AdventureComponentManager acm =
        (AdventureComponentManager) session.getAttribute(AdventureKeys.COMPONENT_MANAGER);
    Cart cart = acm.getCart(session);
    String origin = request.getParameter("origin");
    // if we are doing a search for a different flight from the cart page
    if (origin == null) {
      origin = cart.getOrigin();
    } else {
      cart.setOrigin(origin);
    }

    String noTransport = request.getParameter("no_transport");
    String showTransport = request.getParameter("show_flights");
    Locale locale = new Locale("en", "us");
    String destination = cart.getDestination();
    // access catalog component and retrieve data from the database
    List transpDepartureBeans = searchTransportation(origin, destination, locale);
    List transpReturnBeans = searchTransportation(destination, origin, locale);

    // places result bean data in the request
    request.setAttribute("departure_result", transpDepartureBeans);
    request.setAttribute("return_result", transpReturnBeans);
    request.setAttribute("search_target", "transportation");
    return null;
  }
Ejemplo n.º 11
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    String support = "support"; // valid username

    HttpSession session = null;
    session = req.getSession(false); // Get user's session object (no new one)
    if (session == null) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String userName = (String) session.getAttribute("user"); // get username

    if (!userName.equals(support)) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String action = "";
    if (req.getParameter("todo") != null) action = req.getParameter("todo");

    if (action.equals("update")) {

      doUpdate(out);
      return;
    }

    out.println("<p>Nothing to do.</p>todo=" + action);
  }
Ejemplo n.º 12
0
  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      userMap.clear();
    }
    String key = pathInfo.substring(1);
    userMap.remove(key);
    saveUserSettingsMap(username, userMap);
    return;
  }
Ejemplo n.º 13
0
  public synchronized void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    HttpSession dbSession = request.getSession();
    JspFactory _jspxFactory = JspFactory.getDefaultFactory();
    PageContext pageContext =
        _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
    ServletContext dbApplication = dbSession.getServletContext();

    ServletContext application;
    HttpSession session = request.getSession();
    nseer_db_backup1 finance_db = new nseer_db_backup1(dbApplication);

    try {

      if (finance_db.conn((String) dbSession.getAttribute("unit_db_name"))) {
        String finance_cheque_id = request.getParameter("finance_cheque_id");
        String sql = "delete from finance_bill where id='" + finance_cheque_id + "'";
        finance_db.executeUpdate(sql);
        finance_db.commit();
        finance_db.close();

      } else {
        response.sendRedirect("error_conn.htm");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Ejemplo n.º 14
0
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    if (pathInfo.equals("/")) {
      HttpSession session = req.getSession();
      if (session == null) {
        resp.setStatus(401);
        return;
      }
      String username = (String) session.getAttribute("username");
      if (username == null) {
        resp.setStatus(401);
        return;
      }

      Map userMap = loadUserSettingsMap(username);
      if (userMap == null) {
        resp.setStatus(401);
        return;
      }
      Enumeration parameterNames = req.getParameterNames();
      while (parameterNames.hasMoreElements()) {
        String parameterName = (String) parameterNames.nextElement();
        userMap.put(parameterName, req.getParameter(parameterName));
      }
      saveUserSettingsMap(username, userMap);
      return;
    }

    super.doPost(req, resp);
  }
Ejemplo n.º 15
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      resp.setContentType("application/json; charset=UTF-8");
      resp.getWriter().write(JSONUtil.write(userMap));
      return;
    }

    String key = pathInfo.substring(1);
    String value = (String) userMap.get(key);

    Map jsonObject = new HashMap();
    jsonObject.put(key, value);
    resp.setContentType("application/json; charset=UTF-8");
    resp.getWriter().write(JSONUtil.write(jsonObject));
  }
  /**
   * Method execute
   *
   * @param ActionMapping mapping
   * @param ActionForm form
   * @param HttpServletRequest request
   * @param HttpServletResponse response
   * @return ActionForward
   * @throws Exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    HttpSession session = request.getSession();
    // clientXML = (XMLClient) session.getAttribute("client");
    clientXML = XMLClient.getInstance();
    sessionLogin = (String) session.getAttribute("login");

    ajoutsuppressionForm ajoutForm = (ajoutsuppressionForm) form;

    String idperm = ajoutForm.getId1();
    String idrole = ajoutForm.getId2();

    response.setContentType("text/html");

    boolean ajout = clientXML.ajouterPermissionRole(sessionLogin, idperm, idrole);

    if (ajout) {
      String result = "INFO: Permission ajoutée au role";

      session.setAttribute("Resultat", result);
      return mapping.findForward("ok");
    } else {
      String erreur = "ERREUR: Permission non ajoutée au role";

      session.setAttribute("Resultat", erreur);
      return mapping.findForward("failed");
    }
  }
Ejemplo n.º 17
0
  private void rotateTokens(HttpServletRequest request) {
    HttpSession session = request.getSession(true);

    /** rotate master token * */
    String tokenFromSession = null;

    try {
      tokenFromSession = RandomGenerator.generateRandomId(getPrng(), getTokenLength());
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
    }

    session.setAttribute(getSessionKey(), tokenFromSession);

    /** rotate page token * */
    if (isTokenPerPageEnabled()) {
      @SuppressWarnings("unchecked")
      Map<String, String> pageTokens =
          (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

      try {
        pageTokens.put(
            request.getRequestURI(), RandomGenerator.generateRandomId(getPrng(), getTokenLength()));
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
      }
    }
  }
Ejemplo n.º 18
0
  /**
   * Parse the case id from the url and then delete it. Finally redirects the response and the
   * request to admCase.jsp
   *
   * @see DatabaseMethods#caseDelete(int)
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    DatabaseMethods dbPoint = new DatabaseMethods();
    HttpSession userSession = request.getSession();

    if (Integer.parseInt(userSession.getAttribute("isadmin").toString()) == 1) {
      int caseId = Integer.parseInt(request.getParameter("caseId"));

      int success = dbPoint.caseDelete(caseId);

      if (success != 0) {
        userSession.setAttribute("caseDelete", "1");
      } else {
        userSession.setAttribute("caseDelete", "0");
      }
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/admCase.jsp");
    if (rd != null) {
      rd.forward(request, response);
    }
  }
Ejemplo n.º 19
0
  public void updateTokens(HttpServletRequest request) {
    /** cannot create sessions if response already committed * */
    HttpSession session = request.getSession(false);

    if (session != null) {
      /** create master token if it does not exist * */
      updateToken(session);

      /** create page specific token * */
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        /** first time initialization * */
        if (pageTokens == null) {
          pageTokens = new HashMap<String, String>();
          session.setAttribute(CsrfGuard.PAGE_TOKENS_KEY, pageTokens);
        }

        /** create token if it does not exist * */
        if (isProtectedPageAndMethod(request)) {
          createPageToken(pageTokens, request.getRequestURI());
        }
      }
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      /*String n=request.getParameter("username");
      out.print("Welcome "+n);*/

      String name = request.getParameter("name");
      String dob = request.getParameter("dob");
      String address = request.getParameter("address");
      String email = request.getParameter("email");
      HttpSession session = request.getSession(true);
      String userid = (String) session.getAttribute("theName");
      int AccNo = 0;
      String AccMsg = "";

      DbCommunication db_comm = new DbCommunication();
      AccNo = db_comm.accountCreation(name, dob, address, email, userid);
      // db_comm.accountCreation(name,email);
      AccMsg = "Account created successfully. Account number is:" + AccNo;
      // out.println(AccMsg);

      String redirectURL = "accountCreationPage.jsp";
      response.sendRedirect(redirectURL);
      session.setAttribute("AccCreationalMsgStatus", "set");
      session.setAttribute("AccCreationalMsg", AccMsg);

    } catch (Exception e) {
      System.out.println(e);
    }
  }
Ejemplo n.º 21
0
  /**
   * Get a populated User object from the request passed in.
   *
   * @param The request object to check for the user
   * @return The user object, or null if no user object was found
   */
  public static User getUser(HttpServletRequest request) {
    HttpSession session = request.getSession();
    if (session == null) {
      return null;
    }

    return (User) (session.getAttribute("user"));
  }
Ejemplo n.º 22
0
 public void sessionDestroyed(HttpSessionEvent evt) {
   // Note: Session Fixation Protection (such as Spring Security)
   // might invalidate HTTP session and restore with a new one.
   // Thus, we use an attribute to denote this case and avoid the callback
   final HttpSession hsess = evt.getSession();
   if (hsess.getAttribute(Attributes.RENEW_NATIVE_SESSION) == null)
     WebManager.sessionDestroyed(hsess);
 }
Ejemplo n.º 23
0
 public void sessionDestroyed(HttpSessionEvent se) {
   /* Session is destroyed. */
   System.out.println("用户走了,而且彻底走了");
   HttpSession session = se.getSession();
   String str = (String) session.getAttribute("userName");
   UserAcount uac = UserAcount.getInstance();
   uac.remove(str);
 }
Ejemplo n.º 24
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    /* Get Session */
    HttpSession s = req.getSession(true);
    /* Make sure user is logged in */
    if (s.getAttribute("login") == null || (String) s.getAttribute("login") != "go") {
      req.getRequestDispatcher("login.jsp").forward(req, res);
    }

    try {
      String dbuser = this.getServletContext().getInitParameter("dbuser");
      String dbpassword = this.getServletContext().getInitParameter("dbpassword");

      Class.forName("com.mysql.jdbc.Driver");
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/project", dbuser, dbpassword);

      Statement stmt = conn.createStatement();
      stmt.execute(
          "INSERT INTO songs VALUES(null, '"
              + req.getParameter("song_name")
              + "', '"
              + req.getParameter("artist")
              + "', '"
              + req.getParameter("album")
              + "', '"
              + req.getParameter("genre")
              + "', 0)");

      stmt.close();
      conn.close();

      // delete memcache since new song is now added
      MemcachedClient c = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
      c.delete("master");

      req.getRequestDispatcher("add_song_success.jsp").forward(req, res);

    } catch (Exception e) {
      out.println(e.getMessage());
    }
  }
Ejemplo n.º 25
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter pw = response.getWriter();
   HttpSession session = request.getSession();
   String str = (String) session.getAttribute("foo");
   pw.println("The name is " + str);
 }
Ejemplo n.º 26
0
 public String getPageIds(ClientRequest cr) {
   HttpSession session = cr.getServletRequest().getSession();
   PageState.AllPageInfo info = (PageState.AllPageInfo) session.getAttribute("fiz.PageState");
   if (info == null) {
     return "";
   }
   Object[] keys = info.keySet().toArray();
   Arrays.sort(keys);
   return StringUtil.join(keys, ", ");
 }
Ejemplo n.º 27
0
 /** Get the object associated with the ID in the session */
 protected Object getSessionIdObject(String id) {
   HttpSession session = getSession();
   synchronized (session) {
     BidiMap map = (BidiMap) session.getAttribute(SESSION_KEY_OBJ_MAP);
     if (map == null) {
       return null;
     }
     return map.getKey(id);
   }
 }
Ejemplo n.º 28
0
 public Integer setSession(HttpSession ses) {
   Integer count = (Integer) ses.getAttribute("Counter");
   if (count != null) {
     ses.setAttribute("Counter", ++count);
     return count + 1;
   } else {
     ses.setAttribute("Counter", 1);
     return 1;
   }
 }
Ejemplo n.º 29
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    HttpSession session = req.getSession();
    String exitParam = req.getParameter("exit");
    String deleteParam = req.getParameter("delete");
    String settingsParam = req.getParameter("settings");

    if ("settings".equals(settingsParam)) {
      resp.sendRedirect("/profileSettings");
      return;
    }

    if ("exit".equals(exitParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/login");
    }

    if ("delete".equals(deleteParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      try {
        UserRepository.deleteUser((User) session.getAttribute("user_a"));
      } catch (SQLException e) {
        req.setAttribute("message", "Some problems with server");
        resp.sendRedirect("/profile");

        e.printStackTrace();
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/welcome");
    }
  }
  // required doFilter method
  // redirects users trying to access restricted part of site when not logged in
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws java.io.IOException, javax.servlet.ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession();

    String loggedIn = (String) session.getAttribute("loggedIn");

    if (loggedIn == null) res.sendRedirect("../pleaselogin.html");
    else if (loggedIn == "yes") chain.doFilter(request, response);
  }