1 TEMA 6. Applets y servlets 1.Introducción 2.Applets 3.Servlets.
Servlets O. De Pertat. Servlets Overview Generic Server Business logic API Java Syntax: classes...
-
Upload
osborn-fisher -
Category
Documents
-
view
217 -
download
1
Transcript of Servlets O. De Pertat. Servlets Overview Generic Server Business logic API Java Syntax: classes...
IT GROUP
Servlets O. De Pertat
Servlets Overview
Generic Server Business logic APIJava 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 APIPerformance for parameters transmissionRuns on every operating systemSecure : no SHELL escapes, no buffer overflowsJava programming language (PHP, VB.NET, Python)
Servlets Container used
Apache – Jakarta Tomcat :Conteneur de référence Officiel
http://jakarta.apache.org/tomcat/
IBM – WebSpherehttp://www.ibm.com
BEA – WebLogichttp://www.bea.com
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: <init-param>
<param-name>foo</param-name>
<param-value>bar</param-value>
</init-param>
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 implementiongetOutputStream()
getWriter()
HttpServletResponse :STATUS CODE : SC_OK, SC_NOT_FOUNDsetContentType() : "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 implementationgetInputStream() ,getReader() : binary & text streams handlinggetScheme() : what protocol is used? (http, https)getParameterNames(), getParameterValues() : parameters handlinggetContentType() : 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 class Hello extends HttpServlet
{{
public void doGet(HttpServletRequest req,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("<HTML>");out.println("<HTML>");
out.println("Hello " + name );out.println("Hello " + name );
out.println("</HTML>");out.println("</HTML>");
}}
}}
Ways to call a Servlet
JSP (Java Server Page)
From a Document or WebBrowserhttp://machine-name:port/servlet/servlet-name
Http://localhost:8080/servlet/bookdetails?bookId=203
From an other ServletBookDBServlet database = (BookDBServlet)
this.getServletConfig().getServletContext().getServlet("bookdb");
SSI<SERVLET NAME="Date">
<PARAM NAME="TimeZone"VALUE ="Paris" >
</SERVLET>
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 sessionjavax.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 invalidationjavax.servlet.http.HttpSession session = req.getSession(false);session.invalidate(); // la session est invalidée (i.e. fermée)
HttpSession - 1
IdentificationString sessionid= session.getId(); // Example: To1010mC8601021835741167At
Creation datelong datecreation= session.getCreationTime(); // nb de ms depuis 1/1/1970:00:00
Last access datelong datelastaccess= session.getLastAccessedTime();
ExampleHttpSession session = req.getSession(true);if(session.getLastAccessedTime() - session.getCreationTime() > 5*60*1000 ) {
session.invalidate(); }
HttpSession - 2
Session handlingboolean 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 sessionString HttpServletResponse.encodeRedirectURL(String url)String HttpServletResponse.encodeURL(String url)
Exampleres.sendRedirect(res.encodeRedirectURL("/servlet/login");
Adding Objects to a Session
Used: database connection, carts…
Adding/replacing a valuevoid HttpSession.putValue(String name, Object value)
Deleting a valuevoid HttpSession.removeValue(String name)
Getting objects associated to sessionString[] HttpSession.getValueNames()Object HttpSession.getValue(String name)
ExampleHttpSession session = req.getSession(true);if(session.getLastAccessedTime() - session.getCreationTime() > 5*60*1000)
{ session.invalidate(); }
WebContainer Architecture