2 December 2021 1 Servlet Name :: Mallikarjuna G D Reach me @ Training :: Email :: gdmallikarjuna@gmail.com
2 December 2021 2 Agenda • Introduction to Web Application Technologies • CGI Programs on the Web Server • What is servlet? • Jobs of servlet • Advantages over CGI • Why pages are build dynamically? • Servlet container • Installation & configuration - Type 1: Integration of Tomcat server and eclipse - Type 2: Java Servlet • Servlet Sample Example • Servlet Overview And Architecture - Servlet Life cycle/Single Thread Model - Interface Servlet - HttpServlet Class - HttpServletRequest, HttpServletResponse
2 December 2021 3 Agenda • Handling client request :Http request • Generating Server Response : Http status code • Handling Session - Cookies - Session Tracking - URL-re writing - Hidden Form fields
2 December 2021 4 Introduction to Web Application Technologies • World Wide Web: HTTP (Hypertext Transfer Protocol) is similar to FTP because it is a protocol to transfer files from the server to client. HTTP was created in conjunction with related HTML standard. HTML (Hypertext Markup Language) is a document display language that lets users link from one document to another. HTML permits images and other media objects to be embedded in an HTML document. The media objects are stored in files on a server. HTTP also retrieves these files. Therefore HTTP can be used to transmit any file that confirms to multipurpose Internet Mail Extensions (MIME) specification.
2 December 2021 5 • Web Browsers and and Web Servers: To view an HTML document with rich media content, a graphical user interface was built on the top of the client-side HTTP. This GUI is called as web browser. The server-side HTTP component is called a web server. • Web Applications: Early in the development of HTML, the designers created a mechanism to permit a user to invoke a program on the web server. This mechanism was called as Common Gateway Interface (CGI). When a website includes CGI processing, this is called a web application. (Contd..)
2 December 2021 6 CGI Programs on the Web Server • The browser needs to send data to the CGI program on the server. The CGI specification defines how the data is packaged and sent in the HTTP request to the server. This data is usually typed into the web browser in an HTML form. • The URL determines which CGI program to execute. This might be a script or an executable file. • The CGI program parses the CGI data in the request, processes the data, and generates a response. • The CGI response is sent back to the web server, which wraps the response in an HTTP response. • The HTTP response is sent back to the web browser.
2 December 2021 7 Web Server Architecture with CGI Programs (Contd..)
2 December 2021 8 Advantages and Disadvantages of CGI Programs • Programs can be written in a variety of languages, although they are primarily written in Perl. • A CGI program with bugs does not crash the web server. • Programs are easy for a web designer to reference. When the script is written, the designer can reference it in one line in a web page. • Because CGI programs execute in their own OS Shell, these programs do not have concurrency conflicts with other HTTP requests executing the same CGI program. • All service provides support CGI programs.
2 December 2021 9 • The response time of CGI programs is high because CGI programs execute in their own OS shell. The creation of an OS shell is a heavyweight activity for the OS. • CGI is not scalable. • The languages for CGI are not always secure or object-oriented. • The CGI script has to generate an HTML response, so the CGI code is mingled with HTML. This is not good separation of presentation and business logic. • Scripting languages are often platform-dependent. Disadvantages
• Servlet is a program that runs on server acts as a middle layer between a request coming from web-browser or other HTTP Clients and database or applications on the Server. • Improved substitute for CGI Scripts. • Are executed in context of web server. • Part of JEE (Servlet API 2.4) • Helps client server communication. 2 December 2021 10 What is Servlet?
2 December 2021 11 Jobs of servlet? • Read explicit data sent by client (form data) • Read implicit data sent by client (request header) • Generate the result • Send the explicit data back to client (e.g. HTML format) • Send the implicit data to client (status code and response header) Servlet: HTTP Web Server File system Servlet Server Static Tomcat = Web Server + Servlet Server Other.. Dynamic
2 December 2021 12 Advantages of Servlet over CGI • Efficient/Scalable-handled by separate thread within web-server process. • Convenient - lot of high level utilities. • Powerful – Sharing data, pooling, persistence. • Portable – Run virtually on all operating systems and servers. • Security – No shell escapes, no bufferflow. • Inexpensive.
2 December 2021 13 Disadvantages: • Servlets often contain both business logic and presentation logic. Presentation logic is anything that controls how the application presents information to the user. Generating the HTML response within the servlet code is presentation logic. Business logic is anything that manipulates data to accomplish something such as storing data. • Servlets must handle concurrency issues. • Mixing presentation and business logic means that whenever a web page changes the servlets must be rewritten, recompiled and redeployed. • This disadvantage led to the development of template pages, including Java Server Pages technology.
2 December 2021 14 Why build pages dynamically? • The web page is based on data submitted by the user. e.g.:- result in search engines , online shopping so on. • The web pages are derived from the data changes frequently. e.g.:-weather report, stock exchange, news headline. • The web pages are derived from data from databases or other server side resources. e.g.:- e-commerce page shows availability of product with price information.
2 December 2021 15 Servlet Container/Servlet Engine • The servlet container is compiled, executable program. The container acts as intermediator between webserver and servlet in the container. • The container loads, initializes and executes servlet. When request arrives container maps to servlet. • The container is designed to perform well by serving large number of requests. A container can hold any number of servlets, filters and listener. • Both the container and object contained in it are multithreaded. The container handles multiple requests concurrently, and more than one thread may enter an object at a time. Therefore, each object within a container must be thread safe.
2 December 2021 16 (Contd..) There are three kinds of servlet engine - standalone - add on - embedded • Standalone Servlet Engines - Built in support for servlets. - Hard to keep latest version of servlet. • Add on servlet Servlet-engines - Plug-in to an existing servlets. • Embeddable servlet engines - lightweight servlet-deployment platform that can be embedded in another application.
2 December 2021 17 List of servlet containers Non commercial: • Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under the Apache Software License. • Apache Geronimo -is a full Java EE implementation by Apache. • Jetty • Jaminid - contains a higher abstraction than servlets. • Enhydra • Winstone - supports specification v2.4, has a focus on minimal configuration and the ability to strip the container down to only what you need. • tjws - spec 2.4, small footprint, modular design
2 December 2021 18 Commercial: • BEA WebLogic Server or Weblogic Express, from BEA Systems • Borland Enterprise Server • GlassFish (open source) • Java System Application Server, from Sun Microsystems • Java System Web Server, from Sun Microsystems • JBoss (open source) • JRun, from Adobe Systems (formerly developed by Allaire Corporation) (Contd..)
2 December 2021 19 • LiteWebServer (open source) • Oracle Application Server, from Oracle Corporation • Orion Application Server, from IronFlare • Caucho's Resin Server • ServletExec, from New Atlanta Communications • WebObjects, from Apple Inc. • WebSphere, from IBM (Contd..)
2 December 2021 20 • The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of a Web container and a servlet. • A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. • A Servlet is an object that receives a request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment Java Servlet API
2 December 2021 21 Servlet API History The complete servlet specification was created by Sun Microsystems, with version 1.0 finalized in June 1997. Starting with version 2.3, the servlet specification was developed under the Java Community Process.
2 December 2021 22 Installation and Configuration • Step 1: jdk 11.0 • Download the JDK 11.0 offline installation file (Windows Offline Installation, Multi-language) from Oracle' https://www.oracle.com/java/technologies/downloads/#java11-windows. The online installation will download the installation files through the internet and you will have to re-download them each time you format your HD. • Double click on the .exe file (throughout I assume XP or VISTA or Windows 10, or some other crappy Micro$oft OS). The following screen should pop up:
2 December 2021 23 (Contd..)
2 December 2021 24 (Contd..) We still have to go that extra bit and set up some environment variables - primarily create JAVA_HOME and edit the PATH system variable. In the computers Control Panel double click on the System icon and select the Advanced tab. The result should be something not foreign to the screenshot below:
2 December 2021 25 (Contd..) Set path to the java_home/bin:, finally restart.. And open command prompt to check java installed by giving java –version in prompt.
2 December 2021 26 • Step 2: Install Eclipse download eclipse IDE from http://www.eclipse.org/downloads/ and extract to the required folder. • Step 3: Install Jakarta Tomcat download tomcat 9.x from this site in zip format http://tomcat.apache.org/, then extract to required folder. (Contd..)
2 December 2021 27 (Contd..) • Step 5: Configure Eclipse - start eclipse, and do configuration as per below screen shots.
2 December 2021 28 (Contd..)
2 December 2021 29 Simple Servlet configuration & development 1. Select File > New > Dynamic Web Project..
2 December 2021 30 (Contd..) Input the following code in to the file SimpleServlet.java and click Save button in toolbar. import java.io.PrintWriter; public class SimpleServlet extends javax.servlet.http.HttpServlet { public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { performTask(request, response); } public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { performTask(request, response); }
2 December 2021 31 (Contd..) public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "This is a Simple Servlet Demo"); } catch(Throwable theException) { //theException.printStackTrace(); } } }
2 December 2021 32 (Contd..) Web.xml content: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <servlet> <servlet-name>SimpleServlet</servlet-name> <servlet-class>SimpleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleServlet</servlet-name> <url-pattern>/SimpleServlet</url-pattern> </servlet-mapping> </web-app>
2 December 2021 33 (Contd..) Press the Start Tomcat button in tool bar, after tomcat starts, open a browser and input the URL: http://localhost:8080/ServletDemo/SimpleServlet The result will show as below:
2 December 2021 34 (Contd..) Finally, run the server to see output.
2 December 2021 35 Directory Structure
2 December 2021 36 Servlet Life cycle and Architecture Servlets are first standard to extension to java including two packages: -javax.servlet -javax.servlet.http In general, servlet 1. Generic Servlet - must extend javax.servlet.Servlet - protocol independent 2. Http Servlet - must extend javax.servlet.http.HttpServlet - Handling Http request/reply
2 December 2021 37 (Contd..) Http Servlet: Generic Servlet:
2 December 2021 38 Servlet Life Cycle • The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps: - If an instance of the servlet does not exist, the Web container loads the servlet class. Creates an instance of the servlet class. Initializes the servlet instance by calling the init method. - Invokes the service method, passing a request and response object. • If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.
2 December 2021 39 Servlet Life Cycle
2 December 2021 40 (Contd..) Java class that implements the Servlet interface • Servlet Interface – Defines the Servlet’s life cycle methods. – init(ServletConfig config) – service(ServletRequest req, ServletResponse res) - doGet handles GET request. - doPost handles POST request. – destroy() Called by the servlet container before servlet is taken out of service.
2 December 2021 41 Allowing concurrency: Single thread Model • Container may send multiple request to single instance , using java threads. So service methods (doGet, doPost..) are all thread safe. It means two or more threads operating without interfere each other. • If service methods not thread safe. We have to use single thread model. • The single thread model ensures that only one service method runs at time
2 December 2021 42 Servlet Interface Servlet interface { void init(ServletConfig sc) throws ServletException; void service(ServletRequest req,ServletResponse res) throws ServletException,IOException; void destroy(); }
2 December 2021 43 Methods of Servlet Method Description void init( ServletConfig config ) The servlet container calls this method once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet. ServletConfig getServletConfig( ) This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes). String getServletInfo() This method is defined by a servlet programmer to return a string containing servlet information such as the servlet’s author and version. void service( ServletRequest request, ServletResponse response ) The servlet container calls this method to respond to a client request to the servlet. void destroy() This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection, should be deallocated here.
2 December 2021 44 Http Servlet • Override the servlet class • There are two types of request- Get and Post - doGet responds to Get request -doPost responds to Post request • It has HttpServletRequest and HttpServletResponse Objects
2 December 2021 45 (Contd..) Method Description doDelete Called in response to an HTTP delete request. Such a request is normally used to delete a file from a server. This may not be available on some servers, because of its inherent security risks (e.g., the client could delete a file that is critical to the execution of the server or an application). doHead Called in response to an HTTP head request. Such a request is normally used when the client only wants the headers of a response, such as the content type and content length of the response. doOptions Called in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the version of HTTP (1.0 or 1.1) and the request methods the server supports. doPut Called in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers, because of its inherent security risks (e.g., the client could place an executable application on the server, which, if executed, could damage the server—perhaps by deleting critical files or occupying resources). doTrace Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically returns an HTML document to the client containing the request header information (data sent by the browser as part of the request).
2 December 2021 46 HttpServletRequest Interface • Web server - creates an HttpServletRequest object. - passes it to the servlet’s service method. • HttpServletRequest object contains the request from the client.
2 December 2021 47 (Contd..) Method Description String getParameter( String name ) Obtains the value ofa parameter sent to the servlet as part ofa get or post request. The name argument represents the parameter name. Enumeration getParameterNames() Returns the names ofallthe parameters sent to the servlet as part ofa post request. String[] getParameterValues( String name ) For a parameter with multiple values, this method returns anarrayofstrings containing the values for a specified servlet parameter. Cookie[] getCookies() Returns anarrayof Cookie objects stored onthe client bythe server. Cookie objects canbe used to uniquely identifyclients to the servlet. HttpSession getSession( booleancreate ) Returns an HttpSession object associated withthe client’s current browsing session. This method cancreate an HttpSession object (true argument) ifone does not alreadyexist for the client. HttpSession objects are used insimilar ways to Cookies for uniquely identifying clients.
2 December 2021 48 HttpServletResponse Interface Method Description void addCookie( Cookie cookie ) Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and whether Cookies are enabled on the client determine if Cookies are stored on the client. ServletOutputStream getOutputStream() Obtains a byte-based output stream for sending binary data to the client. PrintWriter getWriter() Obtains a character-based output stream for sending text data to the client. void setContentType( String type ) Specifies the MIME type of the response to the browser. The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page. • Web server - creates an HttpServletResponse object. - passes it to the servlet’s service method.
2 December 2021 49 Handling client request : Http request header General: getHeader, getHeaders, getHeaderNames. Specialized: getCookies, getAuthType, getRemoteUser, getContentLength, getContentType, getDateHeader, getIntHeader Related Info: getMethod, getRequestURI, getProtocol
2 December 2021 50 (Contd..)
2 December 2021 51 Common HTTP Request Header 1.1 • Accept - MIME Types of browser can handle. - Can send different content to different clients. • Accept-Encoding - Indicate encoding (e.g gzip) browser can handle. • Authorization - User identification for password protected pages. • Connection - In Http 1.1, keep alive means browser can handle persistent connection. Persistent connection is default. Persistent means same socket is reused for same type of client request.
2 December 2021 52 (Contd..) • Cookie - Give cookies previously sent to client. • Host - It gives host given in original URL. • If-Modified-Since - Client wants pages, only after changed on some specified dates. • Referrer - URL of referring web page. - Useful for tracking traffic; logged by many servers. • User Agent - String identifying the browser making request.
2 December 2021 53 Generating server response: http status code Purpose: The variety of status code that are essentially indicate failure. e.g.:- HTTP/1.1 200 OK • Changing a status code perform a lot of tasks. - Forward client to another page. - Indicate a missing resource. - Instruct a browser to use cached copy. • Set status before sending document. public void setStatus (int statusCode) - use constant for the code. Not an explicit int. constants are HttpServletResponse. - Names derived from standard message. e.g SC_OK, SC_NOT_FOUND so on. • public sendError(int code, String msg) - Wraps the message inside HTML document.
2 December 2021 54 (Contd..) • Public void sendRedirect(String url) - Relative url is permitted in 2.2/2.3 - Also sets location header. Common HTTP 1.1 Status codes: • 200(OK) - Everything is fine, document follows, default for servlets. • 204(No content) - Browser should keep displaying previous document. • 301(Moved document) - Requested document moved elsewhere. - Browsers go to new location automatically.
2 December 2021 55 (Contd..) • 401(unauthorized) Browser tried to access protected page without proper authorization header. • 404(Not found) No such page. In general 100-199 -> codes in the 100s are informational, indicating that the client should respond with some other action. 200-299 -> values in the 200’s signify that the request was successful. 300-399 -> values in the 300’s are used for files that have moved and usually include location header indicating the new address.
2 December 2021 56 (Contd..) 400-499 -> values in the 400’s indicate an error by the client. 500-599 ->codes in the 500’s signify an error by the server. Common MIME Type:
2 December 2021 57 Session Handling • A server site typically needs to maintain two types of persistent(remembered) information: - Information about the Session. - Information about the User. • Servlet capabilities: Servlets, like Applets, can be trusted or untrusted. - A servlet can use a unique ID to store and retrieve information about a given session. - User information usually requires a login ID and a password. - Since servlets don’t quit between requests, any servlet can maintain information in its internal data structures, as long as the server keeps running.
2 December 2021 58 (Contd..) - A trusted servlet can read and write files on the server, hence can maintain information about sessions and users even when the server is stopped and restarted. - An untrusted servlet will lose all information when the servlet or server stops for any reason. This is sometimes good enough for session information. This is almost never good enough for user information. - HTTP is stateless: When it gets a page request, it has no memory of any previous requests from the same client.
2 December 2021 59 (Contd..) • Session tracking is keeping track of what has gone before in this particular conversation. - Since HTTP is stateless, it does not do this for you. - You have to do it yourself, in your servlets. - This makes it difficult to hold a “conversation”. Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests. - The server must be able to keep track of multiple conversations with multiple users.
2 December 2021 60 • Cookies are small files that the servlet can store on the client computer, and retrieve later. • URL rewriting: You can append a unique ID after the URL to identify the user. • Hidden <form> fields can be used to store a unique ID. • Java’s Session Tracking API can be used to do most of the work for you. Session tracking solution
2 December 2021 61 Cookies • Cookies are small bits of textual information that a web server sends to the browser and that the browser returns unchanged when later visiting the same website or domain. • Cookies are not a security threat. • Cookies can be a privacy threat. - Cookies can be used to customize advertisements. - Outlook Express allows cookies to be embedded in email. - A servlet can read your cookies. Incompetent companies might keep your credit card info in a cookie. Netscape lets you refuse cookies to sites other than that to which you connected.
2 December 2021 62 Why do we need cookies? • Cookies are a very useful tool in maintaining state (persistence) on the Web. Unless something special is done, web servers are only aware of users when a transaction -- sending or receiving information -- is in process. The moment the transaction is complete the server forgets about the user and makes no attempt to correlate subsequent transactions with previous exchanges. • Since the web protocol, HTTP, is a "stateless" (non-persistent) protocol, it is impossible to differentiate between visits to a given web site, unless the server can somehow "mark" a visitor. • This is done by storing a piece of information in the visitor's browser, called a "cookie". Cookies can contain database information, custom page settings, or just about anything that would make a site customizable.
2 December 2021 63 Using cookies • import javax.servlet.http.*; • Constructor: Cookie(String name, String value) • Assuming request is an HttpServletRequest and response is an HttpServletResponse, response.addCookie(cookie); Cookie[ ] cookies = request.getCookies(); String name = cookies[i].getName(); String value = cookies[i].getValue(); • There are, of course, many more methods in the HttpServletRequest, HttpServletResponse, and Cookie classes in the javax.servlet.http package.
2 December 2021 64 (Contd..) • public void setComment(String purpose) - public String getComment() • public void setMaxAge(int expiry) - public int getMaxAge() - Max age in seconds after which cookie will expire. - If expiry is negative, delete when browser exits. - If expiry is zero, delete cookie immediately. • setSecure(boolean flag) - public boolean get Secure() - Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.
2 December 2021 65 (Contd..) Here is the code snippet for initializing a cookie and adding the same to the response object. ..... Cookie cookie = new Cookie ("otncookiename",userName); cookie.setMaxAge(86400); response.addCookie(cookie); Cookie onemorecookie = new Cookie("otncookiepassword",password); onemorecookie.setMaxAge(86400); response.addCookie (onemorecookie); ..... Setting cookies:
2 December 2021 66 (Contd..) Retrieving a cookie value: Here is the code snippet for selecting cookie values from the request object. ...... Cookie[] cookieArray = request.getCookies(); if( cookieArray != null) { for( int i = cookieArray.length-1; i >= 0; i-- ) { Cookie cookie = cookieArray[i]; System.out.println ("Cookie name is " + cookie.getName()); System.out.println ("Cookie value is " + cookie.getValue()); } } ......
2 December 2021 67 (Contd..) Code snippet: Login.html <form name="login" method="post" action="./LoginCookieServlet"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> LoginCookieServlet String name= request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); Cookie userNameCookie = new Cookie("USERNAME", name); response.addCookie(userNameCookie); Cookie passwordCookie = new Cookie("PASSWORD",pwd); response.addCookie(passwordCookie); request.getRequestDispatcher("/LoginNextCookie").forward(request, response);
2 December 2021 68 (Contd..) Code snippet: LoginNextCookie Cookie[] cookies = request.getCookies(); pw.println("cookies[0].getValue()"+cookies[0].getValue()); pw.println("cookies[1].getValue()"+cookies[1].getValue()); for(Cookie cookie: cookies) { pw.println(cookie.getValue()); }
2 December 2021 69 Limitation • The browser should be enabled to accept cookies. • Cookie values must never have spaces, commas or semicolons. • Cookies can store upto 4KB of value.
2 December 2021 70 URL-Rewritting • URL rewriting is another way to support anonymous session tracking. • With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information. • The extra information can be in the form of extra path information, added parameters, or some custom, server-specific URL change. • Due to the limited space available in rewriting a URL, the extra information is usually limited to a unique session ID.
2 December 2021 71 URL-Rewritting • For example, the following URLs have been rewritten to pass the session ID 123: http://server: port/servlet/Rewritten original http://server:port/servlet/Rewritten/123 extra path information http://server:port/servlet/Rewritten?sessionid=123 added parameter http://server:port/servlet/Rewritten;$sessionid$123 custom change
2 December 2021 72 URL-Rewritting • code snippet Loginurlrewriting.html <form name="login" method="post" action="./URLRewriting"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> URLRewriting.java response.getWriter().append("Served at: ").append(request.getContextPath()); String name= request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); request.getRequestDispatcher("/LoginUrlReceive?uname="+name+"&&pwd="+pwd).forward(request , response);
2 December 2021 73 URL-Rewritting • code snippet LoginUrlReceive.java String username = request.getParameter("uname"); String password = request.getParameter("pwd"); pw.println("LoginUrlReceive username::"+username+"password::"+password);
2 December 2021 74 Hidden form fields • One way to support anonymous session tracking is to use hidden form fields. As the name implies, these are fields added to an HTML form that are not displayed in the client's browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this: • <FORM ACTION="/servlet/MovieFinder" METHOD="POST"> ... <INPUT TYPE=hidden NAME="zip" VALUE="94040"> <INPUT TYPE=hidden NAME="level" VALUE="expert"> .. </FORM> In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.
2 December 2021 75 Hidden form fields • code snippet Loginhidform.html <form name="login" method="post" action="./HiddenServlet"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> HiddenServlet.java String name = request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); out.print("<form action='./LoginUrlReceive'>"); out.print("<input type='hidden' name='uname' value='" + name + "'>"); out.print("<input type='hidden' name='pwd' value='" + pwd + "'>"); out.print("<input type='submit' value='go'>"); out.print("</form>");
2 December 2021 76 Hidden form fields • code snippet LoginUrlReceive.java String username = request.getParameter("uname"); String password = request.getParameter("pwd"); pw.println("LoginUrlReceive username::"+username+"password::"+password);
2 December 2021 77 Session tracking API • The session tracking API is in javax.servlet.http.HttpSession and is built on top of cookies. • To use the session tracking API: - Create a session: HttpSession session = request.getSession(); Returns the session associated with this request If there was no associated session, one is created. - Store information in the session and retrieve it as needed: session.setAttribute (name, value); Object obj = getAttribute(name); • Session information is automatically maintained across requests.
2 December 2021 78 Looking up information associated with session • getId - This method returns the unique identifier generated for each session. It is sometimes used as the key name when there is only a single value associated with a session, or when logging information about previous sessions. • isNew - This returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions.
2 December 2021 79 • getCreationTime - This returns the time, in milliseconds since the epoch, at which the session was made. To get a value useful for printing out, pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar. • getLastAccessedTime - This returns the time, in milliseconds since the epoch, at which the session was last sent from the client. • getMaxInactiveInterval - This returns the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never timeout. (Contd..)
2 December 2021 80 • Public Object getValue(String name) • Public Object getAttribute (String name) • Public Object setValue(String name, Object value) • Public Object setAttribute (String name, Object value) • Public Object removeValue(String name) • Public Object removeAttribute(String name) (Contd..)
2 December 2021 81 Code snippet Loginsession.html <form name="login" method="post" action="./AdminServletSession"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> AdminServletSession.java HttpSession session = request.getSession(true); String reqUsername = request.getParameter("txtUserName"); String reqPassword = request.getParameter("txtPassword"); out.println("AdminServletSession::"+"username::"+reqUsername+ "password ::"+reqPassword); session.setAttribute("USERNAME", reqUsername); session.setAttribute("PASSWORD", reqPassword); request.getRequestDispatcher("./HRServletSession").forward(request, response); (Contd..)
2 December 2021 82 Code snippet Loginsession.html < HttpSession session = request.getSession(true); String sessionUsername =(String) session.getAttribute("USERNAME"); String sessionPassword = (String) session.getAttribute("PASSWORD"); out.println("HRServletSession::"+"username::"+sessionUsername+ "password ::"+sessionPassword); (Contd..)

Servlet programming

  • 1.
    2 December 20211 Servlet Name :: Mallikarjuna G D Reach me @ Training :: Email :: gdmallikarjuna@gmail.com
  • 2.
    2 December 20212 Agenda • Introduction to Web Application Technologies • CGI Programs on the Web Server • What is servlet? • Jobs of servlet • Advantages over CGI • Why pages are build dynamically? • Servlet container • Installation & configuration - Type 1: Integration of Tomcat server and eclipse - Type 2: Java Servlet • Servlet Sample Example • Servlet Overview And Architecture - Servlet Life cycle/Single Thread Model - Interface Servlet - HttpServlet Class - HttpServletRequest, HttpServletResponse
  • 3.
    2 December 20213 Agenda • Handling client request :Http request • Generating Server Response : Http status code • Handling Session - Cookies - Session Tracking - URL-re writing - Hidden Form fields
  • 4.
    2 December 20214 Introduction to Web Application Technologies • World Wide Web: HTTP (Hypertext Transfer Protocol) is similar to FTP because it is a protocol to transfer files from the server to client. HTTP was created in conjunction with related HTML standard. HTML (Hypertext Markup Language) is a document display language that lets users link from one document to another. HTML permits images and other media objects to be embedded in an HTML document. The media objects are stored in files on a server. HTTP also retrieves these files. Therefore HTTP can be used to transmit any file that confirms to multipurpose Internet Mail Extensions (MIME) specification.
  • 5.
    2 December 20215 • Web Browsers and and Web Servers: To view an HTML document with rich media content, a graphical user interface was built on the top of the client-side HTTP. This GUI is called as web browser. The server-side HTTP component is called a web server. • Web Applications: Early in the development of HTML, the designers created a mechanism to permit a user to invoke a program on the web server. This mechanism was called as Common Gateway Interface (CGI). When a website includes CGI processing, this is called a web application. (Contd..)
  • 6.
    2 December 20216 CGI Programs on the Web Server • The browser needs to send data to the CGI program on the server. The CGI specification defines how the data is packaged and sent in the HTTP request to the server. This data is usually typed into the web browser in an HTML form. • The URL determines which CGI program to execute. This might be a script or an executable file. • The CGI program parses the CGI data in the request, processes the data, and generates a response. • The CGI response is sent back to the web server, which wraps the response in an HTTP response. • The HTTP response is sent back to the web browser.
  • 7.
    2 December 20217 Web Server Architecture with CGI Programs (Contd..)
  • 8.
    2 December 20218 Advantages and Disadvantages of CGI Programs • Programs can be written in a variety of languages, although they are primarily written in Perl. • A CGI program with bugs does not crash the web server. • Programs are easy for a web designer to reference. When the script is written, the designer can reference it in one line in a web page. • Because CGI programs execute in their own OS Shell, these programs do not have concurrency conflicts with other HTTP requests executing the same CGI program. • All service provides support CGI programs.
  • 9.
    2 December 20219 • The response time of CGI programs is high because CGI programs execute in their own OS shell. The creation of an OS shell is a heavyweight activity for the OS. • CGI is not scalable. • The languages for CGI are not always secure or object-oriented. • The CGI script has to generate an HTML response, so the CGI code is mingled with HTML. This is not good separation of presentation and business logic. • Scripting languages are often platform-dependent. Disadvantages
  • 10.
    • Servlet isa program that runs on server acts as a middle layer between a request coming from web-browser or other HTTP Clients and database or applications on the Server. • Improved substitute for CGI Scripts. • Are executed in context of web server. • Part of JEE (Servlet API 2.4) • Helps client server communication. 2 December 2021 10 What is Servlet?
  • 11.
    2 December 202111 Jobs of servlet? • Read explicit data sent by client (form data) • Read implicit data sent by client (request header) • Generate the result • Send the explicit data back to client (e.g. HTML format) • Send the implicit data to client (status code and response header) Servlet: HTTP Web Server File system Servlet Server Static Tomcat = Web Server + Servlet Server Other.. Dynamic
  • 12.
    2 December 202112 Advantages of Servlet over CGI • Efficient/Scalable-handled by separate thread within web-server process. • Convenient - lot of high level utilities. • Powerful – Sharing data, pooling, persistence. • Portable – Run virtually on all operating systems and servers. • Security – No shell escapes, no bufferflow. • Inexpensive.
  • 13.
    2 December 202113 Disadvantages: • Servlets often contain both business logic and presentation logic. Presentation logic is anything that controls how the application presents information to the user. Generating the HTML response within the servlet code is presentation logic. Business logic is anything that manipulates data to accomplish something such as storing data. • Servlets must handle concurrency issues. • Mixing presentation and business logic means that whenever a web page changes the servlets must be rewritten, recompiled and redeployed. • This disadvantage led to the development of template pages, including Java Server Pages technology.
  • 14.
    2 December 202114 Why build pages dynamically? • The web page is based on data submitted by the user. e.g.:- result in search engines , online shopping so on. • The web pages are derived from the data changes frequently. e.g.:-weather report, stock exchange, news headline. • The web pages are derived from data from databases or other server side resources. e.g.:- e-commerce page shows availability of product with price information.
  • 15.
    2 December 202115 Servlet Container/Servlet Engine • The servlet container is compiled, executable program. The container acts as intermediator between webserver and servlet in the container. • The container loads, initializes and executes servlet. When request arrives container maps to servlet. • The container is designed to perform well by serving large number of requests. A container can hold any number of servlets, filters and listener. • Both the container and object contained in it are multithreaded. The container handles multiple requests concurrently, and more than one thread may enter an object at a time. Therefore, each object within a container must be thread safe.
  • 16.
    2 December 202116 (Contd..) There are three kinds of servlet engine - standalone - add on - embedded • Standalone Servlet Engines - Built in support for servlets. - Hard to keep latest version of servlet. • Add on servlet Servlet-engines - Plug-in to an existing servlets. • Embeddable servlet engines - lightweight servlet-deployment platform that can be embedded in another application.
  • 17.
    2 December 202117 List of servlet containers Non commercial: • Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under the Apache Software License. • Apache Geronimo -is a full Java EE implementation by Apache. • Jetty • Jaminid - contains a higher abstraction than servlets. • Enhydra • Winstone - supports specification v2.4, has a focus on minimal configuration and the ability to strip the container down to only what you need. • tjws - spec 2.4, small footprint, modular design
  • 18.
    2 December 202118 Commercial: • BEA WebLogic Server or Weblogic Express, from BEA Systems • Borland Enterprise Server • GlassFish (open source) • Java System Application Server, from Sun Microsystems • Java System Web Server, from Sun Microsystems • JBoss (open source) • JRun, from Adobe Systems (formerly developed by Allaire Corporation) (Contd..)
  • 19.
    2 December 202119 • LiteWebServer (open source) • Oracle Application Server, from Oracle Corporation • Orion Application Server, from IronFlare • Caucho's Resin Server • ServletExec, from New Atlanta Communications • WebObjects, from Apple Inc. • WebSphere, from IBM (Contd..)
  • 20.
    2 December 202120 • The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of a Web container and a servlet. • A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. • A Servlet is an object that receives a request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment Java Servlet API
  • 21.
    2 December 202121 Servlet API History The complete servlet specification was created by Sun Microsystems, with version 1.0 finalized in June 1997. Starting with version 2.3, the servlet specification was developed under the Java Community Process.
  • 22.
    2 December 202122 Installation and Configuration • Step 1: jdk 11.0 • Download the JDK 11.0 offline installation file (Windows Offline Installation, Multi-language) from Oracle' https://www.oracle.com/java/technologies/downloads/#java11-windows. The online installation will download the installation files through the internet and you will have to re-download them each time you format your HD. • Double click on the .exe file (throughout I assume XP or VISTA or Windows 10, or some other crappy Micro$oft OS). The following screen should pop up:
  • 23.
    2 December 202123 (Contd..)
  • 24.
    2 December 202124 (Contd..) We still have to go that extra bit and set up some environment variables - primarily create JAVA_HOME and edit the PATH system variable. In the computers Control Panel double click on the System icon and select the Advanced tab. The result should be something not foreign to the screenshot below:
  • 25.
    2 December 202125 (Contd..) Set path to the java_home/bin:, finally restart.. And open command prompt to check java installed by giving java –version in prompt.
  • 26.
    2 December 202126 • Step 2: Install Eclipse download eclipse IDE from http://www.eclipse.org/downloads/ and extract to the required folder. • Step 3: Install Jakarta Tomcat download tomcat 9.x from this site in zip format http://tomcat.apache.org/, then extract to required folder. (Contd..)
  • 27.
    2 December 202127 (Contd..) • Step 5: Configure Eclipse - start eclipse, and do configuration as per below screen shots.
  • 28.
    2 December 202128 (Contd..)
  • 29.
    2 December 202129 Simple Servlet configuration & development 1. Select File > New > Dynamic Web Project..
  • 30.
    2 December 202130 (Contd..) Input the following code in to the file SimpleServlet.java and click Save button in toolbar. import java.io.PrintWriter; public class SimpleServlet extends javax.servlet.http.HttpServlet { public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { performTask(request, response); } public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { performTask(request, response); }
  • 31.
    2 December 202131 (Contd..) public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "This is a Simple Servlet Demo"); } catch(Throwable theException) { //theException.printStackTrace(); } } }
  • 32.
    2 December 202132 (Contd..) Web.xml content: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <servlet> <servlet-name>SimpleServlet</servlet-name> <servlet-class>SimpleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleServlet</servlet-name> <url-pattern>/SimpleServlet</url-pattern> </servlet-mapping> </web-app>
  • 33.
    2 December 202133 (Contd..) Press the Start Tomcat button in tool bar, after tomcat starts, open a browser and input the URL: http://localhost:8080/ServletDemo/SimpleServlet The result will show as below:
  • 34.
    2 December 202134 (Contd..) Finally, run the server to see output.
  • 35.
    2 December 202135 Directory Structure
  • 36.
    2 December 202136 Servlet Life cycle and Architecture Servlets are first standard to extension to java including two packages: -javax.servlet -javax.servlet.http In general, servlet 1. Generic Servlet - must extend javax.servlet.Servlet - protocol independent 2. Http Servlet - must extend javax.servlet.http.HttpServlet - Handling Http request/reply
  • 37.
    2 December 202137 (Contd..) Http Servlet: Generic Servlet:
  • 38.
    2 December 202138 Servlet Life Cycle • The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps: - If an instance of the servlet does not exist, the Web container loads the servlet class. Creates an instance of the servlet class. Initializes the servlet instance by calling the init method. - Invokes the service method, passing a request and response object. • If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.
  • 39.
    2 December 202139 Servlet Life Cycle
  • 40.
    2 December 202140 (Contd..) Java class that implements the Servlet interface • Servlet Interface – Defines the Servlet’s life cycle methods. – init(ServletConfig config) – service(ServletRequest req, ServletResponse res) - doGet handles GET request. - doPost handles POST request. – destroy() Called by the servlet container before servlet is taken out of service.
  • 41.
    2 December 202141 Allowing concurrency: Single thread Model • Container may send multiple request to single instance , using java threads. So service methods (doGet, doPost..) are all thread safe. It means two or more threads operating without interfere each other. • If service methods not thread safe. We have to use single thread model. • The single thread model ensures that only one service method runs at time
  • 42.
    2 December 202142 Servlet Interface Servlet interface { void init(ServletConfig sc) throws ServletException; void service(ServletRequest req,ServletResponse res) throws ServletException,IOException; void destroy(); }
  • 43.
    2 December 202143 Methods of Servlet Method Description void init( ServletConfig config ) The servlet container calls this method once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet. ServletConfig getServletConfig( ) This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes). String getServletInfo() This method is defined by a servlet programmer to return a string containing servlet information such as the servlet’s author and version. void service( ServletRequest request, ServletResponse response ) The servlet container calls this method to respond to a client request to the servlet. void destroy() This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection, should be deallocated here.
  • 44.
    2 December 202144 Http Servlet • Override the servlet class • There are two types of request- Get and Post - doGet responds to Get request -doPost responds to Post request • It has HttpServletRequest and HttpServletResponse Objects
  • 45.
    2 December 202145 (Contd..) Method Description doDelete Called in response to an HTTP delete request. Such a request is normally used to delete a file from a server. This may not be available on some servers, because of its inherent security risks (e.g., the client could delete a file that is critical to the execution of the server or an application). doHead Called in response to an HTTP head request. Such a request is normally used when the client only wants the headers of a response, such as the content type and content length of the response. doOptions Called in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the version of HTTP (1.0 or 1.1) and the request methods the server supports. doPut Called in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers, because of its inherent security risks (e.g., the client could place an executable application on the server, which, if executed, could damage the server—perhaps by deleting critical files or occupying resources). doTrace Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically returns an HTML document to the client containing the request header information (data sent by the browser as part of the request).
  • 46.
    2 December 202146 HttpServletRequest Interface • Web server - creates an HttpServletRequest object. - passes it to the servlet’s service method. • HttpServletRequest object contains the request from the client.
  • 47.
    2 December 202147 (Contd..) Method Description String getParameter( String name ) Obtains the value ofa parameter sent to the servlet as part ofa get or post request. The name argument represents the parameter name. Enumeration getParameterNames() Returns the names ofallthe parameters sent to the servlet as part ofa post request. String[] getParameterValues( String name ) For a parameter with multiple values, this method returns anarrayofstrings containing the values for a specified servlet parameter. Cookie[] getCookies() Returns anarrayof Cookie objects stored onthe client bythe server. Cookie objects canbe used to uniquely identifyclients to the servlet. HttpSession getSession( booleancreate ) Returns an HttpSession object associated withthe client’s current browsing session. This method cancreate an HttpSession object (true argument) ifone does not alreadyexist for the client. HttpSession objects are used insimilar ways to Cookies for uniquely identifying clients.
  • 48.
    2 December 202148 HttpServletResponse Interface Method Description void addCookie( Cookie cookie ) Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and whether Cookies are enabled on the client determine if Cookies are stored on the client. ServletOutputStream getOutputStream() Obtains a byte-based output stream for sending binary data to the client. PrintWriter getWriter() Obtains a character-based output stream for sending text data to the client. void setContentType( String type ) Specifies the MIME type of the response to the browser. The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page. • Web server - creates an HttpServletResponse object. - passes it to the servlet’s service method.
  • 49.
    2 December 202149 Handling client request : Http request header General: getHeader, getHeaders, getHeaderNames. Specialized: getCookies, getAuthType, getRemoteUser, getContentLength, getContentType, getDateHeader, getIntHeader Related Info: getMethod, getRequestURI, getProtocol
  • 50.
    2 December 202150 (Contd..)
  • 51.
    2 December 202151 Common HTTP Request Header 1.1 • Accept - MIME Types of browser can handle. - Can send different content to different clients. • Accept-Encoding - Indicate encoding (e.g gzip) browser can handle. • Authorization - User identification for password protected pages. • Connection - In Http 1.1, keep alive means browser can handle persistent connection. Persistent connection is default. Persistent means same socket is reused for same type of client request.
  • 52.
    2 December 202152 (Contd..) • Cookie - Give cookies previously sent to client. • Host - It gives host given in original URL. • If-Modified-Since - Client wants pages, only after changed on some specified dates. • Referrer - URL of referring web page. - Useful for tracking traffic; logged by many servers. • User Agent - String identifying the browser making request.
  • 53.
    2 December 202153 Generating server response: http status code Purpose: The variety of status code that are essentially indicate failure. e.g.:- HTTP/1.1 200 OK • Changing a status code perform a lot of tasks. - Forward client to another page. - Indicate a missing resource. - Instruct a browser to use cached copy. • Set status before sending document. public void setStatus (int statusCode) - use constant for the code. Not an explicit int. constants are HttpServletResponse. - Names derived from standard message. e.g SC_OK, SC_NOT_FOUND so on. • public sendError(int code, String msg) - Wraps the message inside HTML document.
  • 54.
    2 December 202154 (Contd..) • Public void sendRedirect(String url) - Relative url is permitted in 2.2/2.3 - Also sets location header. Common HTTP 1.1 Status codes: • 200(OK) - Everything is fine, document follows, default for servlets. • 204(No content) - Browser should keep displaying previous document. • 301(Moved document) - Requested document moved elsewhere. - Browsers go to new location automatically.
  • 55.
    2 December 202155 (Contd..) • 401(unauthorized) Browser tried to access protected page without proper authorization header. • 404(Not found) No such page. In general 100-199 -> codes in the 100s are informational, indicating that the client should respond with some other action. 200-299 -> values in the 200’s signify that the request was successful. 300-399 -> values in the 300’s are used for files that have moved and usually include location header indicating the new address.
  • 56.
    2 December 202156 (Contd..) 400-499 -> values in the 400’s indicate an error by the client. 500-599 ->codes in the 500’s signify an error by the server. Common MIME Type:
  • 57.
    2 December 202157 Session Handling • A server site typically needs to maintain two types of persistent(remembered) information: - Information about the Session. - Information about the User. • Servlet capabilities: Servlets, like Applets, can be trusted or untrusted. - A servlet can use a unique ID to store and retrieve information about a given session. - User information usually requires a login ID and a password. - Since servlets don’t quit between requests, any servlet can maintain information in its internal data structures, as long as the server keeps running.
  • 58.
    2 December 202158 (Contd..) - A trusted servlet can read and write files on the server, hence can maintain information about sessions and users even when the server is stopped and restarted. - An untrusted servlet will lose all information when the servlet or server stops for any reason. This is sometimes good enough for session information. This is almost never good enough for user information. - HTTP is stateless: When it gets a page request, it has no memory of any previous requests from the same client.
  • 59.
    2 December 202159 (Contd..) • Session tracking is keeping track of what has gone before in this particular conversation. - Since HTTP is stateless, it does not do this for you. - You have to do it yourself, in your servlets. - This makes it difficult to hold a “conversation”. Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests. - The server must be able to keep track of multiple conversations with multiple users.
  • 60.
    2 December 202160 • Cookies are small files that the servlet can store on the client computer, and retrieve later. • URL rewriting: You can append a unique ID after the URL to identify the user. • Hidden <form> fields can be used to store a unique ID. • Java’s Session Tracking API can be used to do most of the work for you. Session tracking solution
  • 61.
    2 December 202161 Cookies • Cookies are small bits of textual information that a web server sends to the browser and that the browser returns unchanged when later visiting the same website or domain. • Cookies are not a security threat. • Cookies can be a privacy threat. - Cookies can be used to customize advertisements. - Outlook Express allows cookies to be embedded in email. - A servlet can read your cookies. Incompetent companies might keep your credit card info in a cookie. Netscape lets you refuse cookies to sites other than that to which you connected.
  • 62.
    2 December 202162 Why do we need cookies? • Cookies are a very useful tool in maintaining state (persistence) on the Web. Unless something special is done, web servers are only aware of users when a transaction -- sending or receiving information -- is in process. The moment the transaction is complete the server forgets about the user and makes no attempt to correlate subsequent transactions with previous exchanges. • Since the web protocol, HTTP, is a "stateless" (non-persistent) protocol, it is impossible to differentiate between visits to a given web site, unless the server can somehow "mark" a visitor. • This is done by storing a piece of information in the visitor's browser, called a "cookie". Cookies can contain database information, custom page settings, or just about anything that would make a site customizable.
  • 63.
    2 December 202163 Using cookies • import javax.servlet.http.*; • Constructor: Cookie(String name, String value) • Assuming request is an HttpServletRequest and response is an HttpServletResponse, response.addCookie(cookie); Cookie[ ] cookies = request.getCookies(); String name = cookies[i].getName(); String value = cookies[i].getValue(); • There are, of course, many more methods in the HttpServletRequest, HttpServletResponse, and Cookie classes in the javax.servlet.http package.
  • 64.
    2 December 202164 (Contd..) • public void setComment(String purpose) - public String getComment() • public void setMaxAge(int expiry) - public int getMaxAge() - Max age in seconds after which cookie will expire. - If expiry is negative, delete when browser exits. - If expiry is zero, delete cookie immediately. • setSecure(boolean flag) - public boolean get Secure() - Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.
  • 65.
    2 December 202165 (Contd..) Here is the code snippet for initializing a cookie and adding the same to the response object. ..... Cookie cookie = new Cookie ("otncookiename",userName); cookie.setMaxAge(86400); response.addCookie(cookie); Cookie onemorecookie = new Cookie("otncookiepassword",password); onemorecookie.setMaxAge(86400); response.addCookie (onemorecookie); ..... Setting cookies:
  • 66.
    2 December 202166 (Contd..) Retrieving a cookie value: Here is the code snippet for selecting cookie values from the request object. ...... Cookie[] cookieArray = request.getCookies(); if( cookieArray != null) { for( int i = cookieArray.length-1; i >= 0; i-- ) { Cookie cookie = cookieArray[i]; System.out.println ("Cookie name is " + cookie.getName()); System.out.println ("Cookie value is " + cookie.getValue()); } } ......
  • 67.
    2 December 202167 (Contd..) Code snippet: Login.html <form name="login" method="post" action="./LoginCookieServlet"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> LoginCookieServlet String name= request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); Cookie userNameCookie = new Cookie("USERNAME", name); response.addCookie(userNameCookie); Cookie passwordCookie = new Cookie("PASSWORD",pwd); response.addCookie(passwordCookie); request.getRequestDispatcher("/LoginNextCookie").forward(request, response);
  • 68.
    2 December 202168 (Contd..) Code snippet: LoginNextCookie Cookie[] cookies = request.getCookies(); pw.println("cookies[0].getValue()"+cookies[0].getValue()); pw.println("cookies[1].getValue()"+cookies[1].getValue()); for(Cookie cookie: cookies) { pw.println(cookie.getValue()); }
  • 69.
    2 December 202169 Limitation • The browser should be enabled to accept cookies. • Cookie values must never have spaces, commas or semicolons. • Cookies can store upto 4KB of value.
  • 70.
    2 December 202170 URL-Rewritting • URL rewriting is another way to support anonymous session tracking. • With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information. • The extra information can be in the form of extra path information, added parameters, or some custom, server-specific URL change. • Due to the limited space available in rewriting a URL, the extra information is usually limited to a unique session ID.
  • 71.
    2 December 202171 URL-Rewritting • For example, the following URLs have been rewritten to pass the session ID 123: http://server: port/servlet/Rewritten original http://server:port/servlet/Rewritten/123 extra path information http://server:port/servlet/Rewritten?sessionid=123 added parameter http://server:port/servlet/Rewritten;$sessionid$123 custom change
  • 72.
    2 December 202172 URL-Rewritting • code snippet Loginurlrewriting.html <form name="login" method="post" action="./URLRewriting"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> URLRewriting.java response.getWriter().append("Served at: ").append(request.getContextPath()); String name= request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); request.getRequestDispatcher("/LoginUrlReceive?uname="+name+"&&pwd="+pwd).forward(request , response);
  • 73.
    2 December 202173 URL-Rewritting • code snippet LoginUrlReceive.java String username = request.getParameter("uname"); String password = request.getParameter("pwd"); pw.println("LoginUrlReceive username::"+username+"password::"+password);
  • 74.
    2 December 202174 Hidden form fields • One way to support anonymous session tracking is to use hidden form fields. As the name implies, these are fields added to an HTML form that are not displayed in the client's browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this: • <FORM ACTION="/servlet/MovieFinder" METHOD="POST"> ... <INPUT TYPE=hidden NAME="zip" VALUE="94040"> <INPUT TYPE=hidden NAME="level" VALUE="expert"> .. </FORM> In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.
  • 75.
    2 December 202175 Hidden form fields • code snippet Loginhidform.html <form name="login" method="post" action="./HiddenServlet"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> HiddenServlet.java String name = request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); out.print("<form action='./LoginUrlReceive'>"); out.print("<input type='hidden' name='uname' value='" + name + "'>"); out.print("<input type='hidden' name='pwd' value='" + pwd + "'>"); out.print("<input type='submit' value='go'>"); out.print("</form>");
  • 76.
    2 December 202176 Hidden form fields • code snippet LoginUrlReceive.java String username = request.getParameter("uname"); String password = request.getParameter("pwd"); pw.println("LoginUrlReceive username::"+username+"password::"+password);
  • 77.
    2 December 202177 Session tracking API • The session tracking API is in javax.servlet.http.HttpSession and is built on top of cookies. • To use the session tracking API: - Create a session: HttpSession session = request.getSession(); Returns the session associated with this request If there was no associated session, one is created. - Store information in the session and retrieve it as needed: session.setAttribute (name, value); Object obj = getAttribute(name); • Session information is automatically maintained across requests.
  • 78.
    2 December 202178 Looking up information associated with session • getId - This method returns the unique identifier generated for each session. It is sometimes used as the key name when there is only a single value associated with a session, or when logging information about previous sessions. • isNew - This returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions.
  • 79.
    2 December 202179 • getCreationTime - This returns the time, in milliseconds since the epoch, at which the session was made. To get a value useful for printing out, pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar. • getLastAccessedTime - This returns the time, in milliseconds since the epoch, at which the session was last sent from the client. • getMaxInactiveInterval - This returns the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never timeout. (Contd..)
  • 80.
    2 December 202180 • Public Object getValue(String name) • Public Object getAttribute (String name) • Public Object setValue(String name, Object value) • Public Object setAttribute (String name, Object value) • Public Object removeValue(String name) • Public Object removeAttribute(String name) (Contd..)
  • 81.
    2 December 202181 Code snippet Loginsession.html <form name="login" method="post" action="./AdminServletSession"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> AdminServletSession.java HttpSession session = request.getSession(true); String reqUsername = request.getParameter("txtUserName"); String reqPassword = request.getParameter("txtPassword"); out.println("AdminServletSession::"+"username::"+reqUsername+ "password ::"+reqPassword); session.setAttribute("USERNAME", reqUsername); session.setAttribute("PASSWORD", reqPassword); request.getRequestDispatcher("./HRServletSession").forward(request, response); (Contd..)
  • 82.
    2 December 202182 Code snippet Loginsession.html < HttpSession session = request.getSession(true); String sessionUsername =(String) session.getAttribute("USERNAME"); String sessionPassword = (String) session.getAttribute("PASSWORD"); out.println("HRServletSession::"+"username::"+sessionUsername+ "password ::"+sessionPassword); (Contd..)