Presentation is loading. Please wait.

Presentation is loading. Please wait.

Servlets O. De Pertat. Servlets Overview Generic Server Business logic API Java Syntax: classes extending the javax.servlet.Servlet interface or any sub-class.

Similar presentations


Presentation on theme: "Servlets O. De Pertat. Servlets Overview Generic Server Business logic API Java Syntax: classes extending the javax.servlet.Servlet interface or any sub-class."— Presentation transcript:

1 Servlets O. De Pertat

2 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)

3 Servlets Container used Apache – Jakarta Tomcat : Conteneur de référence Officiel http://jakarta.apache.org/tomcat/ IBM – WebSphere http://www.ibm.com BEA – WebLogic http://www.bea.com Alliance - iPlanet (Sun & NetScape) Oracle – IAS Allaire – Jrun Caucho’s Resin

4 Javax.servlet

5 Javax.servlet.http

6 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.

7 Servlets life cycle

8 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

9 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)....

10 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

11 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

12 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(" "); }}

13 Ways to call a Servlet JSP (Java Server Page) From a Document or WebBrowser http://machine-name:port/servlet/servlet-name Http://localhost:8080/servlet/bookdetails?bookId=203 From an other Servlet BookDBServlet database = (BookDBServlet) this.getServletConfig().getServletContext().getServlet ("bookdb"); SSI

14 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());

15 Multi-Threaded Environment Warning! Servlet’s Data are not thread- protected ! Two protections: Synchronized method; Implements SingleThreadModel Interface

16 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

17 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);

18 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)

19 HttpSession - 1 Identification String sessionid= session.getId(); // Example: To1010mC8601021835741167At 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(); }

20 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");

21 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(); }

22 WebContainer Architecture


Download ppt "Servlets O. De Pertat. Servlets Overview Generic Server Business logic API Java Syntax: classes extending the javax.servlet.Servlet interface or any sub-class."

Similar presentations


Ads by Google