Summary

These notes provide an overview of servlets, web applications, and CGI. It details the life cycle of a servlet and discusses the advantages of using servlets over CGI. The notes also cover web terminology and different types of websites.

Full Transcript

Servlet: Web Application Basics. Architecture and challenges of Web Application.Introduction to servlet life cycle Developing and Deploying Servlets Exploring Deployment Descriptor (web.xml). Handling Request and Response Initializing a Servlet Accessing Database Servlet Chaining Session Tracking &...

Servlet: Web Application Basics. Architecture and challenges of Web Application.Introduction to servlet life cycle Developing and Deploying Servlets Exploring Deployment Descriptor (web.xml). Handling Request and Response Initializing a Servlet Accessing Database Servlet Chaining Session Tracking & Management Dealing with cookies Transferring Request Accessing Web Context Passing INIT and CONTEXT Parameter Sharing information using scope object Controlling concurrent access User Authentication Filtering Request and Response Programming Filter Filter Mapping Servlet Listeners. Servlets Servlet technology is used to create a web application (resides at server side and generates a dynamic web page). Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language. However, there were many disadvantages to this technology. We have discussed these disadvantages below. There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc. What is a Servlet? Servlet can be described in many ways, depending on the context. o Servlet is a technology which is used to create a web application. o Servlet is an API that provides many interfaces and classes including documentation. o Servlet is an interface that must be implemented for creating any Servlet. o Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests. o Servlet is a web component that is deployed on the server to create a dynamic web page. What is a web application? A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server and respond to the HTTP request. CGI (Common Gateway Interface) CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process. Disadvantages of CGI There are many problems in CGI technology: 1. If the number of clients increases, it takes more time for sending the response. 2. For each request, it starts a process, and the web server is limited to start processes. 3. It uses platform dependent language e.g. C, C++, perl. Advantages of Servlet There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The advantages of Servlet are as follows: 1. Better performance: because it creates a thread for each request, not process. 2. Portability: because it uses Java language. 3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc. 4. Secure: because it uses java language. Web Terminology Servlet Description Terminology Website: static vs It is a collection of related web pages that may contain text, images, audio and dynamic video. HTTP It is the data communication protocol used to establish communication between client and server. HTTP Requests It is the request send by the computer to a web server that contains all sorts of potentially interesting information. Get vs Post It gives the difference between GET and POST request. Container It is used in java for dynamically generating the web pages on the server side. Server: Web vs It is used to manage the network resources and for running the program or Application software that provides services. Content Type It is HTTP header that provides the description about what are you sending to the browser. Website Website is a collection of related web pages that may contain text, images, audio and video. The first page of a website is called home page. Each website has specific internet address (URL) that you need to enter in your browser to access a website. Website is hosted on one or more servers and can be accessed by visiting its homepage using a computer network. A website is managed by its owner that can be an individual, company or an organization. A website can be of two types: o Static Website o Dynamic Website Static website Static website is the basic type of website that is easy to create. You don't need the knowledge of web programming and database design to create a static website. Its web pages are coded in HTML. The codes are fixed for each page so the information contained in the page does not change and it looks like a printed page. Dynamic website Dynamic website is a collection of dynamic web pages whose content changes dynamically. It accesses content from a database or Content Management System (CMS). Therefore, when you alter or update the content of the database, the content of the website is also altered or updated. Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic content. Client side scripting generates content at the client computer on the basis of user input. The web browser downloads the web page from the server and processes the code within the page to render information to the user. In server side scripting, the software runs on the server and processing is completed in the server then plain pages are sent to the user. Static vs Dynamic website Static Website Dynamic Website Prebuilt content is same every time the page is Content is generated quickly and changes regularly. loaded. It uses the HTML code for developing a It uses the server side languages such website. as PHP,SERVLET, JSP, and ASP.NET etc. for developing a website. It sends exactly the same response for every It may generate different HTML for each of the request. request. The content is only changed when someone The page contains "server-side" code which allows publishes and updates the file (sends it to the the server to generate the unique content when the web server). page is loaded. Flexibility is the main advantage of static Content Management System (CMS) is the main website. advantage of dynamic website. HTTP (Hyper Text Transfer Protocol) The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative, distributed, hypermedia information systems. It is the data communication protocol used to establish communication between client and server. HTTP is TCP/IP based communication protocol, which is used to deliver the data like image files, query results, HTML files etc on the World Wide Web (WWW) with the default port is TCP 80. It provides the standardized way for computers to communicate with each other. The Basic Characteristics of HTTP (Hyper Text Transfer Protocol): o It is the protocol that allows web servers and browsers to exchange data over the web. o It is a request response protocol. o It uses the reliable TCP connections by default on TCP port 80. o It is stateless means each request is considered as the new request. In other words, server doesn't recognize the user by default. The Basic Features of HTTP (Hyper Text Transfer Protocol): There are three fundamental features that make the HTTP a simple and powerful protocol used for communication: o HTTP is media independent: It specifies that any type of media content can be sent by HTTP as long as both the server and the client can handle the data content. o HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a browser initiates the HTTP request and after the request is sent the client disconnects from server and waits for the response. o HTTP is stateless: The client and server are aware of each other during a current request only. Afterwards, both of them forget each other. Due to the stateless nature of protocol, neither the client nor the server can retain the information about different request across the web pages. The Basic Architecture of HTTP (Hyper Text Transfer Protocol): The below diagram represents the basic architecture of web application and depicts where HTTP stands: HTTP is request/response protocol which is based on client/server based architecture. In this protocol, web browser, search engines, etc. behave as HTTP clients and the Web server like Servlet behaves as a server HTTP Requests The request sent by the computer to a web server, contains all sorts of potentially interesting information; it is known as HTTP requests. The HTTP client sends the request to the server in the form of request message which includes following information: o The Request-line o The analysis of source IP address, proxy and port o The analysis of destination IP address, protocol, port and host o The Requested URI (Uniform Resource Identifier) o The Request method and Content o The User-Agent header o The Connection control header o The Cache control header The HTTP request method indicates the method to be performed on the resource identified by the Requested URI (Uniform Resource Identifier). This method is case-sensitive and should be used in uppercase. The HTTP request methods are: HTTP Description Request GET Asks to get the resource at the requested URL. POST Asks the server to accept the body info attached. It is like GET request with extra info sent with the request. HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no body. TRACE Asks for the loopback of the request message, for testing or troubleshooting. PUT Says to put the enclosed info (the body) at the requested URL. DELETE Says to delete the resource at the requested URL. OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond Get vs. Post There are many differences between the Get and Post request. Let's see these differences: GET POST 1) In case of Get request, only limited amount of In case of post request, large amount of data can be sent because data is sent in header. data can be sent because data is sent in body. 2) Get request is not secured because data is exposed Post request is secured because data is not in URL bar. exposed in URL bar. 3) Get request can be bookmarked. Post request cannot be bookmarked. 4) Get request is idempotent. It means second Post request is non-idempotent. request will be ignored until response of first request is delivered 5) Get request is more efficient and used more than Post request is less efficient and used less Post. than get. GET and POST Two common methods for the request-response between a server and client are: o GET- It requests the data from a specified resource o POST- It submits the processed data to a specified resource Anatomy of Get Request The query string (name/value pairs) is sent inside the URL of a GET request: 1. GET/RegisterDao.jsp?name1=value1&name2=value2 As we know that data is sent in request header in case of get request. It is the default request type. Let's see what information is sent to the server. Some other features of GET requests are: o It remains in the browser history o It can be bookmarked o It can be cached o It have length restrictions o It should never be used when dealing with sensitive data o It should only be used for retrieving the data Anatomy of Post Request The query string (name/value pairs) is sent in HTTP message body for a POST request: 1. POST/RegisterDao.jsp HTTP/1.1 2. Host: www. javatpoint.com 3. name1=value1&name2=value2 As we know, in case of post request original data is sent in message body. Let's see how information is passed to the server in case of post request. Some other features of POST requests are: o This requests cannot be bookmarked o This requests have no restrictions on length of data o This requests are never cached o This requests do not retain in the browser history o Servlet Container o It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a static WebPages from the server. If the user wants to read the web pages as per input then the servlet container is used in java. o The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: o o Servlet Container States o The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: o Standalone: It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself o In-process: It is separated from the web server, because a different program runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss. o Out-of-process: The web server and servlet container are different programs which are run in a different process. For performing the communications between them, web server uses the plug-in provided by the servlet container. The Servlet Container performs many operations that are given below: o Life Cycle Management o Multithreaded support o Object Pooling o Security etc. Server: Web vs. Application Server is a device or a computer program that accepts and responds to the request made by other program, known as client. It is used to manage the network resources and for running the program or software that provides services. There are two types of servers: 1. Web Server 2. Application Server Web Server Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It can't be used for EJB. It is a computer where the web content can be stored. In general web server can be used to host the web sites but there also used some other web servers also such as FTP, email, storage, gaming etc. Examples of Web Servers are: Apache Tomcat and Resin. Web Server Working It can respond to the client request in either of the following two possible ways: o Generating response by using the script and communicating with database. o Sending file to the client associated with the requested URL. The block diagram representation of Web Server is shown below: Important points o If the requested web page at the client side is not found, then web server will sends the HTTP response: Error 404 Not found. o When the web server searching the requested page if requested page is found then it will send to the client with an HTTP response. o If the client requests some other resources then web server will contact to application server and data is store for constructing the HTTP response. Application Server Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a server centric architecture. It provides the middleware services for state maintenance and security, along with persistence and data access. It is a type of server designed to install, operate and host associated services and applications for the IT services, end users and organizations. The block diagram representation of Application Server is shown below: The Example of Application Servers are: 1. JBoss: Open-source server from JBoss community. 2. Glassfish: Provided by Sun Microsystem. Now acquired by Oracle. 3. Weblogic: Provided by Oracle. It more secured. 4. Websphere: Provided by IBM. Content Type Content Type is also known as MIME (Multipurpose internet Mail Extension)Type. It is a HTTP header that provides the description about what are you sending to the browser. MIME is an internet standard that is used for extending the limited capabilities of email by allowing the insertion of sounds, images and text in a message. The features provided by MIME to the email services are as given below: o It supports the non-ASCII characters o It supports the multiple attachments in a single message o It supports the attachment which contains executable audio, images and video files etc. o It supports the unlimited message length. List of Content Types There are many content types. The commonly used content types are given below: o text/html o text/plain o application/msword o application/vnd.ms-excel o application/jar o application/pdf o application/octet-stream o application/x-zip o images/jpeg o images/png o images/gif o audio/mp3 o video/mp4 o video/quicktime etc. Servlet API The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol. The javax.servlet.http package contains interfaces and classes that are responsible for http requests only. Let's see what are the interfaces of javax.servlet package. Interfaces in javax.servlet package There are many interfaces in javax.servlet package. They are as follows: 1. Servlet 2. ServletRequest 3. ServletResponse 4. RequestDispatcher 5. ServletConfig 6. ServletContext 7. SingleThreadModel 8. Filter 9. FilterConfig 10. FilterChain 11. ServletRequestListener 12. ServletRequestAttributeListener 13. ServletContextListener 14. ServletContextAttributeListener Classes in javax.servlet package There are many classes in javax.servlet package. They are as follows: 1. GenericServlet 2. ServletInputStream 3. ServletOutputStream 4. ServletRequestWrapper 5. ServletResponseWrapper 6. ServletRequestEvent 7. ServletContextEvent 8. ServletRequestAttributeEvent 9. ServletContextAttributeEvent 10. ServletException 11. UnavailableException Interfaces in javax.servlet.http package There are many interfaces in javax.servlet.http package. They are as follows: 1. HttpServletRequest 2. HttpServletResponse 3. HttpSession 4. HttpSessionListener 5. HttpSessionAttributeListener 6. HttpSessionBindingListener 7. HttpSessionActivationListener 8. HttpSessionContext (deprecated now) Classes in javax.servlet.http package There are many classes in javax.servlet.http package. They are as follows: 1. HttpServlet 2. Cookie 3. HttpServletRequestWrapper 4. HttpServletResponseWrapper 5. HttpSessionEvent 6. HttpSessionBindingEvent 7. HttpUtils (deprecated now) Servlet Interface Servlet interface provides commonbehaviorto all the servlets.Servlet interface defines methods that all servlets must implement. Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods. Methods of Servlet interface There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container. Method Description public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. public void service(ServletRequest provides response for the incoming request. It is request,ServletResponse response) invoked at each request by the web container. public void destroy() is invoked only once and indicates that servlet is being destroyed. public ServletConfig getServletConfig() returns the object of ServletConfig. public String getServletInfo() returns information about servlet such as writer, copyright, version etc. Servlet Example by implementing Servlet interface Let's see the simple example of servlet by implementing the servlet interface. File: First.java 1. import java.io.*; 2. import javax.servlet.*; 3. 4. public class First implements Servlet{ 5. ServletConfig config=null; 6. 7. public void init(ServletConfig config){ 8. this.config=config; 9. System.out.println("servlet is initialized"); 10. } 11. 12. public void service(ServletRequest req,ServletResponse res) 13. throws IOException,ServletException{ 14. 15. res.setContentType("text/html"); 16. 17. PrintWriter out=res.getWriter(); 18. out.print(""); 19. out.print("hello simple servlet"); 20. out.print(""); 21. 22. } 23. public void destroy(){System.out.println("servlet is destroyed");} 24. public ServletConfig getServletConfig(){return config;} 25. public String getServletInfo(){return "copyright 2007-1010";} 26. 27. } GenericServlet class GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementation of all the methods of these interfaces except the service method. GenericServlet class can handle any type of request so it is protocol-independent. You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method. Methods of GenericServlet class There are many methods in GenericServlet class. They are as follows: 1. public void init(ServletConfig config) is used to initialize the servlet. 2. public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet. 3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed. 4. public ServletConfig getServletConfig() returns the object of ServletConfig. 5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc. 6. public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config) 7. public ServletContext getServletContext() returns the object of ServletContext. 8. public String getInitParameter(String name) returns the parameter value for the given parameter name. 9. public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file. 10. public String getServletName() returns the name of the servlet object. 11. public void log(String msg) writes the given message in the servlet log file. 12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack trace. Servlet Example by inheriting the GenericServlet class Let's see the simple example of servlet by inheriting the GenericServlet class. File: First.java 1. import java.io.*; 2. import javax.servlet.*; 3. 4. public class First extends GenericServlet{ 5. public void service(ServletRequest req,ServletResponse res) 6. throws IOException,ServletException{ 7. 8. res.setContentType("text/html"); 9. 10. PrintWriter out=res.getWriter(); 11. out.print(""); 12. out.print("hello generic servlet"); 13. out.print(""); 14. 15. } 16. } HttpServlet class The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc. Methods of HttpServlet class There are many methods in HttpServlet class. They are as follows: 1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type. 2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type. 3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container. 4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container. 5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container. 6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container. 7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by the web container. 8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is invoked by the web container. 9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is invoked by the web container. 10. protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was last modified since midnight January 1, 1970 GMT. Life Cycle of a Servlet (Servlet Life Cycle) The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet: 1. Servlet class is loaded. 2. Servlet instance is created. 3. init method is invoked. 4. service method is invoked. 5. destroy method is invoked. As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state. 1) Servlet class is loaded The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2) Servlet instance is created The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below: 1. public void init(ServletConfig config) throws ServletException 4) service method is invoked The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below: 1. public void service(ServletRequest request, ServletResponse response) 2. throws ServletException, IOException 5) destroy method is invoked The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below: 1. public void destroy() Steps to create a servlet example There are given 6 steps to create a servlet example. These steps are required for all the servers. The servlet example can be created by three ways: 1. By implementing Servlet interface, 2. By inheriting GenericServlet class, (or) 3. By inheriting HttpServlet class The mostly used approach is by extending HttpServlet because it provides http request specific method such as doGet(), doPost(), doHead() etc. Here, we are going to use apache tomcat server in this example. The steps are as follows: 1. Create a directory structure 2. Create a Servlet 3. Compile the Servlet 4. Create a deployment descriptor 5. Start the server and deploy the project 6. Access the servlet download this example of servlet download example of servlet by extending GenericServlet download example of servlet by implementing Servlet interface 1)Create a directory structures The directory structure defines that where to put the different types of files so that web container may get the information and respond to the client. The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the directory structure that must be followed to create the servlet. As you can see that the servlet class file must be in the classes folder. The web.xml file must be under the WEB-INF folder. 2)Create a Servlet There are three ways to create the servlet. 1. By implementing the Servlet interface 2. By inheriting the GenericServlet class 3. By inheriting the HttpServlet class The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such as doGet(), doPost, doHead() etc. In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the default request. DemoServlet.java 1. import javax.servlet.http.*; 2. import javax.servlet.*; 3. import java.io.*; 4. public class DemoServlet extends HttpServlet{ 5. public void doGet(HttpServletRequest req,HttpServletResponse res) 6. throws ServletException,IOException 7. { 8. res.setContentType("text/html");//setting the content type 9. PrintWriter pw=res.getWriter();//get the stream to write the data 10. 11. //writing html in the stream 12. pw.println(""); 13. pw.println("Welcome to servlet"); 14. pw.println(""); 15. 16. pw.close();//closing the stream 17. }} 3)Compile the servlet For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files: Jar file Server 1) servlet-api.jar Apache Tomcat 2) weblogic.jar Weblogic 3) javaee.jar Glassfish 4) javaee.jar JBoss Two ways to load the jar file 1. set classpath 2. paste the jar file in JRE/lib/ext folder Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB- INF/classes directory. 4)Create the deployment descriptor (web.xml file) The deployment descriptor is an xml file, from which Web Container gets the information about the servet to be invoked. The web container uses the Parser to get the information from the web.xml file. There are many xml parsers such as SAX, DOM and Pull. There are many elements in the web.xml file. Here is given some necessary elements to run the simple servlet program. web.xml file 1. 2. 3. 4. sonoojaiswal 5. DemoServlet 6. 7. 8. 9. sonoojaiswal 10. /welcome 11. 12. 13. Description of the elements of web.xml file There are too many elements in the web.xml file. Here is the illustration of some elements that is used in the above web.xml file. The elements are as follows: represents the whole application. is sub element of and represents the servlet. is sub element of represents the name of the servlet. is sub element of represents the class of the servlet. is sub element of. It is used to map the servlet. is sub element of. This pattern is used at client side to invoke the servlet. 5)Start the Server and deploy the project To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory. One Time Configuration for Apache Tomcat Server You need to perform 2 tasks: 1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server). 2. Change the port number of tomcat (optional). It is required if another server is running on same port (8080). 1) How to set JAVA_HOME in environment variable? To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables. Go to My Computer properties -> Click on advanced tab then environment variables -> Click on the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable value -> ok -> ok -> ok. Go to My Computer properties: Click on advanced system settings tab then environment variables: Click on the new tab of user variable or system variable: Write JAVA_HOME in variable name and paste the path of jdk folder in variable value: There must not be semicolon (;) at the end of the path. After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin. Note: There are two types of tomcat available: 1. Apache tomcat that needs to extract only (no need to install) 2. Apache tomcat that needs to install It is the example of apache tomcat that needs to extract only. Now server is started successfully. 2) How to change port number of apache tomcat Changing the port number is required if there is another server running on the same system with same port number.Suppose you have installed oracle, you need to change the port number of apache tomcat because both have the default port number 8080. Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory. Change the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it by 9999 and save this file. 5) How to deploy the servlet project Copy the project and paste it in the webapps folder under apache tomcat. But there are several ways to deploy the project. They are as follows: o By copying the context(project) folder into the webapps directory o By copying the war folder into the webapps directory o By selecting the folder path from the server o By selecting the war file from the server Here, we are using the first approach. You can also create war file, and paste it inside the webapps directory. To do so, you need to use jar tool to create the war file. Go inside the project directory (before the WEB-INF), then write: 1. projectfolder> jar cvf myproject.war * Creating war file has an advantage that moving the project from one location to another takes less time. 6) How to access the servlet Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For example: 1. http://localhost:9999/demo/welcome download this example of servlet (using notepad) download example of servlet by extending GenericServlet download example of servlet by implementing Servlet interface How Servlet works? It is important to learn how servlet works for understanding the servlet well. Here, we are going to get the internal detail about the first servlet program. The server checks if the servlet is requested for the first time. If yes, web container does the following tasks: o loads the servlet class. o instantiates the servlet class. o calls the init method passing the ServletConfig object else o calls the service method passing request and response objects The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project. How web container handles the servlet request? The web container is responsible to handle the request. Let's see how it handles the request. o maps the request with the servlet in the web.xml file. o creates request and response objects for this request o calls the service method on the thread o The public service method internally calls the protected service method o The protected service method calls the doGet method depending on the type of request. o The doGet method generates the response and it is passed to the client. o After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation. What is written inside the public service method? The public service method converts the ServletRequest object into the HttpServletRequest type and ServletResponse object into the HttpServletResponse type. Then, calls the service method passing these objects. Let's see the internal code: 1. public void service(ServletRequest req, ServletResponse res) 2. throws ServletException, IOException 3. { 4. HttpServletRequest request; 5. HttpServletResponse response; 6. try 7. { 8. request = (HttpServletRequest)req; 9. response = (HttpServletResponse)res; 10. } 11. catch(ClassCastException e) 12. { 13. throw new ServletException("non-HTTP request or response"); 14. } 15. service(request, response); 16. } What is written inside the protected service method? The protected service method checks the type of request, if request type is get, it calls doGet method, if request type is post, it calls doPost method, so on. Let's see the internal code: 1. protected void service(HttpServletRequest req, HttpServletResponse resp) 2. throws ServletException, IOException 3. { 4. String method = req.getMethod(); 5. if(method.equals("GET")) 6. { 7. long lastModified = getLastModified(req); 8. if(lastModified == -1L) 9. { 10. doGet(req, resp); 11. } 12..... 13. //rest of the code 14. } 15. } War File A war (web archive) File contains files of a web project. It may have servlet, xml, jsp, image, html, css, js etc. files. Here, we will discuss what is war file, how to create war file, how to deploy war file and how to extract war file. What is war file? web archive (war) file contains all the contents of a web application. It reduces the time duration for transferring file. Advantage of war file saves time: The war file combines all the files into a single unit. So it takes less time while transferring file from client to server. How to create war file? To create war file, you need to use jar tool of JDK. You need to use -c switch of jar, to create the war file. Go inside the project directory of your project (outside the WEB-INF), then write the following command: 1. jar -cvf projectname.war * Here, -c is used to create file, -v to generate the verbose output and -f to specify the arhive file name. The * (asterisk) symbol signifies that all the files of this directory (including sub directory). How to deploy the war file? There are two ways to deploy the war file. 1. By server console panel 2. By manually having the war file in specific folder of server. If you want to deploy the war file in apache tomcat server manually, go to the webapps directory of apache tomcat and paste the war file here. Now, you are able to access the web project through browser. How to extract war file manually? To extract the war file, you need to use -x switch of jar tool of JDK. Let's see the command to extract the war file. 1. jar -xvf projectname.war welcome-file-list in web.xml The welcome-file-list element of web-app, is used to define a list of welcome files. Its sub element is welcome-file that is used to define the welcome file. A welcome file is the file that is invoked automatically by the server, if you don't specify any file name. By default server looks for the welcome file in following order: 1. welcome-file-list in web.xml 2. index.html 3. index.htm 4. index.jsp If none of these files are found, server renders 404 error. If you have specified welcome-file in web.xml, and all the files index.html, index.htm and index.jsp exists, priority goes to welcome-file. If welcome-file-list entry doesn't exist in web.xml file, priority goes to index.html file then index.htm and at last index.jsp file. Let's see the web.xml file that defines the welcome files. web.xml 1. 2..... 3. 4. 5. home.html 6. default.html 7. 8. Now, home.html and default.html will be the welcome files. If you have the welcome file, you can directory invoke the project as given below: 1. http://localhost:8888/myproject As you can see, we have not specified any file name after the project. load on startup in web.xml The load-on-startup element of web-app loads the servlet at the time of deployment or server start if value is positive. It is also known as pre initialization of servlet. You can pass positive and negative value for the servlet. Advantage of load-on-startup element As you know well, servlet is loaded at first request. That means it consumes more time at first request. If you specify the load-on-startup in web.xml, servlet will be loaded at project deployment time or server start. So, it will take less time for responding to first request. Passing positive value If you pass the positive value, the lower integer value servlet will be loaded before the higher integer value servlet. In other words, container loads the servlets in ascending integer value. The 0 value will be loaded first then 1, 2, 3 and so on. Let's try to understand it by the example given below: web.xml 1. 2..... 3. 4. 5. servlet1 6. com.javatpoint.FirstServlet 7. 0 8. 9. 10. 11. servlet2 12. com.javatpoint.SecondServlet 13. 1 14. 15. 16.... 17. There are defined 2 servlets, both servlets will be loaded at the time of project deployment or server start. But, servlet1 will be loaded first then servlet2. Passing negative value If you pass the negative value, servlet will be loaded at request time, at first request. ServletRequest Interface An object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header informations, attributes etc. Methods of ServletRequest interface There are many methods defined in the ServletRequest interface. Some of them are as follows: Method Description public String getParameter(String name) is used to obtain the value of a parameter by name. public String[] returns an array of String containing all values of given getParameterValues(String name) parameter name. It is mainly used to obtain values of a Multi select list box. java.util.Enumeration returns an enumeration of all of the request parameter getParameterNames() names. public int getContentLength() Returns the size of the request entity data, or -1 if not known. public String getCharacterEncoding() Returns the character set encoding for the input of this request. public String getContentType() Returns the Internet Media Type of the request entity data, or null if not known. public ServletInputStream Returns an input stream for reading binary data in the getInputStream() throws IOException request body. public abstract String getServerName() Returns the host name of the server that received the request. public int getServerPort() Returns the port number on which this request was received. Example of ServletRequest to display the name of the user In this example, we are displaying the name of the user in the servlet. For this purpose, we have used the getParameter method that returns the value for the given request parameter name. index.html 1. 2. Enter your name 3. 4. DemoServ.java 1. import javax.servlet.http.*; 2. import javax.servlet.*; 3. import java.io.*; 4. public class DemoServ extends HttpServlet{ 5. public void doGet(HttpServletRequest req,HttpServletResponse res) 6. throws ServletException,IOException 7. { 8. res.setContentType("text/html"); 9. PrintWriter pw=res.getWriter(); 10. 11. String name=req.getParameter("name");//will return value 12. pw.println("Welcome "+name); 13. 14. pw.close(); 15. }} RequestDispatcher in Servlet The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration. There are two methods defined in the RequestDispatcher interface. Methods of RequestDispatcher interface The RequestDispatcher interface provides two methods. They are: 1. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. 2. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response. As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user. As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client. How to get the object of RequestDispatcher The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax: Syntax of getRequestDispatcher method 1. public RequestDispatcher getRequestDispatcher(String resource); Example of using getRequestDispatcher method 1. RequestDispatcher rd=request.getRequestDispatcher("servlet2"); 2. //servlet2 is the url-pattern of the second servlet 3. 4. rd.forward(request, response);//method may be include or forward Example of RequestDispatcher interface In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are cheking for hardcoded information. But you can check it to the database also that we will see in the development chapter. In this example, we have created following files: o index.html file: for getting input from the user. o Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet. o WelcomeServlet.java file: a servlet class for displaying the welcome message. o web.xml file: a deployment descriptor file that contains the information about the servlet. index.html 1. 2. Name: 3. Password: 4. 5. Login.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. 6. public class Login extends HttpServlet { 7. 8. public void doPost(HttpServletRequest request, HttpServletResponse response) 9. throws ServletException, IOException { 10. 11. response.setContentType("text/html"); 12. PrintWriter out = response.getWriter(); 13. 14. String n=request.getParameter("userName"); 15. String p=request.getParameter("userPass"); 16. 17. if(p.equals("servlet"){ 18. RequestDispatcher rd=request.getRequestDispatcher("servlet2"); 19. rd.forward(request, response); 20. } 21. else{ 22. out.print("Sorry UserName or Password Error!"); 23. RequestDispatcher rd=request.getRequestDispatcher("/index.html"); 24. rd.include(request, response); 25. 26. } 27. } 28. 29. } WelcomeServlet.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. public class WelcomeServlet extends HttpServlet { 6. 7. public void doPost(HttpServletRequest request, HttpServletResponse response) 8. throws ServletException, IOException { 9. 10. response.setContentType("text/html"); 11. PrintWriter out = response.getWriter(); 12. 13. String n=request.getParameter("userName"); 14. out.print("Welcome "+n); 15. } 16. 17. } web.xml 1. 2. 3. Login 4. Login 5. 6. 7. WelcomeServlet 8. WelcomeServlet 9. 10. 11. 12. 13. Login 14. /servlet1 15. 16. 17. WelcomeServlet 18. /servlet2 19. 20. 21. 22. index.html 23. 24. SendRedirect in servlet The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server. Difference between forward() and sendRedirect() method There are many differences between the forward() method of RequestDispatcher and sendRedirect() method of HttpServletResponse interface. They are given below: forward() method sendRedirect() method The forward() method works at server side. The sendRedirect() method works a client side. It sends the same request and response objects to another servlet. It always sends a new request. It can work within the server only. It can be used within and outside th server. Example: Example: request.getRequestDispacher("servlet2").forward(request,response); response.sendRedirect("servlet2"); Syntax of sendRedirect() method 1. public void sendRedirect(String URL)throws IOException; Example of sendRedirect() method 1. response.sendRedirect("http://www.javatpoint.com"); Full example of sendRedirect method in servlet In this example, we are redirecting the request to the google server. Notice that sendRedirect method works client side, that is why we can our request to anywhere. We can send our request within and outside the server. DemoServlet.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. public class DemoServlet extends HttpServlet{ 6. public void doGet(HttpServletRequest req,HttpServletResponse res) 7. throws ServletException,IOException 8. { 9. res.setContentType("text/html"); 10. PrintWriter pw=res.getWriter(); 11. 12. response.sendRedirect("http://www.google.com"); 13. 14. pw.close(); 15. }} Creating custom google search using sendRedirect In this example, we are using sendRedirect method to send request to google server with the request data. index.html 1. 2. 3. 4. 5. sendRedirect example 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. MySearcher.java 1. import java.io.IOException; 2. import javax.servlet.ServletException; 3. import javax.servlet.http.HttpServlet; 4. import javax.servlet.http.HttpServletRequest; 5. import javax.servlet.http.HttpServletResponse; 6. 7. public class MySearcher extends HttpServlet { 8. protected void doGet(HttpServletRequest request, HttpServletResponse response) 9. throws ServletException, IOException { 10. 11. String name=request.getParameter("name"); 12. response.sendRedirect("https://www.google.co.in/#q="+name); 13. } 14. } Output ServletConfig Interface An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file. If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time. Advantage of ServletConfig The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the web.xml file. Methods of ServletConfig interface 1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name. 2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names. 3. public String getServletName():Returns the name of the servlet. 4. public ServletContext getServletContext():Returns an object of ServletContext. How to get the object of ServletConfig 1. getServletConfig() method of Servlet interface returns the object of ServletConfig. Syntax of getServletConfig() method 1. public ServletConfig getServletConfig(); Example of getServletConfig() method 1. ServletConfig config=getServletConfig(); 2. //Now we can call the methods of ServletConfig interface Syntax to provide the initialization parameter for a servlet The init-param sub-element of servlet is used to specify the initialization parameter for a servlet. 1. 2. 3....... 4. 5. 6. parametername 7. parametervalue 8. 9....... 10. 11. Example of ServletConfig to get initialization parameter In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the servlet. DemoServlet.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. public class DemoServlet extends HttpServlet { 6. public void doGet(HttpServletRequest request, HttpServletResponse response) 7. throws ServletException, IOException { 8. 9. response.setContentType("text/html"); 10. PrintWriter out = response.getWriter(); 11. 12. ServletConfig config=getServletConfig(); 13. String driver=config.getInitParameter("driver"); 14. out.print("Driver is: "+driver); 15. 16. out.close(); 17. } 18. 19. } web.xml 1. 2. 3. 4. DemoServlet 5. DemoServlet 6. 7. 8. driver 9. sun.jdbc.odbc.JdbcOdbcDriver 10. 11. 12. 13. 14. 15. DemoServlet 16. /servlet1 17. 18. 19. Example of ServletConfig to get all the initialization parameters In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet. DemoServlet.java 1. import java.io.IOException; 2. import java.io.PrintWriter; 3. import java.util.Enumeration; 4. 5. import javax.servlet.ServletConfig; 6. import javax.servlet.ServletException; 7. import javax.servlet.http.HttpServlet; 8. import javax.servlet.http.HttpServletRequest; 9. import javax.servlet.http.HttpServletResponse; 10. 11. 12. public class DemoServlet extends HttpServlet { 13. public void doGet(HttpServletRequest request, HttpServletResponse response) 14. throws ServletException, IOException { 15. 16. response.setContentType("text/html"); 17. PrintWriter out = response.getWriter(); 18. 19. ServletConfig config=getServletConfig(); 20. Enumeration e=config.getInitParameterNames(); 21. 22. String str=""; 23. while(e.hasMoreElements()){ 24. str=e.nextElement(); 25. out.print("Name: "+str); 26. out.print(" value: "+config.getInitParameter(str)); 27. } 28. 29. out.close(); 30. } 31. 32. } web.xml 1. 2. 3. 4. DemoServlet 5. DemoServlet 6. 7. 8. username 9. system 10. 11. 12. 13. password 14. oracle 15. 16. 17. 18. 19. 20. DemoServlet 21. /servlet1 22. 23. 24. ServletContext Interface An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application. If any information is shared to many servlet, it is better to provide it from the web.xml file using the element. Advantage of ServletContext Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet. Thus it removes maintenance problem. Usage of ServletContext Interface There can be a lot of usage of ServletContext object. Some of them are as follows: 1. The object of ServletContext provides an interface between the container and servlet. 2. The ServletContext object can be used to get configuration information from the web.xml file. 3. The ServletContext object can be used to set, get or remove attribute from the web.xml file. 4. The ServletContext object can be used to provide inter-application communication. Commonly used methods of ServletContext interface There is given some commonly used methods of ServletContext interface. 1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name. 2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters. 3. public void setAttribute(String name,Object object):sets the given object in the application scope. 4. public Object getAttribute(String name):Returns the attribute for the specified name. 5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. 6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context. How to get the object of ServletContext interface 1. getServletContext() method of ServletConfig interface returns the object of ServletContext. 2. getServletContext() method of GenericServlet class returns the object of ServletContext. Syntax of getServletContext() method 1. public ServletContext getServletContext() Example of getServletContext() method 1. //We can get the ServletContext object from ServletConfig object 2. ServletContext application=getServletConfig().getServletContext(); 3. 4. //Another convenient way to get the ServletContext object 5. ServletContext application=getServletContext(); Syntax to provide the initialization parameter in Context scope The context-param element, subelement of web-app, is used to define the initialization parameter in the application scope. The param-name and param-value are the sub-elements of the context-param. The param-name element defines parameter name and and param-value defines its value. 1. 2....... 3. 4. 5. parametername 6. parametervalue 7. 8....... 9. Example of ServletContext to get the initialization parameter In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don't need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element. Let's see the simple example: DemoServlet.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. 6. public class DemoServlet extends HttpServlet{ 7. public void doGet(HttpServletRequest req,HttpServletResponse res) 8. throws ServletException,IOException 9. { 10. res.setContentType("text/html"); 11. PrintWriter pw=res.getWriter(); 12. 13. //creating ServletContext object 14. ServletContext context=getServletContext(); 15. 16. //Getting the value of the initialization parameter and printing it 17. String driverName=context.getInitParameter("dname"); 18. pw.println("driver name is="+driverName); 19. 20. pw.close(); 21. 22. }} web.xml 1. 2. 3. 4. sonoojaiswal 5. DemoServlet 6. 7. 8. 9. dname 10. sun.jdbc.odbc.JdbcOdbcDriver 11. 12. 13. 14. sonoojaiswal 15. /context 16. 17. 18. Example of ServletContext to get all the initialization parameters In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the getInitParameterNames() method in the servlet class. DemoServlet.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. public class DemoServlet extends HttpServlet{ 6. public void doGet(HttpServletRequest req,HttpServletResponse res) 7. throws ServletException,IOException 8. { 9. res.setContentType("text/html"); 10. PrintWriter out=res.getWriter(); 11. 12. ServletContext context=getServletContext(); 13. Enumeration e=context.getInitParameterNames(); 14. 15. String str=""; 16. while(e.hasMoreElements()){ 17. str=e.nextElement(); 18. out.print(" "+context.getInitParameter(str)); 19. } 20. }} web.xml 1. 2. 3. 4. sonoojaiswal 5. DemoServlet 6. 7. 8. 9. dname 10. sun.jdbc.odbc.JdbcOdbcDriver 11. 12. 13. 14. username 15. system 16. 17. 18. 19. password 20. oracle 21. 22. 23. 24. sonoojaiswal 25. /context 26. 27. 28. Attribute in Servlet An attribute in servlet is an object that can be set, get or removed from one of the following scopes: 1. request scope 2. session scope 3. application scope The servlet programmer can pass informations from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again. Attribute specific methods of ServletRequest, HttpSession and ServletContext interface There are following 4 attribute specific methods. They are as follows: 1. public void setAttribute(String name,Object object):sets the given object in the application scope. 2. public Object getAttribute(String name):Returns the attribute for the specified name. 3. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. 4. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context. Example of ServletContext to set and get attribute In this example, we are setting the attribute in the application scope and getting that value from another servlet. DemoServlet1.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. public class DemoServlet1 extends HttpServlet{ 5. public void doGet(HttpServletRequest req,HttpServletResponse res) 6. { 7. try{ 8. 9. res.setContentType("text/html"); 10. PrintWriter out=res.getWriter(); 11. 12. ServletContext context=getServletContext(); 13. context.setAttribute("company","IBM"); 14. 15. out.println("Welcome to first servlet"); 16. out.println("visit"); 17. out.close(); 18. 19. }catch(Exception e){out.println(e);} 20. 21. }} DemoServlet2.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. public class DemoServlet2 extends HttpServlet{ 5. public void doGet(HttpServletRequest req,HttpServletResponse res) 6. { 7. try{ 8. 9. res.setContentType("text/html"); 10. PrintWriter out=res.getWriter(); 11. 12. ServletContext context=getServletContext(); 13. String n=(String)context.getAttribute("company"); 14. 15. out.println("Welcome to "+n); 16. out.close(); 17. 18. }catch(Exception e){out.println(e);} 19. }} web.xml 1. 2. 3. 4. s1 5. DemoServlet1 6. 7. 8. 9. s1 10. /servlet1 11. 12. 13. 14. s2 15. DemoServlet2 16. 17. 18. 19. s2 20. /servlet2 21. 22. 23. Difference between ServletConfig and ServletContext The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole web application. Session Tracking in Servlets Session simply means a particular interval of time. Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet. Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user. HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:.4KOOPs Concepts in Java Why use Session Tracking? To recognize the user It is used to recognize the particular user. Session Tracking Techniques There are four techniques used in Session tracking: 1. Cookies 2. Hidden Form Field 3. URL Rewriting 4. HttpSession Cookies in Servlet A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. How Cookie works By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user. Types of Cookie There are 2 types of cookies in servlets. 1. Non-persistent cookie 2. Persistent cookie Non-persistent cookie It is valid for single session only. It is removed each time when user closes the browser. Persistent cookie It is valid for multiple session. It is not removed each time when user closes the browser. It is removed only if user logout or signout. Advantage of Cookies 1. Simplest technique of maintaining the state. 2. Cookies are maintained at client side. Disadvantage of Cookies 1. It will not work if cookie is disabled from the browser. 2. Only textual information can be set in Cookie object. Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work. Cookie class javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies. Constructor of Cookie class Constructor Description Cookie() constructs a cookie. Cookie(String name, String value) constructs a cookie with a specified name and value. Useful Methods of Cookie class There are given some commonly used methods of the Cookie class. Method Description public void setMaxAge(int Sets the maximum age of the cookie in seconds. expiry) public String getName() Returns the name of the cookie. The name cannot be changed after creation. public String getValue() Returns the value of the cookie. public void setName(String changes the name of the cookie. name) public void setValue(String changes the value of the cookie. value) Other methods required for using Cookies For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They are: 1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object. 2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser. How to create Cookie? Let's see the simple code to create cookie. 1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object 2. response.addCookie(ck);//adding cookie in the response How to delete Cookie? Let's see the simple code to delete cookie. It is mainly used to logout or signout the user. 1. Cookie ck=new Cookie("user","");//deleting value of cookie 2. ck.setMaxAge(0);//changing the maximum age to 0 seconds 3. response.addCookie(ck);//adding cookie in the response How to get Cookies? Let's see the simple code to get all the cookies. 1. Cookie ck[]=request.getCookies(); 2. for(int i=0;i0){ 29. out.print("Record saved successfully!"); 30. request.getRequestDispatcher("index.html").include(request, response); 31. }else{ 32. out.println("Sorry! unable to save record"); 33. } 34. 35. out.close(); 36. } 37. 38. } File: EditServlet.java 1. import java.io.IOException; 2. import java.io.PrintWriter; 3. 4. import javax.servlet.ServletException; 5. import javax.servlet.annotation.WebServlet; 6. import javax.servlet.http.HttpServlet; 7. import javax.servlet.http.HttpServletRequest; 8. import javax.servlet.http.HttpServletResponse; 9. @WebServlet("/EditServlet") 10. public class EditServlet extends HttpServlet { 11. protected void doGet(HttpServletRequest request, HttpServletResponse response) 12. throws ServletException, IOException { 13. response.setContentType("text/html"); 14. PrintWriter out=response.getWriter(); 15. out.println("Update Employee"); 16. String sid=request.getParameter("id"); 17. int id=Integer.parseInt(sid); 18. 19. Emp e=EmpDao.getEmployeeById(id); 20. 21. out.print(""); 22. out.print(""); 23. out.print(""); 24. out.print("Name:"); 25. out.print("Password: 26. "); 27. out.print("Email:"); 28. out.print("Country:"); 29. out.print(""); 30. out.print("India"); 31. out.print("USA"); 32. out.print("UK"); 33. out.print("Other"); 34. out.print(""); 35. out.print(""); 36. out.print(" "); 37. out.print(""); 38. out.print(""); 39. 40. out.close(); 41. } 42. } File: EditServlet2.java 1. import java.io.IOException; 2. import java.io.PrintWriter; 3. 4. import javax.servlet.ServletException; 5. import javax.servlet.annotation.WebServlet; 6. import javax.servlet.http.HttpServlet; 7. import javax.servlet.http.HttpServletRequest; 8. import javax.servlet.http.HttpServletResponse; 9. @WebServlet("/EditServlet2") 10. public class EditServlet2 extends HttpServlet { 11. protected void doPost(HttpServletRequest request, HttpServletResponse response) 12. throws ServletException, IOException { 13. response.setContentType("text/html"); 14. PrintWriter out=response.getWriter(); 15. 16. String sid=request.getParameter("id"); 17. int id=Integer.parseInt(sid); 18. String name=request.getParameter("name"); 19. String password=request.getParameter("password"); 20. String email=request.getParameter("email"); 21. String country=request.getParameter("country"); 22. 23. Emp e=new Emp(); 24. e.setId(id); 25. e.setName(name); 26. e.setPassword(password); 27. e.setEmail(email); 28. e.setCountry(country); 29. 30. int status=EmpDao.update(e); 31. if(status>0){ 32. response.sendRedirect("ViewServlet"); 33. }else{ 34. out.println("Sorry! unable to update record"); 35. } 36. 37. out.close(); 38. } 39. 40. } File: DeleteServlet.java 1. import java.io.IOException; 2. import javax.servlet.ServletException; 3. import javax.servlet.annotation.WebServlet; 4. import javax.servlet.http.HttpServlet; 5. import javax.servlet.http.HttpServletRequest; 6. import javax.servlet.http.HttpServletResponse; 7. @WebServlet("/DeleteServlet") 8. public class DeleteServlet extends HttpServlet { 9. protected void doGet(HttpServletRequest request, HttpServletResponse response) 10. throws ServletException, IOException { 11. String sid=request.getParameter("id"); 12. int id=Integer.parseInt(sid); 13. EmpDao.delete(id); 14. response.sendRedirect("ViewServlet"); 15. } 16. } File: ViewServlet.java 1. import java.io.IOException; 2. import java.io.PrintWriter; 3. import java.util.List; 4. 5. import javax.servlet.ServletException; 6. import javax.servlet.annotation.WebServlet; 7. import javax.servlet.http.HttpServlet; 8. import javax.servlet.http.HttpServletRequest; 9. import javax.servlet.http.HttpServletResponse; 10. @WebServlet("/ViewServlet") 11. public class ViewServlet extends HttpServlet { 12. protected void doGet(HttpServletRequest request, HttpServletResponse response) 13. throws ServletException, IOException { 14. response.setContentType("text/html"); 15. PrintWriter out=response.getWriter(); 16. out.println("Add New Employee"); 17. out.println("Employees List"); 18. 19. List list=EmpDao.getAllEmployees(); 20. 21. out.print("

Use Quizgecko on...
Browser
Browser