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);
    }
  }
Esempio n. 2
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) {
    }
  }
Esempio n. 3
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();
  }
  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);
    }
  }
Esempio n. 5
0
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   ArrayList<String> ar = new ArrayList<String>();
   boolean flag = false;
   Cookie[] cArr = req.getCookies();
   if (cArr != null) {
     for (int i = 0; i < cArr.length; i++) {
       Cookie c0 = cArr[i];
       if (c0.getName().equals("Name") && !c0.getValue().equals("Logout")) {
         res.sendRedirect("index.html");
         flag = true;
       }
     }
   }
   if (flag == false) res.sendRedirect("Login.html");
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   EstacionBombeoModule module = (EstacionBombeoModule) context.getBean("estacionBombeoModule");
   try {
     String presionSalida = request.getParameter("presionSalida");
     int presionSalidaObj = Integer.parseInt(presionSalida);
     String presionEntrada = request.getParameter("presionEntrada");
     int presionEntradaObj = Integer.parseInt(presionEntrada);
     String cantidadBombas = request.getParameter("cantidadBombas");
     int cantidadBombasObj = Integer.parseInt(cantidadBombas);
     String capacidadMaxima = request.getParameter("capacidadMaxima");
     int capacidadMaximaObj = Integer.parseInt(cantidadBombas);
     String idAcueducto = request.getParameter("idAcueducto");
     int idAcueductoObj = Integer.parseInt(idAcueducto);
     String encargado = request.getParameter("encargado");
     String tipo = request.getParameter("tipo");
     String telefono = request.getParameter("telefono");
     String nombreEstacion = request.getParameter("nombreEstacion");
     module.insertar(
         presionSalidaObj,
         tipo,
         capacidadMaximaObj,
         cantidadBombasObj,
         encargado,
         telefono,
         presionEntradaObj,
         idAcueductoObj,
         nombreEstacion);
     response.sendRedirect("listaEstacionBombeos");
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward(e.getMessage(), request, response);
   }
 }
 public void service(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   HttpSession sess = req.getSession(false);
   sess.invalidate();
   System.out.println("Session Closed");
   res.sendRedirect("index.html");
 }
  private void handleRemoveFeedPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    LOG.info("removing feed");
    User user = userHelpers.getUser(request);

    try {
      if (user == null) {
        LOG.error("User not found");
        return;
      }

      String feedId = request.getParameter(PARAM_FEED_ID);

      LOG.info(String.format("Removing feed %s for user %s", feedId, user));

      // ttt1 add some validation; probably best try to actually get data, set the title, ...
      if (feedId == null || feedId.equals("")) {
        LOG.error("feed not specified");
        // ttt1 show some error
        return;
      }

      if (user.feedIds.remove(
          feedId)) { // ttt2 clean up the global feed table; that's probably better done if nobody
                     // accesses a feed for 3 months or so
        userDb.updateFeeds(user);
        LOG.info(String.format("Removed feed %s for user %s", feedId, user));
      } else {
        LOG.info(String.format("No feed found with ID %s for user %s", feedId, user));
      }
    } finally {
      httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
    }
  }
Esempio n. 9
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Enumeration values = req.getParameterNames();
    String name = "";
    String value = "";
    String id = "";
    while (values.hasMoreElements()) {
      name = ((String) values.nextElement()).trim();
      value = req.getParameter(name).trim();
      if (name.equals("id")) id = value;
    }
    if (url.equals("")) {
      url = getServletContext().getInitParameter("url");
      cas_url = getServletContext().getInitParameter("cas_url");
    }
    HttpSession session = null;
    session = req.getSession(false);
    if (session != null) {
      session.invalidate();
    }
    res.sendRedirect(cas_url);
    return;
  }
Esempio n. 10
0
 private void handleOpenArticle(
     Request request, HttpServletResponse httpServletResponse, String target) throws Exception {
   try {
     int k1 = target.indexOf('/', 1);
     int k2 = target.indexOf('/', k1 + 1);
     String feedId = target.substring(k1 + 1, k2);
     String strSeq = target.substring(k2 + 1);
     int seq = Integer.parseInt(strSeq);
     Article article = articleDb.get(feedId, seq);
     LoginInfo loginInfo = userHelpers.getLoginInfo(request);
     // ttt2 using the link from a non-authenticated browser causes a NPE; maybe do something
     // better, e.g. sign up
     ReadArticlesColl readArticlesColl = readArticlesCollDb.get(loginInfo.userId, feedId);
     if (readArticlesColl == null) {
       readArticlesColl = new ReadArticlesColl(loginInfo.userId, feedId);
     }
     if (!readArticlesColl.isRead(seq)) {
       readArticlesColl.markRead(seq, Config.getConfig().maxSizeForReadArticles);
       readArticlesCollDb.add(readArticlesColl);
     }
     String s =
         URIUtil.encodePath(article.url)
             .replace("%3F", "?")
             .replace("%23", "#"); // ttt2 see how to do this right
     httpServletResponse.sendRedirect(s);
   } catch (Exception e) {
     WebUtils.showResult(
         String.format("Failed to get article for path %s. %s", target, e),
         "/",
         request,
         httpServletResponse);
   }
 }
Esempio n. 11
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();
    }
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   ProfesorRepository profesores = (ProfesorRepository) context.getBean("profesorRepository");
   try {
     String id = request.getParameter("id");
     int idProf = Integer.parseInt(id);
     String cedula = request.getParameter("cedula");
     String nombre = request.getParameter("nombre");
     String titulo = request.getParameter("titulo");
     String area = request.getParameter("area");
     String telefono = request.getParameter("telefono");
     Profesor prof = profesores.findProfesor(idProf);
     try {
       if (cedula != null) prof.setCedula(cedula);
       if (nombre != null) prof.setNombre(nombre);
       if (titulo != null) prof.setTitulo(titulo);
       if (area != null) prof.setArea(area);
       if (telefono != null) prof.setTelefono(telefono);
       profesores.updateProfesor(prof);
     } catch (Exception e) {
     }
     response.sendRedirect("listaProfesores");
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward("/paginaError.jsp", request, response);
   }
 }
Esempio n. 13
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException {
   try {
     ConnectionPool conPool = getConnectionPool();
     if (!realAuthentication(request, conPool)) {
       String queryString = request.getQueryString();
       if (request.getQueryString() == null) {
         queryString = "";
       }
       // if user is not authenticated send to signin
       response.sendRedirect(
           response.encodeRedirectURL(URLAUTHSIGNIN + "?" + URLBUY + "?" + queryString));
     } else {
       response.setHeader("Cache-Control", "no-cache");
       response.setHeader("Expires", "0");
       response.setHeader("Pragma", "no-cache");
       response.setContentType("text/html");
       String errorMessage = processRequest(request, response, conPool);
       if (errorMessage != null) {
         request.setAttribute(StringInterface.ERRORPAGEATTR, errorMessage);
         RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHUSERERROR);
         rd.include(request, response);
       }
     }
   } catch (Exception e) {
     throw new ServletException(e);
   }
 }
Esempio n. 14
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   request.setCharacterEncoding("gb2312");
   String delete = request.getParameter("delete");
   Login loginBean = null;
   HttpSession session = request.getSession(true);
   try {
     loginBean = (Login) session.getAttribute("loginBean");
     boolean b = loginBean.getLogname() == null || loginBean.getLogname().length() == 0;
     if (b) response.sendRedirect("login.jsp"); // 重定向到登录页面
     LinkedList<String> car = loginBean.getCar();
     car.remove(delete);
   } catch (Exception exp) {
     response.sendRedirect("login.jsp"); // 重定向到登录页面
   }
   RequestDispatcher dispatcher = request.getRequestDispatcher("lookShoppingCar.jsp");
   dispatcher.forward(request, response); // 转发
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    LookupService lookupService = new LookupService();
    coshms.ejb.pathalogy.PathalogyRemote pthRemoteSB = lookupService.lookupPathalogyBean();

    java.util.ArrayList pthTestDomainList = new java.util.ArrayList();
    int tStatus = 0;

    if (request.getParameter("status") != null) {
      tStatus = 1;
    }
    String[] cid = request.getParameterValues("contentId");
    String[] cname = request.getParameterValues("cname");
    String[] unit = request.getParameterValues("unit");
    String[] minvalue = request.getParameterValues("minvalue");
    String[] maxvalue = request.getParameterValues("maxvalue");

    for (int i = 0; i < cname.length; i++) {
      PthTestContentsInfo pthTestCon =
          new PthTestContentsInfo(
              "",
              Integer.parseInt(cid[i]),
              cname[i],
              Double.parseDouble(minvalue[i]),
              Double.parseDouble(maxvalue[i]),
              unit[i]);
      pthTestDomainList.add(pthTestCon);
    }
    int empId = 1;

    if (pthRemoteSB.pthTestDomainEdit(
        pthTestDomainList,
        request.getParameter("tname"),
        tStatus,
        Integer.parseInt(request.getParameter("tcost")),
        empId,
        Integer.parseInt(request.getParameter("testId"))))
      response.sendRedirect("pthMessage.jsp?message=Pathalogy Test Edit Successfully");
    else response.sendRedirect("pthMessage.jsp?message=Try Again");
    out.close();
  }
Esempio n. 16
0
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   final String button = request.getParameter("button");
   if (button.equals("create")) {
     Cookie cookie = new Cookie("carlos-cookie-test", "");
     refreshCookie(cookie, response);
     response.sendRedirect("cookie");
   } else if (button.equals("no-pass")) {
     response.sendRedirect("cookie");
   } else if (button.equals("delete")) {
     Cookie cookie = getCookie("carlos-cookie-test", request);
     if (cookie != null) {
       cookie.setMaxAge(0);
       response.addCookie(cookie);
     }
     response.sendRedirect("cookie");
   } else {
     throw new RuntimeException("unknown action: " + button);
   }
 }
  // 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);
  }
Esempio n. 18
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String key = request.getParameter("keyname");
    String keyvalue = request.getParameter("value");

    // Add the task to the default queue.
    Queue queue = QueueFactory.getDefaultQueue();
    queue.add(
        TaskOptions.Builder.withUrl("/worker").param("keyname", key).param("value", keyvalue));

    response.sendRedirect("/done.html");
  }
Esempio n. 19
0
  private void handleSignupPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String userName = request.getParameter(PARAM_USER_NAME);
    String email = request.getParameter(PARAM_EMAIL);
    String stringPassword = request.getParameter(PARAM_PASSWORD);
    String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringPassword.equals(stringPasswordConfirm)) {
      WebUtils.redirectToError(
          "Mismatch between password and password confirmation", request, httpServletResponse);
      return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringPassword, salt);
    User user = userDb.get(userId);
    if (user != null) {
      WebUtils.redirectToError(
          "There already exists a user with the ID " + userId, request, httpServletResponse);
      return;
    }

    user =
        new User(
            userId,
            userName,
            password,
            salt,
            email,
            new ArrayList<String>(),
            Config.getConfig().activateAccountsAtCreation,
            false);
    // ttt2 add confirmation by email, captcha, ...
    List<String> fieldErrors = user.checkFields();
    if (!fieldErrors.isEmpty()) {
      StringBuilder bld =
          new StringBuilder("Invalid values when trying to create user with ID ")
              .append(userId)
              .append("<br/>");
      for (String s : fieldErrors) {
        bld.append(s).append("<br/>");
      }
      WebUtils.redirectToError(bld.toString(), request, httpServletResponse);
      return;
    }

    // ttt2 2 clients can add the same userId simultaneously
    userDb.add(user);

    httpServletResponse.sendRedirect("/");
  }
Esempio n. 20
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // I use "session" in order to throws the object named user bean.
   HttpSession session = request.getSession(true);
   response.setContentType("text/html");
   request.setCharacterEncoding("UTF-8");
   UserBean ub = (UserBean) session.getAttribute("user");
   if (ub == null) {
     String haveLogin = "******";
     session.setAttribute("haveLogin", haveLogin);
     response.sendRedirect("cart");
   } else {
     String mID = ub.getmID();
     String iID = (String) request.getParameter("iID");
     // String idx = (String)request.getParameter("idx");
     Connection conn = null;
     try {
       // Getting the connection from database.
       Class.forName("com.mysql.jdbc.Driver");
       /*conn = DriverManager
       .getConnection("jdbc:mysql://localhost/se?"
       		+ "user=root");*/
       conn =
           DriverManager.getConnection(
               "jdbc:mysql://localhost/user_register?"
                   + "user=sqluser&password=sqluserpw&useUnicode=true&characterEncoding=UTF-8");
       String sql = "delete from cart_item_mapping where mID=? and iID = ?";
       PreparedStatement pst = conn.prepareStatement(sql);
       // Using preparedstatement by set the parameter related to "?" symbol.
       pst.setString(1, mID);
       pst.setString(2, iID);
       pst.executeUpdate();
       pst.close();
       response.sendRedirect("ShowCartController");
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 21
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();

    nseer_db_backup1 stock_db = new nseer_db_backup1(dbApplication);

    try {
      if (stock_db.conn((String) dbSession.getAttribute("unit_db_name"))) {
        int i;
        int intRowCount;
        String sqll =
            "select * from stock_config_public_char where describe1='\u51fa\u5165\u5e93\u7406\u7531'";
        ResultSet rs = stock_db.executeQuery(sqll);
        rs.next();
        rs.last();
        intRowCount = rs.getRow();
        String[] del = new String[intRowCount];
        del = (String[]) dbSession.getAttribute("del");
        if (del != null) {
          for (i = 1; i <= intRowCount; i++) {
            String sql = "delete from stock_config_public_char where id='" + del[i - 1] + "'";
            stock_db.executeUpdate(sql);
          }
        }
        stock_db.commit();
        stock_db.close();
        response.sendRedirect("stock/config/apply_gather_pay/reason.jsp");
      } else {
        response.sendRedirect("error_conn.htm");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  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);
  }
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if ("true".equals(req.getParameter("is_return"))) {
     processReturn(req, resp);
   } else {
     String identifier = req.getParameter("openid_identifier");
     if (identifier != null) {
       this.authRequest(identifier, req, resp);
     } else {
       // this.getServletContext().getRequestDispatcher("/openid/login.xql").forward(req, resp);
       resp.sendRedirect(OpenIDRealm.instance.getSecurityManager().getAuthenticationEntryPoint());
     }
   }
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String category = request.getParameter("item_category");
   vendorItem items = null;
   vendorItemList itemLists = new vendorItemList();
   int item_id;
   String item_title;
   String item_desc;
   float item_price;
   int item_qt;
   String item_category;
   String item_image_path;
   int item_rem_qt;
   dbConnection pool = dbConnection.getInstance();
   Connection connection = pool.getConnection();
   PreparedStatement ps = null;
   try {
     String search_query = "SELECT * FROM Items WHERE item_category = '" + category + "'";
     ps = connection.prepareStatement(search_query);
     ResultSet rs = ps.executeQuery();
     ResultSetMetaData rsmd = rs.getMetaData();
     while (rs.next()) {
       item_id = rs.getInt("item_id");
       item_title = rs.getString("item_title");
       item_desc = rs.getString("item_desc");
       item_price = rs.getFloat("item_price");
       item_qt = rs.getInt("item_qt");
       item_category = rs.getString("item_category");
       item_image_path = rs.getString("item_image_path");
       items =
           new vendorItem(
               item_id,
               item_title,
               item_desc,
               item_price,
               item_qt,
               item_category,
               item_image_path);
       itemLists.addItem(items);
     }
   } catch (SQLException e) {
     e.printStackTrace();
   }
   response.sendRedirect("../resources/vendor/index.jsp");
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    System.out.println(
        "MyProtectedServlet.processRequest "
            + request.getRequestURI()
            + " "
            + request.getQueryString());

    String myUrl = request.getRequestURI();
    if (myUrl.indexOf("login") >= 0) {
      login(request, response);
      return;
    } else if (myUrl.indexOf("redirect") >= 0) {
      redirect(request, response);
      return;
    }

    if (request.getRemoteUser() == null) {
      String callUrl = request.getRequestURI();
      String query = request.getQueryString();
      if (query != null) {
        callUrl = callUrl + "?" + query;
      }
      String nextEncUrl = java.net.URLEncoder.encode(callUrl);
      String redirectUrl =
          request.getContextPath() + "/application/redirect?nextencurl=" + nextEncUrl;
      response.sendRedirect(redirectUrl);
    } else {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet MyProtectedServlet</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h1>Servlet MyProtectedServlet at " + request.getContextPath() + "</h1>");
      out.println("</body>");
      out.println("</html>");

      out.close();
    }
  }
Esempio n. 26
0
 public void doFilter(ServletRequest request0, ServletResponse response0, FilterChain filterChain)
     throws IOException, ServletException {
   HttpServletRequest request = (HttpServletRequest) request0;
   HttpServletResponse response = (HttpServletResponse) response0;
   if (request.getRequestURI().endsWith(requesturl)) {
     boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
     request.getSession().invalidate();
     if (isAjax) {
       Response<String> kv = new Response<String>();
       kv.setReturncode("00000000");
       kv.setReturnmsg("登出成功");
       outputJson(response, kv);
     } else {
       response.sendRedirect(request.getContextPath() + successurl);
     }
     return;
   }
   filterChain.doFilter(request, response);
 }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

    try {
      UserBean user = new UserBean();
      user.setType("getfrozen");
      if (request.getParameter("sort") != null) {
        String sort = (String) request.getParameter("sort");
        if (sort.equals("namabarang")) {
          user.setQuery("SELECT * FROM Barang WHERE Kategori = 'Frozen Food' order by NamaBarang");
        } else if (sort.equals("harga")) {
          user.setQuery("SELECT * FROM Barang WHERE Kategori = 'Frozen Food' order by Harga");
        } else if (sort.equals("urutkan")) {
          user.setQuery("SELECT * FROM Barang WHERE Kategori = 'Frozen Food'");
        }
      } else {
        user.setQuery("SELECT * FROM Barang WHERE Kategori = 'Frozen Food'");
      }
      user = UserDAO.login(user);
      ArrayList<Barang> frozenes = new ArrayList<Barang>();
      frozenes = user.getfrozen();
      HttpSession session = request.getSession(true);
      session.setAttribute("jumlahfrozen", frozenes.size());
      for (int i = 0; i < frozenes.size(); i++) {
        String bnama = "fnama" + (i + 1);
        String bid = "fid" + (i + 1);
        String bharga = "fharga" + (i + 1);
        String bkategori = "fkategori" + (i + 1);
        String bjumlah = "fjumlah" + (i + 1);
        session.setAttribute(bnama, frozenes.get(i).getNama());
        session.setAttribute(bid, frozenes.get(i).getId());
        session.setAttribute(bharga, frozenes.get(i).getHarga());
        session.setAttribute(bkategori, frozenes.get(i).getKategori());
        session.setAttribute(bjumlah, frozenes.get(i).getJumlah());
      }

      response.sendRedirect("Frozen.jsp?f=1&l=10");
    } catch (Throwable theException) {
      System.out.println(theException);
    }
  }
Esempio n. 28
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();

    try {
      HttpSession session = request.getSession();
      PrintWriter out = response.getWriter();
      MakePdf mm = new MakePdf();
      excel query = new excel();
      getKeyColumn column = new getKeyColumn();
      mm.setConfigFile("xml/stock/pdf_export.xml");
      String sql = "";
      String tablename = request.getParameter("tablename");
      String condition = "";
      String queue = "";
      if (tablename.equals("stock_balance")) {
        queue = "order by chain_ID";
        condition = "where address_group!=''";
      }
      sql = "select * from " + tablename + " " + condition + " " + queue;
      int a = sql.indexOf("*");
      String sqla = sql.substring(0, a) + "count(*) as A" + sql.substring(a + 1, sql.length());

      mm.make(
          (String) dbSession.getAttribute("unit_db_name"),
          tablename,
          sqla,
          sql,
          "pdf_files/stock_data",
          1500,
          session);
      int fileAmount = mm.fileAmount();
      response.sendRedirect("stock/export/pdf_ok_a.jsp?file_amount=" + fileAmount + "");

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
 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>");
   }
 }
  @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");
  }