@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>"); }
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) { } }
/** * 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); } }
/** * 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); } }
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); } } }
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 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(); } }
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 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); }
@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!"); } } }
@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); }
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); }
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>"); }
/** 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(); } }
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"); }
/** * 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
/** @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 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); }
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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("save") != null) { User newUser = new User(request.getParameter("login"), request.getParameter("password")); if (BaseUser.addUser(newUser)) { HttpSession sessions = request.getSession(); sessions.setAttribute("userSession", newUser); this.forward("/successRegistration.jsp", request, response); } else { this.forward("/errorRegistration.html", request, response); } } else if (request.getParameter("cancel") != null) { this.forward("/login.jsp", request, response); } }
/** Get the ID with which the object is associated with the session, if any */ protected String getSessionObjectId(Object obj) { HttpSession session = getSession(); BidiMap map; synchronized (session) { map = (BidiMap) session.getAttribute(SESSION_KEY_OBJ_MAP); if (map == null) { map = new DualHashBidiMap(); session.setAttribute(SESSION_KEY_OBJ_MAP, map); } } synchronized (map) { String id = (String) map.get(obj); if (id == null) { id = getNewSessionObjectId(); map.put(obj, id); } return id; } }
/** * Handles HTTP GET requests. * * @param request Description of the Parameter * @param response Description of the Parameter * @exception ServletException if there is a Servlet failure * @exception IOException if there is an IO failure */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Integer sessionCounter = (Integer) session.getAttribute("project4SessionCounter"); if (sessionCounter == null) { Integer newCounter = new Integer(1); sessionCounter = newCounter; } else { sessionCounter++; } session.setAttribute("project4SessionCounter", sessionCounter); String url = "/project4Session.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); }
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(); } } }
public boolean convalida() { boolean tuttoOk = true; Map<String, String> errori = new HashMap<String, String>(); if ((nome == null) || nome.equals("")) { tuttoOk = false; request.setAttribute("nome", nome); errori.put("nome", "campo obbligatorio"); } if ((descrizione == null) || descrizione.equals("")) { tuttoOk = false; request.setAttribute("descrizione", descrizione); errori.put("descrizione", "campo obbligatorio"); } if ((codice == null) || codice.equals("")) { tuttoOk = false; request.setAttribute("codice", codice); errori.put("codice", "campo obbligatorio"); } if (!isInteger(disponibilita)) { tuttoOk = false; request.setAttribute("disponibilita", disponibilita); errori.put("disponibilita", "formato non valido"); } if (!isInteger(prezzo)) { tuttoOk = false; request.setAttribute("prezzo", prezzo); errori.put("prezzo", "formato non valido"); } if (!tuttoOk) request.setAttribute("errori", errori); HttpSession sess = request.getSession(); sess.setAttribute("errori", errori); return tuttoOk; }
@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); } }
private void endHereCommon() throws BeanException { // save EJB object handle in property if (ejb != null) { try { hPubAccessHandle = ejb.getHandle(); } catch (Exception e) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5955 " + this.getClass().getName() + ": ejb.getHandle(), ejb=" + ejb + ": " + e.getClass().getName() + ": " + e.getMessage(); System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } } // save ejb accessHandle and hpubLinkKey in HttpSession if ((oHttpServletRequest != null) && (outputProps != null)) { // a new HPubEjb2HttpSessionBindingListener object containing the ejb access // handle and hPubLinkKey for the connection is bound to the session using // a prefix and the ending connection state of the IO just processed. // This hPubLinkKey uniquely identifies the connection associated with the // IO chain for that HP Runtime JVM. // The ejb access handle is contained within the HPubEjb2HttpSessionBindingListener // object so that an ejb remove can be issued in the case where a session // timeout or session invalidation occurs for an incomplete IO chain. HttpSession theWebsession = oHttpServletRequest.getSession(true); if (theWebsession != null) { synchronized (theWebsession) { try { String theKey = KEY_WEBCONN + outputProps.getHPubEndChainName(); hPubLinkKey = outputProps.getHPubLinkKey(); theWebsession.setAttribute( theKey, new HPubEJB2HttpSessionBindingListener(hPubAccessHandle, hPubLinkKey)); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "theWebsession.setAttribute(" + theKey + ",new HPubEJB2HttpSessionBindingListener(" + hPubAccessHandle + ", " + hPubLinkKey + "))"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } if (auditing == true) { auditArgs[0] = "\n---\nIN:" + this.getClass().getName() + " " + theKey + " " + hPubAccessHandle + " " + hPubLinkKey + " " + theWebsession.getId(); auditArgs[1] = theWebsession; try { auditMethod.invoke(o, auditArgs); } catch (Exception x) { } } } catch (Exception e) { hPubLinkKey = null; // set to null to force following error logic } } } // if an error occurred throw an exception to cause ejb remove to be issued. if ((theWebsession == null) || (hPubLinkKey == null)) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5956 " + this.getClass().getName() + ": HttpServletRequest.getSession(true), hPubLinkKey=" + hPubLinkKey; System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } } // send Event to User indicating that the Query request is complete RequestCompleteEvent hPubEvent = new RequestCompleteEvent(this); fireHPubReqCompleteEvent(hPubEvent); return; }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<br><h4>we are getting data</h4>"); String code = request.getParameter("code"); out.println("<br>code: " + code); out.println("<br>"); try { OAuthClientRequest requestOAuth = OAuthClientRequest.tokenLocation("https://graph.facebook.com/oauth/access_token") .setGrantType(GrantType.AUTHORIZATION_CODE) .setClientId(apiKey) .setClientSecret(secretKey) .setRedirectURI(redirectUri) .setCode(code) .buildBodyMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(requestOAuth, GitHubTokenResponse.class); accessToken = oAuthResponse.getAccessToken(); expiresIn = oAuthResponse.getExpiresIn(); } catch (OAuthSystemException ae) { ae.printStackTrace(); } catch (OAuthProblemException pe) { pe.printStackTrace(); } // out.println("<br>Access Token: " + accessToken); // out.println("<br>Expires In: " + expiresIn); try { FacebookClient facebookClient = new DefaultFacebookClient(accessToken); myFriends = facebookClient.fetchConnection("me/friends", User.class); myFeeds = facebookClient.fetchConnection("me/home", Post.class); for (User myFriend : myFriends.getData()) { f.add(myFriend.getName()); out.println("<br>id: " + myFriend.getId() + " Name: " + myFriend.getName()); } // out.println("<br>"); out.println("<br>f count: " + f.size()); } catch (FacebookException e) { e.printStackTrace(); } facebookDataBean fdb = new facebookDataBean(); fdb.setName("zishan ali khan"); HttpSession session = request.getSession(); if (session != null) { session.setAttribute("myfdb", fdb); session.setAttribute("yourFriends", f); session.setAttribute("feeds", myFeeds); RequestDispatcher view = request.getRequestDispatcher("result.jsp"); view.forward(request, response); f.clear(); // out.println("<br>I am in"); } else { // out.println("<br>Session Over"); } }