K. K. Wagh Polytechnic, Nashik Advance Java Programming Ch. No Name Marks 01 AWT 24 02 Networking 18 03 JDBC 20 04 Swing 05 Servlet Mr. Suyog. S. Dhoot Lecturer (IF Dept) K. K. Wagh Polytechnic, Nashik
Request-response model. Introduction – request-response model Request-response model. HTTP Request request Server <html> <head> <body> … <html> <head> <body> … Client response HTTP HTML
HTTP Request HTTP Response Introduction – what is a request and response HTTP Request HTTP Response Key elements of a “request” stream: HTTP method (action to be performed). The page to access (a URL). Form parameters. Key elements of a “response” stream: A status code (for whether the request was successful). Content-type (text, picture, html, etc…). The content ( the actual content).
HTTP Methods GET HEAD POST OPTIONS PUT DELETE TRACE
Where does Servlet come into the picture? Introduction – What is a Servlet Where does Servlet come into the picture? I can serve only static HTML pages Web Server Application Not a problem. I can handle dynamic requests. Helper Application Web Server machine “The Helper Application is nothing but a SERVLET”
Servlet Small Program execute on server side on web connection Runs on server side Not depend on browser compability It reads Explicit and implicit data and generate result Useful in e -commerce application
CGI Scripts CGI stands for “Common Gateway Interface” server Client sends a request to server Server starts a CGI script client server Script computes a result for server and quits script script Server returns response to client Another client sends a request Server starts the CGI script again Etc.
Servlets A servlet is like an applet, but on the server side server Client sends a request to server Server starts a servlet client server Servlet computes a result for server and does not quit servlet Server returns response to client Another client sends a request Server calls the servlet again Etc.
Servlet Alternatives Cold Fusion PHP: Open Source with file upload and session management ASP Windows IIS ASP.net JSP: Extension of Servlet
What is a Web Container? Servlet Architecture -Web Container Servlet request GET. ….. GET. ….. GET. ….. Web Server Web Container Servlet Client
How does the Container handle a request? Servlet Architecture – Web Container How does the Container handle a request? Servlet request Web Container Http request response Thread Web Server <Html> <Body> ……. </Body> </Html> response Service() Client doGet() Apache: Server Tomcat: Servlet Engine
Benefits Efficiency: More efficient – uses lightweight java threads Persistency: Servlets remain in memory. They can maintain state between requests. Portability: Since servlets are written in Java, they are platform independent. Robustness: Error handling, Garbage collector to prevent problems with memory leaks. Security: Security provided by the server as well as the Java Security Manager. Widespread acceptance: Java is a widely accepted technology. This means that numerous vendors work on Java-based technologies
Disadvantages High Maintenance High Complexity Working Disadvantages High Maintenance High Complexity Lower network efficiency More parts to be configure.
Servlet API Contains two package Javax.servlet.* Javax.servlet.http.* GenericServlet HTTPServlet 14 IBM 14
Javax.servlet.* Interfaces Servlet ServletConfig ServletContext: servlet access information about their environment ServletRequest ServletResponse SingleThreadModel 15 IBM 15
Javax.servlet.* Classes GenericServlet :implants Servlet ServletInputSteam ServletOutputStream: ServletRequest Exception ServletException UnavailableException 16 IBM 16
Life Cylce of Servlet 17 IBM
Life Cylce of Servlet Init() 1) It request for servlet 2) Loading of servlet 3) Resources initialized 4) Once called 5) Parameter: ServletConfig 18 IBM
Life Cylce of Servlet Service() 1) Handle request of client 2) only single instance created 3) Process client request and give response 4) Parameters: ServletRequest, ServletResponse 5) Only work with generic servlet 19 IBM
Life Cylce of Servlet Destroy() This method signifies the end of a servlet’s life. The resources allocated during init( ) are released. Save persistent information that will be used the next time the servlet is loaded. The servlet engine unloads the servlet. Calling destroy( ) yourself will not acutally unload the servlet. Only theservlet engine can do this. 20 IBM
First example import java.io.*; import javax.servlet.*; public class Pract15 extends GenericServlet { public void service(ServletRequest r, ServletResponse res) throws IOException, ServletException res.setContentType("text/html"); PrintWriter p = res.getWriter(); p.println("<HTML>"); p.println("<HEAD> Hello </HEAD>"); p.println("</HTML>"); } 21 IBM
ServletConfig getServletContext() getInitParameter(String name) getServletName() getInitParameterNames() - Enumeration 22 IBM 22
ServletRequest getContentLength() getContentType() getParamenter(String name) getParameterNames() getParameterValues ( String name) getProtocol() getRemoteHost() getRemoteAddr() 23 IBM
ServletResponse getCharacterEncoding() setContentType(string type) setContentLength(int length) 24 IBM
HttpServlet Interface HttpServletRequest HttpServletResponse HttpSession : Allows session data to be read or written HttpSessionBindingListener: Informs Object that it bound or unbound from session 25 IBM
HttpServlet Classes HttpServlet Cookie HttpSessionEvent HttpSessionBindingEvent 26 IBM
HttpServlet Method doGet doPost doTrace doOptions doDelete doPut doHead
HttpServletRequset Method getHeader (String field) getHeaderNames() getMethod() getPathInfo() getQueryString()
HttpServletResponse Method containsHeader (String Field) sendError (int c) sendError (int c,String s) sendRedirect (String url) setHeader (String Field, String Value)
Error Constant 202 SC_ACCEPTED 400 SC_BAD_REQUEST 403 SC_FORBIDDEN 200 SC_OK 404 SC_NOT_FOUND
Session Management Session: how long Particular User alive in the application Session Expires: Server Stopped Client Logout Session Management: Keeping Track of User Activities throughout application
Need of Session Management HTTP is stateless Protocol Separate Connection to web server when cient request for web page Server not maintain information of client E.g. Online Shopping
Techniques for session Tracking User Authentication URL Rewriting Hidden Form Field Cookie
User Authentication Servlet stores client username and password Easy to Implement and access site from different machine Client has to register his account
URL Rewriting Adding extra information along with client request Extra information: Session ID More burden on server E.g. www.msbte.com?session id=252
HiddenFormField Fields are added to html form Fields are not visible in client browser Fields info pass to server that act as visible field Not for static document and e-mail document
Cookie Small amount of information Sent from server that store in client Uniquely identify client Cookie send along with client request Present in javax.servlet.http.* package
Creating Cookie Cookie c1=new Cookie (String name, String value) Name and Value is mandatory parameter Neither the name nor the value should contain white space or any of the following characters: [ ] ( ) = , " / ? @ : ; Cookie may be temporary or persistent browsers generally only accept 20 cookies per site and 300 cookies total and since each cookie can be limited to 4 kilobytes
Cookie Attribute Attribute Type Mandatory? Name String Yes Value MaxAge int No Secure Boolean Comment Path Version
Cookie Methods setX() getX() X: Cookie Attribute Name
Cookie operations Send Cookie by server response.addCookie (Cookie c1) Retrieve Cookie request.getCookies() Return array of cookie
Sample code PrintWriter out= response.getWriter() Cookie c[]= request.getCookies() for( int i=0; i<c.length; i++) { Cookie c1=c[i]; out.println (“”+ c1. getName()); out.println (“”+ c1. getValue()); }
Servlet Filter A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet. The filters execute in the order that they are declared in the deployment descriptor. A filter is simply a Java class that implements the javax.servlet.Filter interface
javax.servlet.Filter methods
Servlet Chaining Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. . In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client.
Servlet Chaining The javax.servlet.RequestDispatcher interface comes with only two methods of include() and forward() RequestDispatcher is used whenever the Programmer would like dispatch the request to another resource (like HTML. Servlet, JSP etc.) on the server .
Servlet Chaining