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) { } }
/** * Creates a Discussion Post * * <p>- Requires a cookie for the session user - Requires a comment and threadId request parameter * for the POST * * @param req The HTTP Request * @param res The HTTP Response */ public void createPostAction(HttpServletRequest req, HttpServletResponse res) { // Ensure there is a cookie for the session user if (AccountController.redirectIfNoCookie(req, res)) return; Map<String, Object> viewData = new HashMap<>(); if (req.getMethod() == HttpMethod.Post) { DiscussionManager dm = new DiscussionManager(); HttpSession session = req.getSession(); Session userSession = (Session) session.getAttribute("userSession"); // Create the discussion post DiscussionPost post = new DiscussionPost(); post.setUserId(userSession.getUserId()); post.setMessage(req.getParameter("comment")); post.setThreadId(Integer.parseInt(req.getParameter("threadId"))); dm.createPost(post); redirectToLocal(req, res, "/group/discussion/?threadId=" + req.getParameter("threadId")); } else { httpNotFound(req, res); } }
/** * Deletes a meeting from the database * * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the * HTTP GET * * @param req The HTTP Request * @param res The HTTP Response */ public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) { // Ensure there is a cookie for the session user if (AccountController.redirectIfNoCookie(req, res)) return; if (req.getMethod() == HttpMethod.Get) { // Get the meeting int meetingId = Integer.parseInt(req.getParameter("meetingId")); MeetingManager meetingMan = new MeetingManager(); Meeting meeting = meetingMan.get(meetingId); meetingMan.deleteMeeting(meetingId); // Update the User Session to remove meeting HttpSession session = req.getSession(); Session userSession = (Session) session.getAttribute("userSession"); List<Meeting> adminMeetings = userSession.getUser().getMeetings(); for (int i = 0; i < adminMeetings.size(); i++) { Meeting m = adminMeetings.get(i); if (m.getId() == meeting.getId()) { adminMeetings.remove(i); break; } } redirectToLocal(req, res, "/home/dashboard"); return; } else if (req.getMethod() == HttpMethod.Post) { httpNotFound(req, res); } }
public static void showSession(HttpServletRequest req, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); out.println("Session id: " + session.getId()); out.println(" session.isNew(): " + session.isNew()); out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs"); out.println( " session.getCreationTime(): " + session.getCreationTime() + " (" + new Date(session.getCreationTime()) + ")"); out.println( " session.getLastAccessedTime(): " + session.getLastAccessedTime() + " (" + new Date(session.getLastAccessedTime()) + ")"); out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie()); out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL()); out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid()); out.println("Saved session Attributes:"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(" " + name + ": " + session.getAttribute(name) + "<BR>"); } }
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 String getTokenValue(HttpServletRequest request, String uri) { String tokenValue = null; HttpSession session = request.getSession(false); if (session != null) { if (isTokenPerPageEnabled()) { @SuppressWarnings("unchecked") Map<String, String> pageTokens = (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY); if (pageTokens != null) { if (isTokenPerPagePrecreate()) { createPageToken(pageTokens, uri); } tokenValue = pageTokens.get(uri); } } if (tokenValue == null) { tokenValue = (String) session.getAttribute(getSessionKey()); } } return tokenValue; }
public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); // Increment the hit count for this page. The value is saved // in this client's session under the name "snoop.count". Integer count = (Integer) session.getAttribute("snoop.count"); if (count == null) { count = 1; } else count = count + 1; session.setAttribute("snoop.count", count); out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag()); out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>"); out.println("<BODY><H1>Session Snoop</H1>"); // Display the hit count for this page out.println( "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times.")); out.println("<P>"); out.println("<H3>Here is your saved session data:</H3>"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(name + ": " + session.getAttribute(name) + "<BR>"); } out.println("<H3>Here are some vital stats on your session:</H3>"); out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>"); out.println("New session: " + session.isNew() + "<BR>"); out.println("Timeout: " + session.getMaxInactiveInterval()); out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>"); out.println("Creation time: " + session.getCreationTime()); out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>"); out.println("Last access time: " + session.getLastAccessedTime()); out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>"); out.println( "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>"); out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>"); out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>"); out.println("<H3>Test URL Rewriting</H3>"); out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>"); out.println("to test that session tracking works via URL"); out.println("rewriting even when cookies aren't supported."); out.println("</BODY></HTML>"); }
/** * Permet de repondre a une requete web En affichant la liste des Spectacles et representations : * Utiliste JQuery javascript pour la mise en forme * * @param HttpServletRequest request requete * @param HttpServletResponse response reponse * @throw IOException, ServletException * @return void */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get the session object HttpSession session = req.getSession(true); // Get the output stream ServletOutputStream out = res.getOutputStream(); res.setContentType("text/html"); out.println("<HEAD><TITLE>Reservation de tickets </TITLE></HEAD><BODY>"); out.println("<h1> Reservations de tickets </h1>"); out.println("<BODY bgproperties=\"fixed\" background=\"/images/rideau.JPG\">"); out.println("<p align=\"Right\"><font face=\"Monotype Corsiva\"style=\"font-size: 16pt\">"); try { // Open the file that is the first // command line parameter String relativeWebPath = "/WEB-INF/files/JAVASCRIPTPROG.txt"; String absoluteDiskPath = this.getServletContext().getRealPath(relativeWebPath); File file = new File(absoluteDiskPath); FileInputStream fstream = new FileInputStream(file); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console out.println(strLine); } // Close the input stream in.close(); } catch (Exception e) { // Catch exception if any out.println("Error: " + e.getMessage()); } if (session.isNew() || session.getAttribute("session.PanierListe") == null) out.println("<a href=\"admin/admin.html\">Caddie (vide)</a></font><br></p>"); else if (session.getAttribute("session.PanierListe") != null) if (((PanierListe) session.getAttribute("session.PanierListe")).getSize() > 0) out.println( "<a href=\"admin/admin.html\">afficher caddie(" + ((PanierListe) session.getAttribute("session.PanierListe")).Liste.size() + "Representations dans le panier)" + "</a></font><br></p>"); try { Utilisateur user = Utilitaires.Identification(this); out.println(Utilitaires.AffichageAchat(user)); } catch (Exception e) { out.println(e.getMessage()); } out.println("</BODY>"); out.close(); }
/** * 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 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(); } }
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); } } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); HttpSession session = req.getSession(); if (session == null) { resp.setStatus(401); return; } String username = (String) session.getAttribute("username"); if (username == null) { resp.setStatus(401); return; } Map userMap = loadUserSettingsMap(username); if (userMap == null) { resp.setStatus(401); return; } if (pathInfo.equals("/")) { resp.setContentType("application/json; charset=UTF-8"); resp.getWriter().write(JSONUtil.write(userMap)); return; } String key = pathInfo.substring(1); String value = (String) userMap.get(key); Map jsonObject = new HashMap(); jsonObject.put(key, value); resp.setContentType("application/json; charset=UTF-8"); resp.getWriter().write(JSONUtil.write(jsonObject)); }
public void updateTokens(HttpServletRequest request) { /** cannot create sessions if response already committed * */ HttpSession session = request.getSession(false); if (session != null) { /** create master token if it does not exist * */ updateToken(session); /** create page specific token * */ if (isTokenPerPageEnabled()) { @SuppressWarnings("unchecked") Map<String, String> pageTokens = (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY); /** first time initialization * */ if (pageTokens == null) { pageTokens = new HashMap<String, String>(); session.setAttribute(CsrfGuard.PAGE_TOKENS_KEY, pageTokens); } /** create token if it does not exist * */ if (isProtectedPageAndMethod(request)) { createPageToken(pageTokens, request.getRequestURI()); } } } }
public Event perform(HttpServletRequest request) throws HTMLActionException { HttpSession session = request.getSession(); // look up the adventure transportation AdventureComponentManager acm = (AdventureComponentManager) session.getAttribute(AdventureKeys.COMPONENT_MANAGER); Cart cart = acm.getCart(session); String origin = request.getParameter("origin"); // if we are doing a search for a different flight from the cart page if (origin == null) { origin = cart.getOrigin(); } else { cart.setOrigin(origin); } String noTransport = request.getParameter("no_transport"); String showTransport = request.getParameter("show_flights"); Locale locale = new Locale("en", "us"); String destination = cart.getDestination(); // access catalog component and retrieve data from the database List transpDepartureBeans = searchTransportation(origin, destination, locale); List transpReturnBeans = searchTransportation(destination, origin, locale); // places result bean data in the request request.setAttribute("departure_result", transpDepartureBeans); request.setAttribute("return_result", transpReturnBeans); request.setAttribute("search_target", "transportation"); return null; }
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 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); } }
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); HttpSession session = req.getSession(); if (session == null) { resp.setStatus(401); return; } String username = (String) session.getAttribute("username"); if (username == null) { resp.setStatus(401); return; } Map userMap = loadUserSettingsMap(username); if (userMap == null) { resp.setStatus(401); return; } if (pathInfo.equals("/")) { userMap.clear(); } String key = pathInfo.substring(1); userMap.remove(key); saveUserSettingsMap(username, userMap); return; }
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); if (pathInfo.equals("/")) { HttpSession session = req.getSession(); if (session == null) { resp.setStatus(401); return; } String username = (String) session.getAttribute("username"); if (username == null) { resp.setStatus(401); return; } Map userMap = loadUserSettingsMap(username); if (userMap == null) { resp.setStatus(401); return; } Enumeration parameterNames = req.getParameterNames(); while (parameterNames.hasMoreElements()) { String parameterName = (String) parameterNames.nextElement(); userMap.put(parameterName, req.getParameter(parameterName)); } saveUserSettingsMap(username, userMap); return; } super.doPost(req, resp); }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); String support = "support"; // valid username HttpSession session = null; session = req.getSession(false); // Get user's session object (no new one) if (session == null) { invalidUser(out); // Intruder - reject return; } String userName = (String) session.getAttribute("user"); // get username if (!userName.equals(support)) { invalidUser(out); // Intruder - reject return; } String action = ""; if (req.getParameter("todo") != null) action = req.getParameter("todo"); if (action.equals("update")) { doUpdate(out); return; } out.println("<p>Nothing to do.</p>todo=" + action); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(); String str = (String) session.getAttribute("foo"); pw.println("The name is " + str); }
/** Get the object associated with the ID in the session */ protected Object getSessionIdObject(String id) { HttpSession session = getSession(); synchronized (session) { BidiMap map = (BidiMap) session.getAttribute(SESSION_KEY_OBJ_MAP); if (map == null) { return null; } return map.getKey(id); } }
/** * 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
/** * Creates a db connecton. * * @return true if OK, false if there's a problem */ private boolean createDbConnection( HttpSession session, HttpServletRequest req, HttpServletResponse res) throws Exception { // At this point a driver and connection may already be set // up. So here it first tests if a connection can be made. // If not, set params up, and test the setup. if (ConnManager.getConn() == null) { ConnManager.getInstance() .setLoginParams( session.getAttribute("dbtDbDriver"), session.getAttribute("dbtDbUrl"), session.getAttribute("dbtDbUser"), session.getAttribute("dbtDbPassword")); if (ConnManager.getConn() == null) { Util.putMessagePage(res, "Cannot login to DBT database"); // Invalidates the session in case connection is "stuck" in error session.invalidate(); return false; } } return true; }
private void verifySessionToken(HttpServletRequest request) throws CsrfGuardException { HttpSession session = request.getSession(true); String tokenFromSession = (String) session.getAttribute(getSessionKey()); String tokenFromRequest = request.getParameter(getTokenName()); if (tokenFromRequest == null) { /** FAIL: token is missing from the request * */ throw new CsrfGuardException("required token is missing from the request"); } else if (!tokenFromSession.equals(tokenFromRequest)) { /** FAIL: the request token does not match the session token * */ throw new CsrfGuardException("request token does not match session token"); } }
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(); } }
/** @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(); }
private void verifyPageToken(HttpServletRequest request) throws CsrfGuardException { HttpSession session = request.getSession(true); @SuppressWarnings("unchecked") Map<String, String> pageTokens = (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY); String tokenFromPages = (pageTokens != null ? pageTokens.get(request.getRequestURI()) : null); String tokenFromSession = (String) session.getAttribute(getSessionKey()); String tokenFromRequest = request.getParameter(getTokenName()); if (tokenFromRequest == null) { /** FAIL: token is missing from the request * */ throw new CsrfGuardException("required token is missing from the request"); } else if (tokenFromPages != null) { if (!tokenFromPages.equals(tokenFromRequest)) { /** FAIL: request does not match page token * */ throw new CsrfGuardException("request token does not match page token"); } } else if (!tokenFromSession.equals(tokenFromRequest)) { /** FAIL: the request token does not match the session token * */ throw new CsrfGuardException("request token does not match session token"); } }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter toClient = res.getWriter(); toClient.println("<!DOCTYPE HTML>"); toClient.println("<html>"); toClient.println("<head><title>Books</title></head>"); toClient.println("<body>"); toClient.println("<a href=\"index.html\">Home</A>"); toClient.println("<h2>List of books</h2>"); HttpSession session = req.getSession(false); if (session != null) { String name = (String) session.getAttribute("name"); if (name != null) { toClient.println("<h2>name: " + name + "</h2>"); } } toClient.print("<form action=\"bookOpinion\" method=GET>"); toClient.println("<table border='1'>"); String sql = "Select code, title, author FROM books"; System.out.println(sql); try { Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql); while (result.next()) { toClient.println("<tr>"); String codeStr = result.getString("code"); toClient.println( "<td><input type=\"radio\" name=\"book" + "\" value=\"" + codeStr + "\"></td>"); toClient.println("<td>" + codeStr + "</td>"); toClient.println("<td>" + result.getString("title") + "</td>"); toClient.println("<td>" + result.getString("author") + "</td>"); toClient.println("</tr>"); } } catch (SQLException e) { e.printStackTrace(); System.out.println("Resulset: " + sql + " Exception: " + e); } toClient.println("</table>"); toClient.println("<textarea rows=\"8\" cols=\"60\" name=\"comment\"></textarea><BR>"); toClient.println("<input type=submit>"); toClient.println("</form>"); toClient.println("</body>"); toClient.println("</html>"); toClient.close(); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession(); String food = (String) session.getAttribute("FOOD"); String animal = request.getParameter("ANIMAL"); session.invalidate(); response.setContentType("text/html;charset=euc-kr"); PrintWriter out = response.getWriter(); out.println("<HEAD><TITLE>성격 테스트</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H3>성격 테스트</H3>"); out.printf("당신은 %s와 %s를 좋아하는 성격입니다.", food, animal); out.println("</BODY>"); out.println("</HTML>"); }
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); } }