Example #1
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) {
    }
  }
Example #2
1
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.print("<html><head><title>Page2</title></head><body>");
    Users tmpUser = null;
    HttpSession session;

    tmpUser = usersService.findByLogin(request.getParameter("login"));
    if (tmpUser != null) {
      if ((tmpUser.getPassword()).equals(request.getParameter("password"))) {
        session = request.getSession(true);
        session.setAttribute("users", tmpUser);
        response.sendRedirect("http://localhost:8080/orders");
      } else {
        out.print("Access denied :(");
      }

    } else {
      String login = request.getParameter("login");
      String pass = request.getParameter("password");
      tmpUser = new Users(login, pass);
      usersService.saveUsers(tmpUser);
      session = request.getSession(true);
      session.setAttribute("users", tmpUser);
      response.sendRedirect("http://localhost:8080/orders");
    }
    out.print("</body></html>");
  }
  private void processReturn(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Account principal = this.verifyResponse(req);

    // System.out.println(principal);

    String returnURL = req.getParameter("exist_return");

    if (principal == null) {
      // this.getServletContext().getRequestDispatcher("/openid/login.xql").forward(req, resp);
      resp.sendRedirect(returnURL);
    } else {
      HttpSession session = req.getSession(true);

      // ((XQueryURLRewrite.RequestWrapper)req).setUserPrincipal(principal);

      Subject subject = new Subject();

      // TODO: hardcoded to jetty - rewrite
      // *******************************************************
      DefaultIdentityService _identityService = new DefaultIdentityService();
      UserIdentity user = _identityService.newUserIdentity(subject, principal, new String[0]);

      Authentication cached = new HttpSessionAuthentication(session, user);
      session.setAttribute(HttpSessionAuthentication.__J_AUTHENTICATED, cached);
      // *******************************************************

      resp.sendRedirect(returnURL);
    }
  }
  /**
   * 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");
    }
  }
Example #5
0
 /**
  * Adds pair of session and user to the map of active users.
  *
  * @param session the session
  * @param user the user
  */
 public void add(final HttpSession session, final String user) {
   session.setAttribute("User", user);
   session.setAttribute("UserManager", this);
   this.users.put(session, user);
   System.out.println("Login: "******"Logged in users: " + this.users.size());
 }
Example #6
0
  /**
   * Validates the login. Writes the isValid flag into the session along with the current user.
   *
   * @return true if OK, false if there's a problem
   */
  private boolean validateLogin(
      HttpSession session, HttpServletRequest req, HttpServletResponse res) throws Exception {

    // Creates a user database access bean.
    UserManager userManager = new UserManager();
    // (no setSession() here, since user may not exist yet)

    // Validates the login
    String username = req.getParameter("Username");
    String password = req.getParameter("Password");
    boolean isValid = userManager.isValidUser(username, password);
    boolean isAdmin = userManager.isAdmin(username);

    // To allow bootstrapping the system, if there are no users
    // yet, set this session valid, and grant admin privileges.
    if (userManager.getRecords().isEmpty()) {
      isValid = true;
      isAdmin = true;
    }

    if (isValid) {
      // Writes User object and validity flag to the session
      session.setAttribute("user", new User(username, password, isAdmin));
      session.setAttribute("isValid", new Boolean(isValid));
    } else {
      Util.putMessagePage(res, "Invalid user or password");
      return false;
    }
    return isValid;
  }
  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);
    }
  }
Example #8
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);
    }
  }
Example #9
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;
   }
 }
  @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");
    }
  }
Example #11
0
	public void loginRoom(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		HttpSession session = request.getSession();
		String username=request.getParameter("username");	//获得登录用户名
		UserInfo user=UserInfo.getInstance();		//获得UserInfo类的对象
		session.setMaxInactiveInterval(600);		//设置Session的过期时间为10分钟
		Vector vector=user.getList();
		boolean flag=true;		//标记是否登录的变量
		//判断用户是否登录
		System.out.println("vector的size:"+vector.size());
		if(vector!=null&&vector.size()>0){
			for(int i=0;i<vector.size();i++){
				System.out.println("vector"+i+":"+vector.elementAt(i)+" user:"******"<script language='javascript'>alert('该用户已经登录');window.location.href='index.jsp';</script>");
					} catch (IOException e) {
						e.printStackTrace();
					}
					flag=false;
					break;
				}
			}
		}
		//保存用户信息
		if(flag){
			UserListener ul=new UserListener();					//创建UserListener的对象
			ul.setUser(username);								//添加用户
			user.addUser(ul.getUser());							//添加用户到UserInfo类的对象中
			session.setAttribute("user",ul);						//将UserListener对象绑定到Session中
			session.setAttribute("username",username);	//保存当前登录的用户名
			session.setAttribute("loginTime",new Date().toLocaleString());		//保存登录时间
        ServletContext application=getServletContext();

        String sourceMessage="";

        if(null!=application.getAttribute("message")){
            sourceMessage=application.getAttribute("message").toString();
        }
        sourceMessage+="系统公告:<font color='gray'>" + username + "走进了聊天室!</font><br>";
        application.setAttribute("message",sourceMessage);
        try {
            request.getRequestDispatcher("login_ok.jsp").forward(request, response);
        } catch (Exception ex) {
            Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, ex);
        }
		}
	}
Example #12
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 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());
        }
      }
    }
  }
  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);
      }
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    String amount = request.getParameter("amount");
    String amount2 = request.getParameter("amount2");
    String amount3 = request.getParameter("amount3");
    Integer posotita = Integer.parseInt(amount);
    Integer posotita2 = Integer.parseInt(amount2);
    Integer posotita3 = Integer.parseInt(amount3);

    HttpSession session = request.getSession();

    if (session.isNew()) {
      request.setAttribute("sessionVal", "this is a new session");
    } else {
      request.setAttribute("sessionVal", "Welcome Back!");
    }

    double total = ((posotita * 18.50) + (posotita2 * 6.95) + (posotita3 * 1.29));
    session.setAttribute("totalVal", total);

    request.setAttribute("currency", total);
    request.setAttribute("from", amount);
    request.setAttribute("from2", amount2);
    request.setAttribute("from3", amount3);

    RequestDispatcher view = request.getRequestDispatcher("index.jsp");
    view.forward(request, response);
  }
  public static void afterRoot(
      FacesContext context, HttpServletRequest req, HttpServletResponse res) {
    HttpSession session = ((HttpServletRequest) req).getSession(false);

    if (session != null)
      session.setAttribute(ViewHandler.CHARACTER_ENCODING_KEY, res.getCharacterEncoding());
  }
Example #17
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // POST method only used for tracked login operation
    HttpSession session = request.getSession();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Get the username and password from request
    String username = request.getParameter("id");
    String password = request.getParameter("pwd");

    Long id = 0L;
    try {
      id = Long.parseLong(username);
    } catch (Exception ex) {
    }

    if (username != null && password != null) {
      // Login into tracked system
      CTracked ctracked = db.loginTrackedFromMobile(id, password).getResult();

      if (ctracked != null) {
        // Login successful
        out.print("OK," + ctracked.getUsername());
        session.setAttribute("device_id", ctracked.getUsername());
        log.info(ctracked + " : logined!");
      }
    }
  }
Example #18
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // get a connection
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();

    String sqlStatement = request.getParameter("sqlStatement");
    String sqlResult = "";
    try {
      // create a statement
      Statement statement = connection.createStatement();

      // parse the SQL string
      sqlStatement = sqlStatement.trim();
      if (sqlStatement.length() >= 6) {
        String sqlType = sqlStatement.substring(0, 6);
        if (sqlType.equalsIgnoreCase("select")) {
          // create the HTML for the result set
          ResultSet resultSet = statement.executeQuery(sqlStatement);
          sqlResult = SQLUtil.getHtmlTable(resultSet);
          resultSet.close();
        } else {
          int i = statement.executeUpdate(sqlStatement);
          if (i == 0) {
            sqlResult = "<p>The statement executed successfully.</p>";
          } else { // an INSERT, UPDATE, or DELETE statement
            sqlResult = "<p>The statement executed successfully.<br>" + i + " row(s) affected.</p>";
          }
        }
      }
      statement.close();
      connection.close();
    } catch (SQLException e) {
      sqlResult = "<p>Error executing the SQL statement: <br>" + e.getMessage() + "</p>";
    } finally {
      pool.freeConnection(connection);
    }

    HttpSession session = request.getSession();
    session.setAttribute("sqlResult", sqlResult);
    session.setAttribute("sqlStatement", sqlStatement);

    String url = "/index.jsp";
    getServletContext().getRequestDispatcher(url).forward(request, response);
  }
Example #20
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>");
  }
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   String uID = req.getParameter("email");
   String pass = req.getParameter("password");
   if (validate(uID, pass)) {
     System.out.println("Valid");
     HttpSession sess = req.getSession();
     String type = getType();
     sess.setAttribute("Name", getName());
     sess.setAttribute("Type", type);
     sess.setAttribute("uID", uID);
     res.sendRedirect("/loginCheck");
   } else {
     PrintWriter out = res.getWriter();
     out.println("<script type=\"text/javascript\">");
     out.println("alert('Invalid Details. Please Try Again.');");
     out.println("window.location = '/loginCheck';");
     out.println("</script>");
   }
 }
Example #22
0
 /** Get an unused ID string for storing an object in the session */
 protected String getNewSessionObjectId() {
   HttpSession session = getSession();
   synchronized (session) {
     Integer id = (Integer) getSession().getAttribute(SESSION_KEY_OBJECT_ID);
     if (id == null) {
       id = new Integer(1);
     }
     session.setAttribute(SESSION_KEY_OBJECT_ID, new Integer(id.intValue() + 1));
     return id.toString();
   }
 }
Example #23
0
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   HttpSession session = req.getSession(false);
   ServletContext sc = getServletContext();
   RequestDispatcher rd;
   String strPrizeID = req.getParameter("prizeid");
   if (strPrizeID != null) {
     DataBaseConn DelPrizeDBC = new DataBaseConn();
     String sqlStr = "delete from pthwinnum where id='" + Integer.parseInt(strPrizeID) + "';";
     DelPrizeDBC.execute(sqlStr);
     DelPrizeDBC.connCloseUpdate();
   }
   PageInfoGet objPageInfoGet = new PageInfoGet();
   String strChSql = "select id from pthwinnum";
   objPageInfoGet.generInfo(req, "pthwinnum", strChSql);
   session.setAttribute("userpc", objPageInfoGet.getUserPageConn());
   session.setAttribute("bepagshow", objPageInfoGet.getBeanPageShow());
   rd = sc.getRequestDispatcher("/WEB-INF/usermanage/pth/pthprizepage.jsp");
   rd.forward(req, res);
 }
  /**
   * 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");

    planifProgForm planifForm = (planifProgForm) form;

    String idprog = planifForm.getIdprog();
    String idcanal = planifForm.getIdcanal();
    String jour = planifForm.getJour();
    String mois = planifForm.getMois();
    String annee = planifForm.getAnnee();
    String heure = planifForm.getHeure();
    String minute = planifForm.getMinute();
    String seconde = planifForm.getSeconde();

    response.setContentType("text/html");

    boolean planifie =
        clientXML.planifierProgramme(
            sessionLogin, idprog, idcanal, jour, mois, annee, heure, minute, seconde);

    if (planifie) {
      String result = "INFO: Programme planifié sur le canal";

      session.setAttribute("Resultat", result);
      return mapping.findForward("ok");
    } else {
      String erreur = "ERREUR: Programme non planifié";

      session.setAttribute("Resultat", erreur);
      return mapping.findForward("failed");
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    HttpSession session = request.getSession();

    String name = request.getParameter("name");
    String ID = request.getParameter("ID");
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String position = request.getParameter("position");

    try {
      MD5Util.addNewStaff(name, Integer.parseInt(ID), email, password, position);
      session.setAttribute("AddStaff", "Yes");
    } catch (Exception e) {
      session.setAttribute("AddStaff", "No");
    }

    response.sendRedirect("/library/people.jsp");
  }
Example #26
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    response.setContentType("text/html;charset=windows-1252");
    /* set up the intrinsic variables using the pageContext goober:
     ** session = HttpSession
     ** application = ServletContext
     ** out = JspWriter
     ** page = this
     ** config = ServletConfig
     ** all session/app beans declared in globals.jsa
     */
    PageContext pageContext =
        JspFactory.getDefaultFactory()
            .getPageContext(this, request, response, null, true, JspWriter.DEFAULT_BUFFER, true);
    // Note: this is not emitted if the session directive == false
    HttpSession session = pageContext.getSession();
    if (pageContext.getAttribute(OracleJspRuntime.JSP_REQUEST_REDIRECTED, PageContext.REQUEST_SCOPE)
        != null) {
      pageContext.setAttribute(
          OracleJspRuntime.JSP_PAGE_DONTNOTIFY, "true", PageContext.PAGE_SCOPE);
      JspFactory.getDefaultFactory().releasePageContext(pageContext);
      return;
    }
    int __jsp_tag_starteval;
    ServletContext application = pageContext.getServletContext();
    JspWriter out = pageContext.getOut();
    _mainMib page = this;
    ServletConfig config = pageContext.getServletConfig();

    try {
      // global beans
      // end global beans

      /*@lineinfo:user-code*/
      /*@lineinfo:1^1*/
      session.setAttribute("ip", request.getParameter("ip"));

      /*@lineinfo:generated-code*/
      out.write(__oracle_jsp_text[0]);

    } catch (Throwable e) {
      try {
        if (out != null) out.clear();
      } catch (Exception clearException) {
      }
      pageContext.handlePageException(e);
    } finally {
      OracleJspRuntime.extraHandlePCFinally(pageContext, false);
      JspFactory.getDefaultFactory().releasePageContext(pageContext);
    }
  }
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = null;
    try {
      try {
        session = request.getSession(true);
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session");
        // rethrow the exception for handling in one place.
        throw e;
      }

      // Get the session data value
      Integer ival = (Integer) session.getAttribute("sessiontest.counter");
      // if there is not a counter then create one.
      if (ival == null) {
        ival = new Integer(1);
      } else {
        ival = new Integer(ival.intValue() + 1);
      }
      session.setAttribute("sessiontest.counter", ival);
      // if the session count is equal to five invalidate the session
      if (ival.intValue() == 5) {
        session.invalidate();
      }

      try {
        // Output the page
        response.setContentType("text/html");
        response.setHeader("SessionTrackingTest-counter", ival.toString());

        PrintWriter out = response.getWriter();
        out.println(
            "<html><head><title>Session Tracking Test 2</title></head><body><HR><BR><FONT size=\"+2\" color=\"#000066\">HTTP Session Test 2: Session create/invalidate <BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: "
                + initTime
                + "</FONT><BR><BR>");
        hitCount++;
        out.println(
            "<B>Hit Count: " + hitCount + "<BR>Session hits: " + ival + "</B></body></html>");
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session information");
        // rethrow the exception for handling in one place.
        throw e;
      }

    } catch (Exception e) {
      // log the excecption
      Log.error(e, "PingSession2.doGet(...): error.");
      // set the server responce to 500 and forward to the web app defined error page
      response.sendError(500, "PingSession2.doGet(...): error. " + e.toString());
    }
  } // end of the method
Example #28
0
  /** @service the servlet service request. called once for each servlet request. */
  public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException {
    String name;
    String value[];
    String val;

    servRes.setHeader("AUTHORIZATION", "user fred:mypassword");
    ServletOutputStream out = servRes.getOutputStream();

    HttpSession session = servReq.getSession(true);
    session.setAttribute("timemilis", new Long(System.currentTimeMillis()));
    if (session.isNew()) {
      out.println("<p> Session is new ");
    } else {
      out.println("<p> Session is not new ");
    }
    Long l = (Long) session.getAttribute("timemilis");
    out.println("<p> Session id = " + session.getId());
    out.println("<p> TimeMillis = " + l);

    out.println("<H2>Servlet Params</H2>");
    Enumeration e = servReq.getParameterNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      value = servReq.getParameterValues(name);
      out.println(name + " : ");
      for (int i = 0; i < value.length; ++i) {
        out.println(value[i]);
      }
      out.println("<p>");
    }

    out.println("<H2> Request Headers : </H2>");
    e = servReq.getHeaderNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      val = (String) servReq.getHeader(name);
      out.println("<p>" + name + " : " + val);
    }
    try {
      BufferedReader br = servReq.getReader();
      String line = null;
      while (null != (line = br.readLine())) {
        out.println(line);
      }
    } catch (IOException ie) {
      ie.printStackTrace();
    }

    session.invalidate();
  }
  public void updateToken(HttpSession session) {
    String tokenValue = (String) session.getAttribute(getSessionKey());

    /** Generate a new token and store it in the session. * */
    if (tokenValue == null) {
      try {
        tokenValue = 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(), tokenValue);
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    if (session == null) {
      response.sendRedirect("login.html");
      return;
    }

    String userName = (String) session.getAttribute("userName");
    if (isMissing(userName)) {
      response.sendRedirect("login.html");
      return;
    }
    String title = request.getParameter("title");
    String link = request.getParameter("link");
    String description = request.getParameter("description");
    session.setAttribute("title", title);
    session.setAttribute("link", link);
    session.setAttribute("description", description);
    String address = "WEB-INF/view/SaveBookmarkPage.jsp";
    String urlEncoding = response.encodeURL(address);
    RequestDispatcher dispatcher = request.getRequestDispatcher(urlEncoding);
    dispatcher.forward(request, response);
  }