HTTP Sessions
140 likes | 167 Vues
Learn how cookies and HttpSession interface work to manage user sessions in HTTP, addressing the stateless nature of HTTP requests and enabling consistent user interactions on web applications.
HTTP Sessions
E N D
Presentation Transcript
HTTP Sessions http://flic.kr/p/8KTNbe
What are you goingto learn about today? • How cookies work • How to manage user sessions http://flic.kr/p/8JpkTg
Recall: HTTP/Servlet interaction Client A and Client B could be the same!
Sometimes you’d like your web app to have a “conversation” with a userProblem: HTTP is stateless, so don’t know who sent a given requestAny idea how to solve this problem? This is what cookies were made for! http://flic.kr/p/9ksxQa
How cookies work Session ID
Good news! You don’t have to mess with cookies yourself—there’s HttpSession protected void doPost(HttpServletRequest request, HttpServletResponse response) { … HttpSession session = request.getSession(); … } public interface HttpSession { public void setAttribute(String name, Object value) {…} public Object getAttribute(String name) {…} public boolean isNew() {…} … }
How sessions work: Second request, same session Same servlet Different thread Same session Same user
How sessions work: Different user/session Same servlet Different thread Different session Different user
Activity: Creating “Ping Pong”Servlets with Sessions • Create two servlets, PingServlet and PongServlet • Keep track of how many times each has been visited in a session • Each servlet displays the two counts and provides a link to the other servlet What happens if you disable cookies in your browser? Try it! http://flic.kr/p/5dfuqL
Don’t worry: There’s a backup planin case cookies are disabled
Unfortunately, you must “encode” all URLs (to yourwebapp) that you link to in your response HTML public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); out.println(“<html><body>”); out.println(“<a href=\”” + response.encodeURL(“/BeerTest.do”) + “\”>click me</a>”); out.println(“</body></html>”); }
Summary • HttpSession • Cookies for session management • URL encoding as a backup http://flic.kr/p/YSY3X