Servlets O. De Pertat
Servlets Overview Generic Server Business logic API Java Syntax: classes extending the javax.servlet.Servlet interface or any sub-class. Packages: javax.servlet javax.servlet.http.*. Features: Thread–oriented instead of process management (like CGI or Fast- CGI) High level API Performance for parameters transmission Runs on every operating system Secure : no SHELL escapes, no buffer overflows Java programming language (PHP, VB.NET, Python)
Servlets Container used Apache – Jakarta Tomcat : Conteneur de référence Officiel IBM – WebSphere BEA – WebLogic Alliance - iPlanet (Sun & NetScape) Oracle – IAS Allaire – Jrun Caucho’s Resin
Javax.servlet
Javax.servlet.http
Servlets types Servlet interface is the contract passed between a Servlet and its container. GenericServlet basic implement of a Servlet. Implementation is not protocol specific. HttpServlet HTTP protocol implementation of a Servlet. Every class that extends of the previously described class.
Servlets life cycle
Servlet Initialization Handle by the init method that we can overload: Open Database connection Variables initializations… getInitParameter() method allows to retrieve the declared parameters set into the web container configuration. Into TOMCAT: foo bar
Handling requests The WebContainer invoke the service(ServletRequest req, ServletResponse res) method. For an HTTP Servlet the service method is overloaded and call the method that fit to the HTTP Command: GET : protected void doGet (HttpServletRequest req, HttpServletResponse resp) POST : protected void doPost (HttpServletRequest req, HttpServletResponse resp) HEAD : protected void doPost (HttpServletRequest req, HttpServletResponse resp) PUT : protected void doPut (HttpServletRequest req, HttpServletResponse resp)....
Servlet Response ServletResponse interface implemention getOutputStream() getWriter() HttpServletResponse : STATUS CODE : SC_OK, SC_NOT_FOUND setContentType() : "text/html", "image/gif" setStatus() : 200, SC_OK, SC_NOT_FOUND… addCookie() : add a cookie to the HTTP response setDateHeader() : sets Date in HTTP response’s header setHeader() : to set any HTTP Header sendError() : to send an HTTP error to the client
Servlet Request HttpServletRequest. Interface implementation getInputStream(),getReader() : binary & text streams handling getScheme() : what protocol is used? (http, https) getParameterNames(), getParameterValues() : parameters handling getContentType() : text/html, … getRemoteAddr(), getRemoteHost() HttpServletRequest : getHeaderNames() : HTTP header management getMethod() : HTTP Method used HTTP: GET,POST getRequestURI() : What URI the client asked for? Cookies management Session handling
Hello World ! public class Hello extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) HttpServletResponse resp) throws ServletException, IOException throws ServletException, IOException { resp.setContentType("text/html"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); PrintWriter out = resp.getWriter(); String name = req.getParameter("name"); String name = req.getParameter("name"); if(name==null) name="World !"; if(name==null) name="World !"; out.println(" "); out.println(" "); out.println("Hello " + name ); out.println("Hello " + name ); out.println(" "); out.println(" "); }}
Ways to call a Servlet JSP (Java Server Page) From a Document or WebBrowser From an other Servlet BookDBServlet database = (BookDBServlet) this.getServletConfig().getServletContext().getServlet ("bookdb"); SSI
Including external elements Including Servlet output into an other one: ServletContext sc = getServletContext(); RequestDispatcher d = sc.getRequestDispatcher( "/AnOtherServlet"); req.setAttribute("Param", "Value"); d.include(req, resp); Non dynamic element inclusion: URL url = sc.getResource(« /hello.html"); Out.print(url.getContent());
Multi-Threaded Environment Warning! Servlet’s Data are not thread- protected ! Two protections: Synchronized method; Implements SingleThreadModel Interface
Cookies Data stored on the client-side by the server Structure: Name, Value, Expiration date, domain, path Managed by the class javax.servlet.http.Cookie Java Class Cookie allows to read, add & remove HTTP Cookies (RFC 2109). Allows user’s session handling above HTTP Protocol
Reading / Adding Cookies Reading Cookies : Cookie [] cookies = req.getCookies(); for (int i=0 ; i < cookies.length ; i++) { out.print(cookies[i].getName() +"=" ); out.println(cookies[i].getValue() ); } Adding Cookies : userid = generationIDUtilisateur(); Cookie c = new Cookie("userid", userid); c.setDomain(".i2sconsulting.fr"); c.setPath("/"); resp.addCookie(c);
HTTP Session Session handling: Cookies Long URL Opening/retrieving a session javax.servlet.http.HttpSession session = req.getSession(false); // la session est récupérée ou null si elle n ’existait pas déjà javax.servlet.http.HttpSession session = req.getSession(true); // la session est récupérée ou ouverte si elle n ’existait pas déjà Session invalidation javax.servlet.http.HttpSession session = req.getSession(false); session.invalidate(); // la session est invalidée (i.e. fermée)
HttpSession - 1 Identification String sessionid= session.getId(); // Example: To1010mC At Creation date long datecreation= session.getCreationTime(); // nb de ms depuis 1/1/1970:00:00 Last access date long datelastaccess= session.getLastAccessedTime(); Example HttpSession session = req.getSession(true); if(session.getLastAccessedTime() - session.getCreationTime() > 5*60*1000 ) { session.invalidate(); }
HttpSession - 2 Session handling boolean HttpServletRequest.isRequestedSessionIdFromCookie() // is this session opened with a cookie? boolean HttpServletRequest.isRequestedSessionIdFromURL() // do we use URL rewrite method? URL Rewrite (if isRequestedSessionIdFromURL) URL generated must be encoded in order to keep the session String HttpServletResponse.encodeRedirectURL(String url) String HttpServletResponse.encodeURL(String url) Example res.sendRedirect(res.encodeRedirectURL("/servlet/login");
Adding Objects to a Session Used: database connection, carts… Adding/replacing a value void HttpSession.putValue(String name, Object value) Deleting a value void HttpSession.removeValue(String name) Getting objects associated to session String[] HttpSession.getValueNames() Object HttpSession.getValue(String name) Example HttpSession session = req.getSession(true); if(session.getLastAccessedTime() - session.getCreationTime() > 5*60*1000) { session.invalidate(); }
WebContainer Architecture