/**Servlet to demonstrate how to use cookies to implement sessions * Internet Programming 2 - Course * @author Martin Carlsson */ import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import mixer.*; public class CookieSession extends HttpServlet { private static String filePath = "/ip-2/cookie-session"; private static String htmlFile = null; private String htmlFileName ="cookie-session.htm"; public void init()throws ServletException { if(htmlFile == null) { htmlFile = Mixer.getContent(new File(getServletContext().getRealPath(filePath+"\\"+htmlFileName))); } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { Mixer m = new Mixer(htmlFile); res.setContentType("text/html"); PrintWriter out = res.getWriter(); String timeCookie = null,nameCookie = null; Cookie[] cookies = req.getCookies(); if(cookies != null) { for(int i = 0; i < cookies.length; i++) { if(cookies[i].getName().equals("timeCookie")) { timeCookie = cookies[i].getValue(); m.add("","_m_","A cookie with the name \"timeCookie\" and the value \"" + timeCookie + "\" has been sent back to the server side application from your browser."); } if(cookies[i].getName().equals("nameCookie")) { nameCookie = cookies[i].getValue(); m.add("","_m_","A cookie with the name \"nameCookie\" and the value \"" + nameCookie + "\" has been sent back to the server side application from your browser."); } } } if(timeCookie == null) { timeCookie = new Date().toString(); Cookie c = new Cookie("timeCookie", timeCookie); c.setMaxAge(60*60*3); res.addCookie(c); m.add("","_m_","A cookie with the name \"timeCookie\" and the value \"" + timeCookie + "\" has been sent from the server application."); } if(nameCookie == null) { nameCookie = "Hasse"; Cookie c2 = new Cookie("nameCookie",nameCookie); c2.setMaxAge(60*60*3); res.addCookie(c2); m.add("","_m_","A cookie with the name \"nameCookie\" and the value \"" + nameCookie + "\" has been sent from the server side application."); } m.add("","_m_","To view these cookies in Internet Explorer\n, go to: " + "Tools - Internet Options - Settings - View Files."); m.add("","_m_","Press refresh button to send the cookies back to the server side application."); out.println(m.getMix()); } } // End class CookieSessions