Você está na página 1de 233

1. What is servlet? Methods of Servlet Life Cycle of Servlet Features of Servlet 2.4 Features of Servlet 2.

5 Advantages of Java Servlets Advantages of Servlets over CGI 2. Quick get to Servlet Servlets overview Introduction to Server Side programming Introduction to Java Servlets Installing Configuring and Running ervlets 3. How to run a Servlet? Install the tomcat server in a directory in which you want to install and set the classpath.for the variable JAVA_HOME in the environment variable. 4. Writing Hello World We should start understanding the servlets from the beginning. Lets start by making one program which will just print the "Hello World" on the browser. Each time the user visits this page it will display "Hello World" to the user. 5. Displaying Date in Servlet In this example we are going to show how we can display a current date and time on our browser. It is very easy to display it on our browser by using the Date class of the java.util package. 6. Simple Counter In Servlet In this example we are going to know how we can make a program on counter which will keep track how many times the servlet has been accessed.

7. A Holistic counter in Servlet In this program we are going to make a such a servlet which will count the number it has been accessed and the number of threads created by the server. 8. Counter in Init() Method In this program we are going to make a such a servlet which will count and displays the number of times it has been accessed and by reading the init parameter to know from where the counting will begin. 9. Snooping the server To display the name of the server you are using use the method getServerName() of the ServletRequest interface. To display the server port number use the method getServerPort(). 10. Snooping Headers In this program we are going to going to make a servlet which will retrieve all the Http request header. 11. Dice Roller We are going to make one program on the dice roller in which the number in the dice will be selected randomly. 12. Getting Init Parameter Names Whenever the container makes a servlet it always reads it deployment descriptor file i.e. web.xml. Container creates name/value pairs for the ServletConfig object. Once the parameters are in ServletConfig they will never be read again by the Container. 13. Passing Parameter Using Html Form This is a very simple example in which we are going to display the name on the browser which we have entered from the Html page. 14. Multiple values for a single parameter In our program it may be that we may have multiples values for a single parameter like in checkboxes. 15. Time Updater in Servlet In this program we are going to make one program on servlet which will keep on updating the time in every second and the result will be displayed to you.

16. Send Redirect in Servlet In this example we are going to make one html in which we will submit the user name and his password. The controller will check if the password entered by the user is correct or not. 17. Session Tracking As we know that the Http is a stateless protocol, means that it can't persist the information. It always treats each request as a new request. In Http client makes a connection to the server, sends the request., gets the response, and closes the connection. 18. To Determine whether the Session is New or Old In this program we are going to make one servlet on session in which we will check whether the session is new or old. 19. Pre- Existing Session In this example we are going to find out whether the session is pre- existing or not. 20. Session Last Accessed Time Example This example illustrates to find current access time of session and last access time of session. Sessions are used to maintain state and user identity across multiple page requests. 21. Get Session Id In this example we are going to make a program in which we will find the session id which was generated by the container. 22. Display session value Using Servlet Sometime while developing web application it is necessary to interact with the different values of the Session object. In this example we will explore the different values of the Session object and then learn how to use it in our programming code. 23. Hit Counter Servlet Example This example illustrates about counting how many times the servlet is accessed. When first time servlet (CounterServlet) runs then session is created and value of the counter will be zero and after again accessing of servlet the counter value will be increased by one. Connection with the Database

24. Inserting Data In Database table using Statement In this program we are going to insert the data in the database from our java program in the table stored in the database. 25. Retrieving Data from the table using Statement In this program we are going to fetch the data from the database in the table from our java program. 26. Inserting data from the HTML page to the database In this program we are going to make program in which we are going to insert the values in the database table from the html form. 27. Retrieving Data from the table using PreparedStatement In this program we are going to fetch the data from the database in the table from our java program using PreparedStatement. 28. Getting Columns Names using Servlets Consider a situation where there is a need to know about the name of the columns without touching our database. As we are the programmers so why we need to worry about the database. 29. Getting Number of Columns Consider a situation where there is a need to know about the number of columns in the table without touching our database. As we are the programmers so why we should worry about the database. 30. Getting Number of Rows Consider a situation where we want to know about the number of rows in the particular database table without touching our database. We want to find out the number of rows without going touching our back- end. 31. Deleting Rows From Table Consider a situation where we have entered some wrong data and in later situation it starts giving problem to the organization. 32. Deleting All Rows From the database Table Consider a situation where we have entered some wrong data and in later situation it starts giving problem to an organization or may become useless after sometime . Rather than go through with that data its better to delete that data.

33. How to add a column in a table Consider a situation where the requirement of the client gets changed and you have asked to modify the structure of the table. In reality it is the work of the database administrator but as a Java programmer you should know how you can modify the structure of the table. 34. How to delete a table in mysql Consider a situation where we need to delete a table from a database. 35. changing column name consider a scenario where we have a table and it consists some data and a situation arises where there is a need to change the name of the column. 36. insert into statement in sql using servlets In this tutorial we are going to learn how we can insert a value from a html form in the table stored in the database. 37. join tables mysql using servlets In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. 38. Natural Left Join using servlets In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. This join will be natural left join. 39. Natural Right Join using servlets In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. This join will be natural right join. 40. Difference between Servlet 2.4 and Servlet 2.5 In this tutorial you will know the difference between Servlet 2.4 and Servlet 2.5 41. Get And Post Method of Http The Get is one the simplest Http method. Its main job is to ask the server for the resource. The Post method is more powerful request. By using Post we can request as well as send some data

to the server. 42. Servlets Links Servlets are the Java platform technology of choice for extending and enhancing Web servers. Servlets provide a componentbased, platform-independent method for building Web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server- and platform-independent. 43. Select Color In this program we are going to selected the various color and on the basis of the selection the output will be displayed to the user. 44. sendRedirect In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not. 45. Send Redirect in Servlet When we want that someone else should handle the response of our servlet, then there we should use sendRedirect() method. 46. Random Redirector In this program we are going to make such a servlet which will be responsible to select a site randomly from the list of sites you have entered. Note that the selection of the site will be randomly. 47. Servlet Context ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it. 48. Servlet Context Listener ServContextListener is a interface which contains two methods: public void contextInitialized(ServletContextEvent event) and public void contextDestroyed(ServletContextEvent event).

49. ServletContextListener example ServletContextListener is notified when the context is initialized. It will be notified when the context is destroyed. It closes the database connection. 50. ServletContextAttributeListener The listener ServletContextAttributeListener is an interface and extends the java.util.EventListener class. This listener come into existence when this interface receives notifications of changes to the attribute list on the servlet context of a web application. 51. HttpSessionListener HttpSessionListener is an interface which extends java.util.EventListener class. The main purpose of this listener is to notify whenever there is a change in the list of active sessions in a web application.. 52. HttpSessionListener example Before going into the details of the SessionListener we should firstly know about the sessions. Whenever a client makes a request for any resources to the server, the server receives the request and processes the request and sends back the response. 53. HttpSessionAttributeListener The listener HttpSessionAttributeListener is an interface and extends the java.util.EventListener class. This listener will be called by the container whenever there there will be change to the attribute list on the servlet session of a web application. 54. HttpSessionAttributeListener Example This listener is used when we want to know when a attribute has been added in a session, when a attribute has been removed and when it is replaced by another attribute. 55. httpsessionbindinglistener HttpSessionBindingListener is a interface which extends java.util.EventListener interface. The purpose of the this interface is to notify an object when it is bound to or unbound from a session. 56. httpsessionbindinglistener example This interface has two methods: valueBound(HttpSessionBindingEvent event) and valueUnBound(HttpSessionBindingEvent event).

57. ServletRequestAttributeListener This listener is used when we want to know when a attribute has been added in a request, when a attribute has been removed and when it is replaced by another attribute. 58. Inserting Image in a database Table Consider a case where we want that along with the name of the person and its information, his image should also come with all these things. 59. Insert Image into Database Using Servlet This example illustrate the process of inserting image into database table using Servlet. This type of program is useful in social networking or HR application where it is necessary to save the uploaded photograph of the user. 60. Retrieve image from database using Servlet In this example we will show you how to develop a Servlet that connects to the MySQL database and retrieves the image from the table. After completing this tutorial you will be able to develop program for your java based applications that retrieves the image from database. 61. say hello in spanish In this program we are going to display "hello" in spanish along with the date. 62. Accessing Date In Servlet In this example, we are going to show how we can display a creation date of the session and last accessed date or time and id on our browser. It is very easy to display it on our browser by using the Date class of the java.util package. 63. Post Message In servlet In this example, we are going to implement posting massage to servlet. In the following program, you will learn how to post massage. 64. Show Parameter In Servlet In this section, you will learn how to send and put all parameter names into the table. The following program uses two methods, which is described below. 65. Get Parameter Name From Servlet Request This example illustrates about how to get parameter from jsp page in your servlet. In the jsp (parameter.jsp) page we have

taken three input fields having name as firstname, lastname and middle name.. 66. How to connect to MySql Database from Servlet? In this example we will show you how to connect to MySQL database and perform select operation. You will learn the JDBC steps necessary to connect to the MySQL Database and execute the query. 67. Servlet Error Message based on user input In this example user is presented with a screen to enter the name. If the entered name exists in the database its displays the sucess message otherwise it displays the error message. So, you can use Servlet to check the user input against database and display the message to the user. 68. Quintessential Servlet Quintessential servlet is not any special kind of servlet. It is just a proper and appropriate way to write a servlet. This quintessential servlet means that servlet is having accurate way of code written for an organizations servlet. 69. Logging Filter Servlet Example This example illustrates how one can write Logging Filter servlet to provide control over log file. You can have additional controls over these log files and these all are available to use by implementing "Filter" class. 70. Context Log Example Using Servlet This example illustrates about how to use of Context Log in servlet. Context Log is used to write specified message to server log file when servlet is called. In the following JSP page (message.jsp) we have simply taken a text area where user give his/her message and post the form. 71. Response Filter Servlet Example This Example shows how to use of response filter in Java Servlet. Filter reads own initial parameters and adds its value to the response. Use the init-param child element of the filter element to declare the initialization parameter and its value. 72. IP Filter Example The filter provides a basic security mechanism for a firewall to determining what traffic passes through the firewall based on IP address details. This protects the secure network from outsiders.

73. Working with Tomcat Server Apache Tomcat is a famous Servlet container developed at Apache Software Foundation. This software is released under under the Apache Software License.

What is Servlet? Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Webbased applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTPspecific calls, receive all the benefits of the mature java language including portability, performance, reusability, and crash protection. Today servlets are the popular choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server and others. Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language. HTTP Servlet typically used to:

Priovide dynamic content like getting the results of a database query and returning to the client. Process and/or store the data submitted by the HTML. Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.

Methods of Servlets A Generic servlet contains the following five methods:

init() public void init(ServletConfig config) throws ServletException The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service. The servlet cannot be put into the service if

The init() method does not return within a fix time set by the web server. It throws a ServletException

Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred. service() public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and javax.servlet.ServletResponse are passed by the servlet container. The status code of the response always should be set for a servlet that throws or sends an error. Parameters - The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception. getServletConfig() public ServletConfig getServletConfig() This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented then it

stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface. Returns - the ServletConfig object getServletInfo() public String getServletInfo() The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup. Returns - a string that contains the information about the servlet destroy() public void destroy() This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held. Life cycle of Servlet The life cycle of a servlet can be categorized into four parts: 1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-onstartup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet. 2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of

the

servlet.

The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet. 3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object. 4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.

Life Cycle of a Servlet

Features of Servlet 2.4 1. Upgraded supports for Http, J2SE, and J2EE: Servlet 2.4 depends on Http1.1 and J2SE 1.3. 2. Additional ServletRequest methods : In Servlet 2.4 four new methods are added in the ServletRequest o getRemotePort(): It returns the IP source port of the client. o getLocalName(): It returns the host name on which the request was recieved. o getLocalAddr(): It returns the IP address on which the request was recieved. o getLocalPort(): It returns the IP port number. 3. New Support for Internationalization and charset choice: To provide support of internationization, Servlet 2.4 has added two new methods in the ServletResponse interface. o setCharacterEncoding(String encoding): The purpose of this method is to set the response's character encoding. This method helps us to pass a charset parameter to setContentType(String) or passing a Locale to setLocale(Locale). We can now avoid setting the charset in the setContentType("text/html;charset=UTF-8") as setCharacterEncoding() method pairs with the preexisting getCharacterEncoding() method to manipulate and view the response's character encoding. getContentType(): It is responsible for returning the response's content type. The content type can be dynamically set with a combination of setContentType(), setLocale(), and setCharacterEncoding() calls, and the method getContentType() provides a way to view the generated type string. 4. New features has been added in RequestDispatcher: In Servlet 2.4 five new request attributes has been added for providing extra information during a RequestDispatcher forward() call. This features has been added is Servlet 2.4 to know the true original request URI. The following request attributes are: o javax.servlet.forward.request_uri o javax.servlet.forward.context_path o javax.servlet.forward.servlet_path o javax.servlet.forward.path_info o javax.servlet.forward.query_string
o

5. SingleThreadModel interface has been deprecated: In Servlet 2.4 the SingleThreadModel interface has been deprecated. 6. HttpSession details and interaction with logins has been clarified: The new method HttpSession.logout() has been added in Servlet 2.4. Now session allows zero or negative values in the <session-timeout> element to indicate sessions should never time out. If the object in the session can't be serialize in a distributed environment then it must throw an IllegalArgumentException. 7. Welcome file behavior and Classloading has been clarified: In servlet 2.4 welcome file can be a servlet. 8. The web.xml file now uses XML Schema: Version 2.4 servers must still accept the 2.2 and 2.3 deployment descriptor formats, but all new elements are solely specified in Schema. Features of Servlet 2.5 This version has been released on September 26, 2005 by the Sun MicroSystems. It is not necessary that all web servers and application servers support the features of Servlet 2.5. Still most of the popular containers like Tomcat 5.5 and JBoss 4.0 support Servlet 2.4. The list of the added features is given below: 1. Dependency on J2SE 5.0: The minimum platform requirement for Servlet 2.5 is JDK 1.5. Servet 2.5 can't be used in versions below than JDK1.5. All the available features of JDK1.5 like generics, autoboxing, an improved for loop etc are guaranteed available to Servlet 2.5 programmers. 2. Support For annotations: Annotations provide a mechanism for decorating java code constructs (classes, methods, fields, etc.) with metadata information. Annotations are mark code in such a way that code processors may alter their behavior based on the metadata information. 3. Several web.xml convenience: Servlet 2.5 introduces several small changes to the web.xml file to make it more convenient to use. For example while writing a <filter-mapping>, we can now use an asterisk in a <servlet-name> which will represent all servlets as well as JSP. Previously we used to do <filter-mapping> <filter-name>FilterName</filter-name>

<servlet-name>FilterName</servlet-name> </filter-mapping> Now, <filter-mapping> <filter-name>FilterName</filter-name> <servlet-name>*</servlet-name> </filter-mapping> Previously in <servlet-mapping> or <filter-mapping> there used to be only one <url-pattern>, but now we can have multiple <url-pattern>, like <servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/abc/*</url-pattern> <url-pattern>/abc/*</url-pattern> </servlet-mapping> Apart from these changes, many more facilities added in web.xml. 4. A Handful of removed restrictions: Servlet 2.5 removed a few restrictions around error handling and session tracking. Now it has removed the restriction that the <error-page> could not call the setStatus() method to alter the error code that triggered them. In session tracking, Servlet 2.5 eased a rule that a servlet called by RequestDispatcher include() couldn't set response headers. 5. Some edge case clarifications: The servlet 2.4 specification says that before calling request.getReader() we must call request.setCharacterEncoding(). However there is no such clarification given why it is so. Advantages of Java Servlets 1. 2. 3. 4. 5. 6. 7. Portability Powerful Efficiency Safety Integration Extensibilty Inexpensive

Each of the points are defined below:

Portability As we know that the servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations. We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server running on the iPlanet/Netscape Application server. So servlets are write once, run anywhere (WORA) program. Powerful We can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. It can do many other things which are difficult to implement in the CGI programs. Efficiency As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. Safety As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. If any exception occurs then it will throw an exception. Integration Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc. Extensibility The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets.

Inexpensive There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.

Advantages of Servlets over CGI Servlets are server side components that provides a powerful mechanism for developing server web applications for server side. Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun's write once run anywhere technology java servlets provide excellent framework for server side processing. Using servlets web developers can create fast and efficient server side applications and can run it on any servlet enabled web server. Servlet runs entirely inside the Java Virtual Machine. Since the servlet runs on server side so it does not depend on browser compatibility. Servlets have a number of advantages over CGI and other API's. They are: 1. Platform Independence Servlets are written entirely in java so these are platform independent. Servlets can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server, you can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets. 2. Performance Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request. 3. Extensibility Java Servlets are developed in java which is robust, welldesigned and object oriented language which can be extended or polymorphed into new objects. So the java servlets take all these advantages and can be extended from existing class to provide the ideal solutions.

4. Safety Java provides very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension. 5. Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.

JAVA SERVLETS An Overview This tutorial covers concepts pertaining to Server side programming in general and Java Servlets in particular. In addition, it demonstrates as how to create and compile a simple Servlet and finally execute it using a Web Server such as an Apache Tomcat Server. It also guides the student through a step by step approach as how to install the above Server, configure it and create the relevant folders and files. After completion of this tutorial, the student would not only be familiar with Servlet fundamentals, but also get hands-on experience in terms of creating and executing simple Servlet programs. 1. Introduction to Server Side Programming 2. Introduction to Java Servlets 3. Installation, Configuration and running Servlets

Introduction to Server Side Programming All of us (or most of us) would have started programming in Java with the ever famous Hello World! program. If you can recollect, we saved this file with a .java extension and later compiled the program using javac and then executed the class file with java. Apart from introducing you to the language basics, the point to be noted about this program is that It is a client side program. This means that you write, compile and also execute the program on a client machine (e.g. Your PC). No doubt, this is the easiest and fastest way to write, compile and execute programs. But, it has little practical significance when it comes to real world programming. 1. Why Server Side Programming? Though it is technically feasible to implement almost any business logic using client side programs, logically or functionally it carries no ground when it comes to enterprise applications (e.g. banking, air ticketing, e-shopping etc.). To further explain, going by the client side programming logic; a bank having 10,000 customers would mean that each customer should have a copy of the program(s) in his or her PC which translates to 10,000 programs! In addition, there are issues like security, resource pooling, concurrent access and manipulations to the database which simply cannot be handled

by client side programs. The answer to most of the issues cited above is Server Side Programming. Figure-1 illustrates Server side architecture in the simplest terms.

2. Advantages of Server Side Programs The list below highlights some of the important advantages of Server Side programs. i. All programs reside in one machine called the Server. Any number of remote machines (called clients) can access the server programs. ii. New functionalities to existing programs can be added at the server side which the clients can advantage without having to change anything from their side. iii. Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about clients hardware or software capabilities. iv. Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by service side applications. v. They are portable and possess the capability to generate dynamic and user-based content (e.g. displaying transaction information of credit card or debit card depending on users choice). 3. vi. Types of Server Side Programs Active Server Pages (ASP)

vii. viii. ix. x.

Java Servlets Java Server Pages (JSPs) Enterprise Java Beans (EJBs) PHP

To summarize, the objective of server side programs is to centrally manage all programs relating to a particular application (e.g. Banking, Insurance, e-shopping, etc). Clients with bare minimum requirement (e.g. Pentium II, Windows XP Professional, MS Internet Explorer and an internet connection) can experience the power and performance of a Server (e.g. IBM Mainframe, Unix Server, etc) from a remote location without having to compromise on security or speed. More importantly, server programs are not only portable but also possess the capability to generate dynamic responses based on users request. Introduction to Java Servlets Java Servlets are server side Java programs that require either a Web Server or an Application Server for execution. Examples for Web Servers include Apaches Tomcat Server and Macromedias JRun. Web Servers include IBMs Weblogic and BEAs Websphere server. Examples for other Server programs include Java Server Pages (JSPs) and Enterprise Java Beans (EJBs). In the forthcoming sections, we will get acquainted with Servlet fundamentals and other associated information required for creating and executing Java Servlets. 1. Basic Servlet Structure As seen earlier, Java servlets are server side programs or to be more specific; web applications that run on servers that comply HTTP protocol. The javax.servlet and javax.servlet.http packages provide the necessary interfaces and classes to work with servlets. Servlets generally extend the HttpServlet class and override the doGet or the doPost methods. In addition, other methods such as init, service and destroy also called as life cycle methods might be used which will be discussed in the following section. The skeleton of a servlet is given in Figure

2. A Servlets Life Cycle The first time a servlet is invoked, it is the init method which is called. And remember that this is called only once during the lifetime of a servlet. So, you can put all your initialization code here. This method next calls the service method. The service method in turn calls the doGet or doPost methods (whichever the user has overridden). Finally, the servlet calls the destroy method. It is in a sense equivalent to the finally method. You can reset or close references / connections done earlier in the servlets methods (e.g. init, service or doGet /doPost). After this method is called, the servlet ceases to exist for all practical purposes. However, please note that it is not mandatory to override all these methods. More often than not, it is the doGet or doPost method used with one or more of the other life cycle methods.

3. A Servlet Program

Output Screens To appreciate the execution of the servlet life cycle methods, keep refreshing the browser (F5 in Windows). In the background, what actually happens is with each refresh, the doGet method is called which increments is value and displays the current value. Find below the screen shots (Figures 5 through 7) captured at random intervals. The procedure to run the servlets

using a Web Server will be demonstrated in the next section (1.3.).

Installing Configuring and Running Servlets In this section, we will see as how to install a WebServer, configure it and finally run servlets using this server. Throughout this tutorial, we will be using Apaches Tomcat server as the WebServer. Tomcat is not only an open and free server, but also the most preferred WebServer across the world. A few reasons we can attribute for its popularity is Easy to install and configure, very less memory footprint, fast, powerful and portable. It is the ideal server for learning purpose. 1. Installation of Tomcat Server and JDK As mentioned earlier, Apaches Tomcat Server is free software available for download @ www.apache.org. The current version of Tomcat Server is 6.0 (as of November 2007). This Server supports Java Servlets 2.5 and Java Server Pages (JSPs) 2.1 specifications. In case of doubt or confusion, you can refer to the abundant documentation repository available on this site. Important software required for running this server is Suns JDK (Java Development Kit) and JRE (Java Runtime Environment). The current version of JDK is 6.0. Like Tomcat, JDK is also free and is available for download at www.java.sun.com. 2. Configuring Tomcat Server

Set JAVA_HOME variable - You have to set this variable which points to the base installation directory of JDK installation. (e.g. c:\program file\java\jdk1.6.0). You can either set this from the command prompt or from My Computer -> Properties -> Advanced -> Environment Variables. o Specify the Server Port You can change the server port from 8080 to 80 (if you wish to) by editing the server.xml file in the conf folder. The path would be something like this c:\program files\apache software foundation\tomcat6\conf\server.xml 3. Run Tomcat Server
o

Once the above pre-requisites are taken care, you can test as whether the server is successfully installed as follows: Step 1 Go to C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin and double click on tomcat6 OR Go to Start->Programs->Apache Tomcat 6.0 -> Monitor Tomcat. You will notice an icon appear on the right side of your Status Bar. Right click on this icon and click on Start service. Step 2 Open your Browser (e.g. MS Internet Explorer) and type the following URL : http://localhost/ (If you have changed to port # to 80) OR Open your Browser (e.g. MS Internet Explorer) and type the following URL : http://localhost:8080/ (If you have NOT changed the default port #) In either case, you should get a page similar to the one in Figure8 which signifies that the Tomcat Server is successfully running on your machine.

4. Compile and Execute your Servlet This section through a step by step (and illustration) approach explains as how to compile and then run a servlet using Tomcat Server. Though this explanation is specific to Tomcat, the procedure explained holds true for other Web servers too (e.g. JRun, Cauchos Resin). Step 1 Compile your servlet program The first step is to compile your servlet program. The procedure is no different from that of writing and compiling a java program. But, the point to be noted is that neither the javax.servlet.* nor the javax.servlet.http.* is part of the standard JDK. It has to be exclusively added in the CLASSPATH. The set of classes required for writing servlets is available in a jar file called servlet-api.jar. This jar file can be downloaded from several sources. However, the easiest one is to use this jar file available with the Tomcat server (C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar). You need to include this path in CLASSPATH. Once you have done this, you will be able to successfully compile your servlet program. Ensure that the class file is created successfully. Step 2 Create your Web application folder The next step is to create your web application folder. The name of the folder can be any valid and logical name that represents your application (e.g. bank_apps, airline_tickets_booking, shopping_cart,etc). But the most important criterion is that this folder should be created under webapps folder. The path would be similar or close to this - C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps. For demo purpose, let us create a folder called demo-examples under the webapps folder.

Figure- depicts the same. Step 3 Create the WEB-INF folder The third step is to create the WEB-INF folder. This folder should be created under your web application folder that you created in the previous step. Figure-10 shows the WEB-INF folder being placed under the demo-examples folder.

Figure WEB-INF folder inside web application folder Step 4 Create the web.xml file and the classes folder The fourth step is to create the web.xml file and the classes folder. Ensure that the web.xml and classes folder are created under the WEB-INF folder. Figure-11 shows this file and folder being placed under the WEB-INF folder.

Figure web.xml file and the classes folder Note Instead of creating the web.xml file an easy way would be to copy an existing web.xml file (e.g. C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\examples\WEB-INF) and paste it into this folder. You can later edit this file and add relevant information to your web application. Step 5 Copy the servlet class to the classes folder We need to copy the servlet class file to the classes folder in order to run the servlet that we created. All you need to do is copy the servlet class file (the file we obtained from Step 1) to this folder. Figure-12 shows the servlet_lifecycle (refer section 1.2.3.) class being placed in the classes folder.

Figure servlet class file placed under classes folder Step 6 Edit web.xml to include servlets name and url pattern This step involves two actions viz. including the servlets name and then mentioning the url pattern. Let us first see as how to include the servlets name in the web.xml file. Open the web.xml file and include the servlets name as shown in Figure-13.

Figure Include servlets name using the <servlet> </servlet> tag Note The servlet-name need not be the same as that of the class name. You can give a different name (or alias) to the actual servlet. This is one of the main reasons as why this tag is used for. Next, include the url pattern using the <servlet-mapping> </servlet-mapping> tag. The url pattern defines as how a user can access the servlet from the browser. Figure-14 shows the url pattern entry for our current servlet.

Figure Include url-pattern using the <servlet-mapping> </servlet-mapping> tag Note Please remember that the path given in the url-pattern is a relative path. This means that this path is w.r.t. your web applications folder (demo-examples in this case). Step 7 Run Tomcat server and then execute your Servlet This step again involves two actions viz. running the Web Server and then executing the servlet. To run the server, follow the steps explained in Section 1.3.3. After ensuring that the web server is running successfully, you can run your servlet. To do this, open your web browser and enter the url as specified in the web.xml file. The complete url that needs to be entered in the browser is: http://localhost/demo-examples/servlet_lifecycle

Figure Our servlets output! Eureka! Heres the output of our first servlet. After a long and pain staking effort, we finally got an output! As mentioned in Section 1.2.3. you can keep refreshing the browser window and see for yourself as how i value is incremented (a proof that the doGet is called every time you re-invoke a servlet).

How to Run a Servlet To run a servlet one should follow the steps illustrated below:

Download and Install the tomcat server: Install the tomcat server in a directory in which you want to install and set the classpath.for the variable JAVA_HOME in the environment variable. To get details about the installation process and setting the classpath click the link Tomcat installation. Set the class for the jar file: Set the classpath of the servletapi.jar file in the variable CLASSPATH inside the environment variable by using the following steps. For Windows XP, Go to Start->Control Panel->System->Advanced->Environment Variables->New button and Set the values as Variable Name: CLASSPATH Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servletapi.jar For Windows 2000 and NT Go to Start->Settings->Control Panel->System->Environment Variables->New button and Set the values as Variable Name: CLASSPATH Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servletapi.jar

Create a java source file and a web.xml file in a directory structure. Compile the java source file, put the compiled file (.class file) in the classes folder of your application and deploy the directory of your application in the webapps folder inside the tomcat directory. Start the tomcat server, open a browser window and type the URL http://localhost:8080/directory (folder name of your application) name/servler name and press enter. If everything is correct your servlet will run.

Writing Hello World We should start understanding the servlets from the beginning. Lets start by making one program which will just print the "Hello World" on the browser. Each time the user visits this page it will display "Hello World" to the user. As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. The server invokes doGet() method whenever web server recieves the GET request from the servlet. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException. Whenever the user sends the request to the server then server generates two obects, first is HttpServletRequest object and the second one is HttpServletResponse object. HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response. Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html. It is the standard MIME content type for the Html pages. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object. To display the output on the browser we use the println() method of the PrintWriter class. The code the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<html>"); pw.println("<head><title>Hello World</title></title>"); pw.println("<body>");

pw.println("<h1>Hello World</h1>"); pw.println("</body></html>"); } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Displaying Date in Servlet In this example we are going to show how we can display a current date and time on our browser. It is very easy to display it on our browser by using the Date class of the java.util package. As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. The server invokes doGet() method whenever web server recieves the GET request from the servlet. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException. Whenever the user sends the request to the server then server generates two obects, first is HttpServletRequest object and the second one is HttpServletResponse object. HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response. Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html. It is the standard MIME content type for the Html pages. The MIME type tells the browser what kind of data the browser is about to receive. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object. To display the output on the browser we use the println() method of the PrintWriter class. The code the program is given below: import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class DisplayingDate extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletRespons e response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); Date today = new Date(); pw.println("<html>"+"<body><h1>Today Date is</h1>"); pw.println("<b>"+ today+"</b></body>"+ "</html>");

} } XML File for this program <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>DateDisplay</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/DateDisplay</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Simple Counter In Servlet In this example we are going to know how we can make a program on counter which will keep track how many times the servlet has been accessed. To make this program firstly we have to make one class SimpleCounterInServlet. The name of the class should follow the naming convention. Remember to keep the name of the class in such a way that it becomes easy to understand what the program is going to do just by seeing the class name. After making a class define one variable counter which will keep record for how many times the servlet has been accessed. Now use method either doGet() or doPost() to write a logic of the program. Our program logic is simple. We have to just increment the value of the counter by 1. To display the output use the method getWriter() method of the response object which will in turn return the object of the PrintWriter class. Now display the value of the counter. The code of the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet{ int counter = 0; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); counter++; pw.println("At present the value of the counter is " + counter); } } The output of the program is given below:

A Holistic counter in Servlet In this program we are going to make a such a servlet which will count the number it has been accessed and the number of threads created by the server. In this example firstly we are going to create one class named as HolisticCounterInServlet. Now declare a variable counter of int with initial value 0, the value of this counter will be different for each servlet and create a Hashtable object. This object will be shared by all the threads in the container. Inside the doGet() method use the method getWriter() method of the response object which will return the PrintWriter object. The code of the program is given below: import import import import import java.io.*; java.io.IOException; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class HolisticCounter extends HttpServlet{ int counter = 0; //separate For Each Servlet static Hashtable hashTable = new Hashtable(); //Shared by all the thr eads public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); counter++; pw.println("This servlet has been accessed" + counter + "times<br>" ); hashTable.put(this,this); pw.println("There are currently" + hashTable.size() + "threads<br>"); } } The output of the program is given below:

Counter in Init() Method In this program we are going to make a such a servlet which will count and displays the number of times it has been accessed and by reading the init parameter to know from where the counting will begin. In this program we are going to make use of the init method of the Servlet interface which takes one argument of ServletConfig. Firstly declare a variable counter which will have the initial value of the counter. The init() method accepts an object which implements ServletConfig interface. It uses the method getInitParameter() method of the ServletConfig interface to the value of the init parameter initial which we have defined in the deployment descriptor file. You need to parse the String value which you will get from the getInitParameter() method to a Integer. The code of the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterInInit extends HttpServlet { int counter; public void init(ServletConfig config) throws ServletException{ super.init(config); String initValue = config.getInitParameter("initial"); try{ counter = Integer.parseInt(initValue); } catch(NumberFormatException e){ counter = 0; } } protected void doGet(HttpServletRequest request, HttpServletResp onse response) throws ServletException, IOException {response.setContentType("tex t/html"); PrintWriter pw = response.getWriter(); counter++; pw.println("Since loading this servlet has been accessed" + counter + "times"); } }

web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>CounterInInit</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/CounterInInit</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Snooping the server In this program we are going to tell you how can a use servlet to display information about its server. Firstly we will create a class in which there will be doGet() method which takes two objects as arguments, first is request object and the second one is of response. To display the name of the server you are using use the method getServerName() of the ServletRequest interface. To display the server port number use the method getServerPort(). You can also use other methods of the ServletRequest interface like getProtocol() to display the protocol you are using and many more methods depending on your needs. The code of the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SnoopingServerServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); pw.println("The server name is " + request.getServerName() + "<br>"); pw.println("The server port number is " + request.getServerPort()+ "<br>"); pw.println("The protocol is " + request.getProtocol()+ "<br>"); pw.println("The scheme used is " + request.getScheme()); } } web.xml file for this program:<?xml version="1.0" encoding="ISO8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>SnoopingServerServlet</servlet-class> </servlet>

<servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/SnoopingServerServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Snooping Headers In this program we are going to going to make a servlet which will retrieve all the Http request header. To make a program over this firstly we need to make one class named GettingSnoopingHeader. In HttpRequest there are too many headers. To retrieve all the headers firstly we need to call the getWriter() which returns PrintWriter object and helps us to display all the headers. To get a header names call the method getHeaderNames() of the request object which will return the Enumeration of the headers. Now to retrieve all the headers from the Enumeration use the method hasMoreElements(). This method checks whether there are more headers or not. To display the output on your browser use the PrintWriter object. The code of the program is given below: import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class HeaderSnoopServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResp onse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); pw.println("Request Headers are"); Enumeration enumeration = request.getHeaderNames(); while(enumeration.hasMoreElements()){ String headerName = (String)enumeration.nextElement(); Enumeration headerValues = request.getHeaders(headerName); if (headerValues != null){ while (headerValues.hasMoreElements()){ String values = (String) headerValues.nextElement(); pw.println(headerName + ": " + values); } } } } } web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>HeaderSnoopServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HeaderSnoopServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Dice Roller We are going to make one program on the dice roller in which the number in the dice will be selected randomly. To make a program over this firstly we need to make a class DiceRoller in which we will have a doGet() method in which we will have our application logic. To make the dice working randomly use the random() method of the class java.lang.Math. To print the number on the browser call the method getWriter() of the response object which will return the PrintWriter object. Now by the object of the PrintWriter class print the values of the dice on the browser. The code of the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DiceRollerServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletRespo nse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); String dice1 = Integer.toString((int)(Math.random()*6)+1); String dice2 = Integer.toString((int)(Math.random()*6)+1); pw.println("<html><body>"); pw.println("dice roller<br>"); pw.println("dice1 value is " + dice1 + " and <br>dice2 value is " +dic e2); } } XML File for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//E N" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>DiceRollerServlet</servlet-class>

</servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/DiceRollerServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Getting Init Parameter Names In this example we are going to retreive the init paramater values which we have given in the web.xml file. Whenever the container makes a servlet it always reads it deployment descriptor file i.e. web.xml. Container creates name/value pairs for the ServletConfig object. Once the parameters are in ServletConfig they will never be read again by the Container. The main job of the ServletConfig object is to give the init parameters. To retrieve the init parameters in the program firstly we have made one class named GettingInitParameterNames. The container calls the servlet's service() method then depending on the type of request, the service method calls either the doGet() or the doPost(). By default it will be doGet() method. Now inside the doGet() method use getWriter() method of the response object which will return a object of the PrintWriter class which helps us to print the content on the browser. To retrieve all the values of the init parameter use method getInitParameterNames() which will return the Enumeration of the init parameters. The code of the program is given below: import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; java.util.*;

public class InitServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); pw.print("Init Parameters are : "); Enumeration enumeration = getServletConfig().getInitParameterNa mes(); while(enumeration.hasMoreElements()){ pw.print(enumeration.nextElement() + " "); }

pw.println("\nThe email address is " + getServletConfig().getInitPara meter("AdminEmail")); pw.println("The address is " + getServletConfig().getInitParameter(" Address")); pw.println("The phone no is " + getServletConfig().getInitParameter( "PhoneNo")); } } web.xml file of this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <init-param> <param-name>AdminEmail</param-name> <param-value>zulfiqar_mca@yahoo.co.in</param-value> </init-param> <init-param> <param-name>Address</param-name> <param-value>Okhla</param-value> </init-param> <init-param> <param-name>PhoneNo</param-name> <param-value>9911217074</param-value> </init-param> <servlet-name>Zulfiqar</servlet-name> <servlet-class>InitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/InitServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Passing Parameter Using Html Form This is a very simple example in which we are going to display the name on the browser which we have entered from the Html page. To get the desired result firstly we have to make one html form which will have only one field named as name in which we will enter the name. And we will also have one submit button, on pressing the submit button the request will go to the server and the result will be displayed to us. In the servlet which will work as a controller here picks the value from the html page by using the method getParameter(). The output will be displayed to you by the object of the PrintWriter class. The code of the program is given below: <html> <head> <title>New Page 1</title> </head> <body> <h2>Login</h2> <p>Please enter your username and password</p> <form method="GET" action="/htmlform/LoginServlet"> <p> Username <input type="text" name="username" size="20" ></p> <p> Password <input type="text" name="password" size="20"> </p> <p><input type="submit" value="Submit" name="B1"></p> </form> <p>&nbsp;</p> </body> </html> LoginServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class LoginServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("username"); String pass = request.getParameter("password"); out.println("<html>"); out.println("<body>"); out.println("Thanks Mr." + " " + name + " " + "for visiting roseindi a<br>" ); out.println("Now you can see your password : " + " " + pass + "<br >"); out.println("</body></html>"); } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Multiple values for a single parameter In our program it may be that we may have multiples values for a single parameter like in checkboxes. We are going to make one program over it. To make such a servlet which we have made one html form from where the values will be passed to the controller. In this program we have used the checkbox which will have the same name but with different values. We have one more button submit, on pressing this button the request will be forwarded. Now in the servlet that is working like a controller will retrieve the values we have entered in the html form by the method getParameterValues() which returns the array of String. At last to retrieve all the values from the array use the for loop. The output will be displayed to you by the PrintWriter object. The code of the program is given below: Index.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Insert title here</title> </head> <body> <form method = "post" action = "/GetParameterServlet/GetParameter Values"> <p>Which of the whisky you like most</p> <input type = "checkbox" name ="whisky" value = "RoyalChallenge"> RoyalChallenge.<br> <input type = "checkbox" name ="whisky" value = "RoyalStag">Royal Stag.<br> <input type = "checkbox" name ="whisky" value = "Bagpiper">Bagpi per.<br> <input type ="submit" name= "submit"> </form> </body> </html> GetParameterValues.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetParameterValues extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResp onse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String[] whisky = request.getParameterValues("whisky"); for(int i=0; i<whisky.length; i++){ pw.println("<br>whisky : " + whisky[i]); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>GetParameterValues</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/GetParameterValues</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Here is the result of the above selection:

Time Updater in Servlet In this program we are going to make one program on servlet which will keep on updating the time in every second and the result will be displayed to you. To make this servlet firstly we need to make a class named TimeUpdater. The name of the class should be such that it becomes easy to understand what the program is going to do. Call the method getWriter() method of the response object which will return a PrintWriter object. Use the method getHeader() of the response object to add a new header. We can also use setHeader() in place of getHeader(). The setHeader() method overrides the previous set header. Now by using the PrintWriter object display the result on the browser. The code of the program is given below:

import import import import

java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class TimeUpdater extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); response.addHeader("Refresh", "1"); pw.println(new Date().toString()); } } The output of the program is given below:

Send Redirect in Servlet When we want that someone else should handle the response of our servlet, then there we should use sendRedirect() method. In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not. If not then the servlet decides that the request can be handle by other servlet or jsp. Then the servlet calls the sendRedirect() method of the response object and sends back the response to the browser along with the status code. Then the browser sees the status code and look for that servlet which can now handle the request. Again the browser makes a new request, but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser. In all this process the client is unaware of the processing. In this example we are going to make one html in which we will submit the user name and his password. The controller will check if the password entered by the user is correct or not. If the password entered by the user is correct then the servlet will redirect the request to the other servlet which will handle the request. If the password entered by the user is wrong then the request will be forwarded to the html form. The code of the example is given below: html file for this program: <html> <head> <title>New Page 1</title> </head> <body> <form method="POST" action="/SendRedirect/SendRedirectServlet"> <p>Enter your name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs p;&nbsp; <input type="text" name="username" size="20"></p> <p>Enter your password&nbsp; <input type="text" name="passwor d" size="20"></p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;& nbsp;&nbsp;&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="submit" value="Submit" name="B1"></p> </form> </body> </html>

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SendRedirectServlet extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResp onse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String name = request.getParameter("username"); String password = request.getParameter("password"); if(name.equals("James")&& password.equals("abc")){ response.sendRedirect("/SendRedirect/ValidUserServlet"); } else{ pw.println("u r not a valid user"); } } }

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ValidUserServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletRespo nse response)

throws ServletException, IOException { PrintWriter pw = response.getWriter(); pw.println("Welcome to roseindia.net " + " "); pw.println("how are you"); } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>SendRedirectServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/SendRedirectServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>ValidUserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/ValidUserServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Session Tracking As we know that the Http is a stateless protocol, means that it can't persist the information. It always treats each request as a new request. In Http client makes a connection to the server, sends the request., gets the response, and closes the connection. In session management client first make a request for any servlet or any page, the container receives the request and generate a unique session ID and gives it back to the client along with the response. This ID gets stores on the client machine. Thereafter when the client request again sends a request to the server then it also sends the session Id with the request. There the container sees the Id and sends back the request. Session Tracking can be done in three ways: 1. Hidden Form Fields: This is one of the way to support the session tracking. As we know by the name, that in this fields are added to an HTML form which are not displayed in the client's request. The hidden form field are sent back to the server when the form is submitted. In hidden form fields the html entry will be like this : <input type ="hidden" name = "name" value="">. This means that when you submit the form, the specified name and value will be get included in get or post method. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command. 2. URL Rewriting: This is another way to support the session tracking. URLRewriting can be used in place where we don't want to use cookies. It is used to maintain the session. Whenever the browser sends a request then it is always interpreted as a new request because http protocol is a stateless protocol as it is not persistent. Whenever we want that out request object to stay alive till we decide to end the request object then, there we use the concept of session tracking. In session tracking firstly a session object is created when the first request goes to the server. Then server creates a token which will be used to maintain the session. The token is transmitted to the client by the response object and gets stored on the client machine. By default the server creates a cookie and the cookie get stored on the client machine. 3. Cookies: When cookie based session management is used, a token is generated which contains user's information, is sent to the browser by the server. The cookie is sent back to the server when the user sends a new request. By this cookie, the server is able to identify the user. In this way the session is maintained.

Cookie is nothing but a name- value pair, which is stored on the client machine. By default the cookie is implemented in most of the browsers. If we want then we can also disable the cookie. For security reasons, cookie based session management uses two types of cookies.

To Determine whether the Session is New or Old In this program we are going to make one servlet on session in which we will check whether the session is new or old. To make this program firstly we need to make one class named CheckingTheSession. Inside the doGet() method, which takes two objects one of request and second of response. Inside this method call the method getWriter() of the response object. Use getSession() of the request object, which returns the HttpSession object. Now by using the HttpSession we can find out whether the session is new or old. The code of the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CheckingTheSession extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResp onse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Checking whether the session is new or old<br>"); HttpSession session = request.getSession(); if(session.isNew()){ pw.println("You have created a new session"); } else{ pw.println("Session already exists"); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app>

<servlet> <servlet-name>Hello</servlet-name> <servlet-class>CheckingTheSession</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/CheckingTheSession</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Pre- Existing Session In this example we are going to find out whether the session is preexisting or not. Consider a situation where servlet want to use only a existing session. It is not always a good idea to create a new session. To perform this work we have one overloaded method getSession(boolean) of the request object. If we don't want to create a new session then we should use getSession(false). In the example below we have used the method getSession(false) which will test whether the session is null or not. If there will be no session then the new session will be created by the method getSession(). The code of the program is given below: PreExistingSessionServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class PreExistingSessionServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResp onse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Testing The Session : "); HttpSession session = request.getSession(false); if(session==null){ pw.println("There is no session"); pw.println("Can we create a session for you. Creating........."); session = request.getSession(); } else{ pw.println("Session already exists"); } } } web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>PreExistingSessionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/PreExistingSessionServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Session Last Accessed Time Example This example illustrates to find current access time of session and last access time of session. Sessions are used to maintain state and user identity across multiple page requests. An implementation of HttpSession represents the server's view of the session. The server considers a session to be new until it has been joined by the client. Until the client joins the session, isNew() method returns true.

Here is the source code of LastAccessTime.java import import import import import import import import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; java.net.*; java.util.*; javax.servlet.ServletConfig; javax.servlet.ServletException; javax.servlet.ServletOutputStream; javax.servlet.http.HttpSession; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class LastAccessTime extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse respons e) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String head; Integer count = new Integer(0); if (session.isNew()) { head = "New Session Value "; } else { head = "Old Session value"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1);

} } session.putValue("count", count); out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" + "<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" + "<H4 ALIGN=\"CENTER\">Session Access Time:</H4>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"pink\">\n" + " <TD>Session Creation Time\n" +" <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR BGCOLOR=\"pink\">\n" +" <TD>Last Session Access Time\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "</TABLE>\n" +"</BODY></HTML>"); } public void doPost(HttpServletRequest request,HttpServletResponse respons e) throws ServletException, IOException { doGet(request, response); } } Description of code: In the above servlet, isNew() method is used to find whether session is new or old. The getCreationTime() method is used to find the time when session was created. The getLastAccessedTime() method is used to find when last time session was accessed by the user. Here is the mapping of servlet ("LastAccessTime.java") in the web.xml file: <servlet> <servletname>LastAccessTime</servle t-name> <servletclass>LastAccessTime</servlet -class> </servlet> <servlet-mapping> <servletname>LastAccessTime</servle t-name> <urlpattern>/LastAccessTime</urlpattern> </servlet-mapping>

Running the servlet by this url: http://localhost:8080/CodingDiaryExample/LastAccessTime displays the output like below:

When user re-calls the servlet the creation time will be same but last accessed time will be changed as shown in the following figure:

Get Session Id In this example we are going to make a program in which we will find the session id which was generated by the container. HttpSession session = request.getSession(); Inside the service method we ask for the session and every thing gets automatically, like the creation of the HttpSession object. There is no need to generate the unique session id. There is no need to make a new Cookie object. Everything happens automatically behind the scenes. As soon as call the method getSession() of the request object a new object of the session gets created by the container and a unique session id generated to maintain the session. This session id is transmitted back to the response object so that whenever the client makes any request then it should also attach the session id with the requsest object so that the container can identify the session. The code of the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionIdServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResp onse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(); String id = session.getId(); pw.println("Session Id is : " + id); } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app>

<servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>SessionIdServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/SessionIdServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Display session value Using Servlet Sometime while developing web application it is necessary to interact with the different values of the Session object. In this example we will explore the different values of the Session object and then learn how to use it in our programming code. You will learn how to find all the session related information like:

getId. This method is used to find the identifier of the session which is unique. isNew. This method is used when find, whether session is newly created or preexisted. If session has never seen by user then this method return "true" but if session is preexisted then it return "false". getCreationTime. This method is used to find the creation time of session. To use of this method we can find the following details about session i.e. day, month, date, time, GMT(Greenwich Mean Time) and year will be displayed. getLastAccessedTime. This method is used to find the last accessed time of session. It returns the time, in milliseconds. getMaxInactiveInterval. This method returns the total time, in seconds, during which session remains active if user does not accesses the session for this maximum time interval. After this time the session will be invalidated automatically. A negative value indicates that the session should never timeout.

Here is the sample code for HttpSessionDisplay.java: import import import import import import import import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; java.net.*; java.util.*; javax.servlet.ServletConfig; javax.servlet.ServletException; javax.servlet.ServletOutputStream; javax.servlet.http.HttpSession; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class HttpSessionDisplay extends HttpServlet { String head; public void doGet(HttpServletRequest request,HttpServletResponse response ) throws ServletException, IOException {

HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Integer count = new Integer(0); if (session.isNew()) { head = "New Session Value"; } else { head = "Old Session value"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1); } } session.putValue("count", count); out.println("<HTML><BODY BGCOLOR=\"pink\">\n" + "<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" + "<H3 ALIGN=\"CENTER\">Description about Session:</H3>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"voilet\">\n" + " <TH>Information Type<TH>Session Value\n" +"<TR>\n" +" <TD>ID\n" + "<TD>" + session.getId() + "\n" + "<TR>\n" + " <TD>Session Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" +" <TD>Last Session Access Time\n" +" <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" +" <TD>Number of Previous Session Accesses\n" + "<TD>" + count + "\n" + "</TABLE>\n" +"</BODY></HTML>"); } public void doPost(HttpServletRequest request,HttpServletResponse respons e) throws ServletException, IOException { doGet(request, response); } } Here is the mapping of class file in web.xml. <servlet> <servletname>HttpSessionDisplay</servle t-name> <servletclass>HttpSessionDisplay</servlet -class>

</servlet> <servlet-mapping> <servletname>HttpSessionDisplay</servle t-name> <urlpattern>/HttpSessionDisplay</urlpattern> </servlet-mapping> Run this example by this url: http://localhost:8080/CodingDiaryExample/HttpSessionDisplay Output: In case of first time accessing of servlet the following session value will be displayed

In case of preexist session if user accessed the servlet then the following session value will be displayed.

Hit Counter Servlet Example This example illustrates about counting how many times the servlet is accessed. When first time servlet (CounterServlet) runs then session is created and value of the counter will be zero and after again accessing of servlet the counter value will be increased by one. In this program isNew() method is used whether session is new or old and getValue() method is used to get the value of counter.

Here is the source code of CounterServlet.java: import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class CounterServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Integer count = new Integer(0); String head; if (session.isNew()) { head = "This is the New Session"; } else { head = "This is the old Session"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1); } } session.putValue("count", count); out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" + "<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" + "<TABLE BORDER=1 ALIGN=CE n" + "<TR BGCOLOR=\"#FFAD00\">\n" +" <TH>Information Type<TH>Session Count\n"

+"<TR>\n" +" <TD>Total Session Accesses\n" + "<TD>" + count + "\n" + "</TABLE>\n" +"</BODY></HTML>" ); } } Mapping of Servlet ("CounterServlet.java") in web.xml file <servlet> <servletname>CounterServlet</servle t-name> <servletclass>CounterServlet</servlet -class> </servlet> <servlet-mapping> <servletname>CounterServlet</servle t-name> <urlpattern>/CounterServlet</urlpattern> </servlet-mapping> Running the servlet by this url: http://localhost:8080/CodingDiaryExample/CounterServlet displays the figure below:

When servlet is hit two times by the user the counter value will be increased by two as shown in figure below:

Inserting Data In Database table using Statement In this program we are going to insert the data in the database from our java program in the table stored in the database. To accomplish our goal we first have to make a class named as ServletInsertingData, which must extends the abstract HttpServlet class, the name of the class should be such that other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method that takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException. Inside this method call the getWriter() method of the PrintWriter class. We can insert the data in the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we first need to call the method forName(), which is static in nature of the class Class. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method createStatement() of the Connection object which will return the Statement object. This object is used for executing a static SQL statement and obtaining the results produced by it. We have to insert a values into the table so we need to write a query for inserting the values into the table. This query we will write inside the executeUpdate() method of the Statement object. This method returns int value. If the record will get inserted in the table then output will show "record has been inserted" otherwise "sorry! Failure". The code of the program is given below: import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class DataInsertion extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String url = "jdbc:mysql://localhost/zulfiqar? user=root&password=admin"; Connection conn; ResultSet rs; try{ Class.forName("org.gjt.mm.mysql.Driver"); conn = DriverManager.getConnection(url); Statement statement = conn.createStatement(); String query = "insert into emp_sal values('zulfiqar', 15000)"; int i = statement.executeUpdate(query); if(i!=0){ out.println("The record has been inserted"); } else{ out.println("Sorry! Failure"); } rs = statement.executeQuery("select * from emp_sal"); while(rs.next()){ out.println("<p><table>" + rs.getString(1) + " " + rs.getInt(2) + "</p></table>"); } rs.close(); statement.close(); } catch (Exception e){ System.out.println(e); } } } XML File for this program <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name>

<servlet-class>DataInsertion</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/DataInsertion</url-pattern> </servlet-mapping> </web-app> Table in the database before Insertion: mysql> select * from emp_sal; Empty set (0.02 sec) The output of the program is given below:

Table in the database after Insertion: mysql> select * from emp_sal; +----------+-------+ | EmpName | salary | +----------+-------+ | zulfiqar | 15000 | +----------+-------+ 1 row in set (0.02 sec)

Retrieving Data from the table using Statement In this program we are going to fetch the data from the database in the table from our java program. To accomplish our goal we first have to make a class named as ServletFetchingData which must extends the abstract HttpServlet class, the name of the class should be such that the other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method which takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException. Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we firstly need to call the method forName() which is static in nature of the class ClassLoader. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method createStatement() of the Connection object which will return the Statement object. This object is used for executing a static SQL statement and obtaining the results produced by it. As we need to retrieve the data from the table so we need to write a query to select all the records from the table. This query will be passed in the executeQuery() method of Statement object, which returns the ResultSet object. Now the data will be retrieved by using the getString() method of the ResultSet object. The code of the program is given below: import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletFetchingDataFromDatabase1 extends HttpServle t{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection=null; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("Select * from emp_sal"); while(rs.next()){ pw.println("EmpName" + " " + "EmpSalary" + "<br>"); pw.println(rs.getString(1) + " " + rs.getString(2) + "<br>"); } } catch (Exception e){ pw.println(e); } } } XML File for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>ServletFetchingDataFromDatabase</servletclass> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/ServletFetchingDataFromDatabase</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Table in the database: mysql> select * from emp_sal; +----------+--------+ | EmpName | salary | +----------+--------+ | zulfiqar | 15000 | | vinod | 12000 | +----------+--------+ 2 rows in set (0.00 sec)

Inserting data from the HTML page to the database In this program we are going to make program in which we are going to insert the values in the database table from the html form. To make our program working we need to make one html form in which we will have two fields, one is for the name and the other one is for entering the password. At last we will have the submit form, clicking on which the values will be passed to the server. The values which we have entered in the Html form will be retrieved by the server side program which we are going to write. To accomplish our goal we first have to make a class named as ServletInsertingDataUsingHtml which must extends the abstract HttpServlet class, the name of the class should be such that the other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method which takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException. Inside this method call the getWriter() method of the PrintWriter class. We can insert the data in the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we firstly need to call the method forName() which is static in nature of the class Class. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method prepareStatement() of the Connection object which will return the PreparedStatement object and takes one a query which we want to fire as its input. The values which we have got from the html will be set in the database by using the setString() method of the PreparedStatement object. If the record will get inserted in the table then output will show "record has been inserted" otherwise "sorry! Failure". The code of the program is given below: <html>

<head> <title>New Page 1</title> </head> <body> <form method="POST" action="/InDataByHtml/ServletInsertingDataUsi ngHtml"> <!--webbot bot="SaveResults" UFile="fpweb:///_private/form_results.txt" S-Format="TEXT/CSV" S-Label-Fields="TRUE" --> <p>Enter Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input ty pe="text" name="username" size="20"></p> <p>Enter Password: <input type="text" name="password" size="20 "></p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;& nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="submit" value="Submit" name="B1"></p> </form> </body> </html> ServletInsertingDataUsingHtml.java import import import import import java.io.*; java.lang.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletInsertingDataUsingHtml extends HttpServlet{ public void doPost(HttpServletRequest request, HttpServletRespons e response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ String username = request.getParameter("username");

String password = request.getParameter("password"); pw.println(username); pw.println(password); Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("insert into emp_info values(?,?)"); pst.setString(1,username); pst.setString(2,password); int i = pst.executeUpdate(); if(i!=0){ pw.println("<br>Record has been inserted"); } else{ pw.println("failed to insert the data"); } } catch (Exception e){ pw.println(e); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletInsertingDataUsingHtml</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletInsertingDataUsingHtml</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

This is the output of the above input.

Retrieving Data from the table using PreparedStatement In this program we are going to fetch the data from the database in the table from our java program using PreparedStatement. To accomplish our goal we first have to make a class named as ServletFetchingDataFromDatabase which must extends the abstract HttpServlet class, the name of the class should be such that the other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method which takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException. Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we firstly need to call the method forName() which is static in nature of the class ClassLoader. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method prepareStatement() of the Connection object which will return the PreparedStatement object and takes a query as its parameter. In this query we will write the task we want to perform. The Resultset object will be retrieved by using the executeQuery() method of the PreparedStatement object. Now the data will be retrieved by using the getString() method of the ResultSet object. The code of the program is given below: import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletFetchingDataFromDatabase extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection=null; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("Select * fr om emp_sal"); ResultSet rs = pst.executeQuery(); while(rs.next()){ pw.println(rs.getString(1) +" " + rs.getString(2)+"<br>"); } } catch (Exception e){ pw.println(e); } pw.println("hello"); } } The output of the program is given below:

Table in the database: mysql> select * from emp_sal; +----------+--------+ | EmpName | salary | +----------+--------+ | zulfiqar | 15000 | | vinod | 12000 | +----------+--------+

2 rows in set (0.00 sec)

Getting Columns Names using Servlets Consider a situation where there is a need to know about the name of the columns without touching our database. As we are the programmers so why we need to worry about the database. We want to do the manipulation by sitting on our computer through our program without going into the database. In this example we are going to exactly the same as we said above. To make this possible we need to make a class named ServletGettingColumnsNames, the name of the program should be such that if in future there is any need to make any change in the program, you can easily understand in which program you have to make a change. Now inside the doGet() method use the getWriter() method of the response object and its returns the PrintWriter object, which helps us to write on the browser. To get a column names from the database there is a need for the connection between the database and the java program. After the establishment of the connection with the database pass a query for retrieving all the records from the database and this will return the PreparedStatement object. To get the column names from the database we firstly need a reference of ResultSetMetaData object and we will get it only when if we have the ResultSet object. To get the object of the ResultSet we will call the method executeQuery() of the PreparedStatement interface. Now we have the object of the ResultSet. By the help of the ResultSet we can get the object of ResultSetMetaData. We will get it by calling the method getMetaData() of the ResultSet interface. The names of the columns will be retrieved by the method getColumnsNames() of the ResultSetMetaData interface. The output will be displayed to you by the PrintWriter object. The code of the program is given below: import import import import javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class ServletGettingColumnsNames extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html");

PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection=null; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("select * fr om emp_details"); ResultSet rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int noOfColumns = rsmd.getColumnCount(); //It shows the number of columns pw.println("The number of columns are " + noOfColumns + "<br>" ); //It shows the name of the columns pw.println("The name of the columns are: <br>"); for(int i =1; i<=noOfColumns;i++){ String names = rsmd.getColumnName(i); pw.println(names); } } catch(Exception e){ pw.println("The exception is " + e); } } } XML File for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletGettingColumnsNames</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletGettingColumnsNames</url-pattern> </servlet-mapping> </web-app>

The output of the program is given below:

Table in the database: mysql> select * from emp_details; +--------+----------+---------+----------+----------+-------+---------+--------+ | userId | Name | surname | address1 | address2 | town | country | zipcode | +--------+----------+---------+----------+----------+-------+---------+--------+ | 73979 | zulfiqar | Ahmed | Moradabad | Delhi | Okhla | India | 110025 | +--------+----------+---------+----------+----------+-------+---------+--------+ 1 row in set (0.00 sec)

Getting Number of Columns Consider a situation where there is a need to know about the number of columns in the table without touching our database. As we are the programmers so why we should worry about the database. We want to do the manipulation by sitting on our computer through our program without going into the database. In this example we are going to exactly the same as we said above. To make this possible we need to make a class named ServletGettingNoOfColumns, the name of the program should be such that if in future there is any need to make any change in the program, you can easily understand in which program you have to make a change. As we know that in Servlet the main logic of the program is written inside the service method and in turn the service method calls the doGet() method. Now inside the doGet() method use the getWriter() method of the response object and its returns the PrintWriter object, which helps us to write on the browser. To get the number of columns from the database table there is a need for the connection between the database and the java program. After the establishment of the connection with the database, pass a query for retrieving all the records from the database and this will return the PreparedStatement object. To get the number of columns from the database we firstly need a reference of ResultSetMetaData object and we will get it only when if we have the ResultSet object with us. To get the object of the ResultSet we will call the method executeQuery() of the PreparedStatement interface. Now we have the object of the ResultSet. By the help of the ResultSet we can get the object of ResultSetMetaData. We will get it by calling the method getMetaData() of the ResultSet interface. The number of columns in the databasd table will be retrieved by the method getColumnsCount() of the ResultSetMetaData interface. This method will return the integer type of value. The number of columns will be displayed on the browser by the PrintWriter object. The code of the program is given below: import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletGettingNoOfColumns extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection=null; try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("select * fr om emp_details"); ResultSet rs = pst.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int noOfColumns = rsmd.getColumnCount(); //It shows the number of columns pw.println("The number of columns are " + noOfColumns); } catch(Exception e){ pw.println("The exception is " + e); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletGettingNoOfColumns</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletGettingNoOfColumns</url-pattern> </servlet-mapping> </web-app> Table emp_details in the database: mysql> select * from emp_details;

+--------+----------+---------+-----------+---------+--------+---------+--------+ | userId | Name | surname | address1 | address2 | town | country | zipcod e| +--------+----------+---------+-----------+---------+--------+---------+--------+ | 86372 | Zulfiqar | Ahmed | Moradabad | Rohini | Rohini | Delhi | 110025 | +--------+----------+---------+-----------+---------+--------+---------+------The output of the program is given below:

Getting Number of Rows Consider a situation where we want to know about the number of rows in the particular database table without touching our database. As we are the programmers so why we should worry about the database complexities. We want to find out the number of rows without going touching our back- end. In this example we are going to exactly the same as we said above. To make this possible we need to make a class named ServletGettingNoOfRows, the name of the program should be such, if in future there is any need to make any change in the program, you can easily understand in which program you have to make a change. As we know that in Servlet the main logic of the program is written inside the service method and in turn the service method calls the doGet() method. Now inside the doGet() method use the getWriter() method of the response object and its returns the PrintWriter object, which helps us to write on the browser. To get the number of rows from the database table there is a need for the connection between the database and the java program. After the establishment of the connection with the database, fire a query for selecting the number of rows from the database table inside the executeQuery() method of the PreparedStatement object and returns the ResultSet object. Now we have the ResultSet object, by the help of this object we can get the number of rows we have in the database table. The number of rows we have in the database table will be displayed on the browser by the PrintWriter object. The code of the program is given below: import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletGettingNoOfRows extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ int rows=0; response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection;

try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement(""); ResultSet rs = pst.executeQuery("select count(*) from emp_sal"); while (rs.next()){ rows = rs.getInt(1); } pw.println("The number of rows are " + rows); } catch(Exception e){ pw.println("The exception is " + e); } } } XML File for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletGettingNoOfRows</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletGettingNoOfRows</url-pattern> </servlet-mapping> </web-app> Table emp_sal in the database: mysql> select * from emp_sal; +----------+--------+ | EmpName | salary | +----------+--------+ | zulfiqar | 15000 | | vinod | 12000 |

+----------+--------+ 2 rows in set (0.05 sec) The output of the program is given below:

Deleting Rows From Table Consider a situation where we have entered some wrong data and in later situation it starts giving problem to the organization. Rather than go through with that data its better to delete that data. We can do it very easily through our program, what we need is a simple query. In this example we are going to exactly the same as we said above. To make this possible we need to make a class named ServletDeletingRowsFromTable, the name of the program should be such, if in future there is any need to make any change in the program, you can easily understand in which program you have to make a change. As we know that in Servlet the main logic of the program is written inside the service method and in turn the service method calls the doGet() method. Now inside the doGet() method use the getWriter() method of the response object and its returns the PrintWriter object, which helps us to write on the browser. To delete the unwanted data from our table there is a need for the connection between the database and the java program. After the establishment of the connection with the database, fire a query for deleting the unwanted row in the database table. This query will be fired inside the prepareStatement() method of the Connection object and returns the PreparedStatement object. If the rows has been deleted from the database table then print the message "row is deleted" otherwise "no rows has been deleted". The code of the program is given below: import import import import javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class ServletDeletingRowsFromTable extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ int rows; response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root",

"admin"); PreparedStatement pst = connection.prepareStatement ("delete from emp_sal where EmpName = 'vinod'"); int i = pst.executeUpdate(); if (i==0){ pw.println("Row has been deleted"); } else{ pw.println("No rows has been deleted"); } } catch(Exception e){ pw.println("The exception is " + e); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletDeletingRowsFromTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletDeletingRowsFromTable</url-pattern> </servlet-mapping> </web-app> Table in the database before deletion: mysql> select * from emp_sal; +----------+--------+ | EmpName | salary | +----------+--------+ | zulfiqar | 15000 | | vinod | 12000 |

+----------+--------+ 2 rows in set (0.00 sec) The output of the program is given below:

Table in the database after deletion: mysql> select * from emp_sal; +----------+-------+ | EmpName | salary | +----------+-------+ | zulfiqar | 15000 | +----------+-------+ 1 row in set (0.05 sec)

Deleting All Rows From the database Table Consider a situation where we have entered some wrong data and in later situation it starts giving problem to an organization or may become useless after sometime . Rather than go through with that data its better to delete that data. We can do it very easily through our program, what we need is a simple query. In this example we are going to exactly the same as we said above. To make this possible we need to make a class named ServletDeletingAllRowsFromTable, the name of the program should be such, if in future there is any need to make any change in the program, you can easily understand in which program you have to make a change. As we know that in Servlet the main logic of the program is written inside the service method and in turn the service method calls the doGet() method. Now inside the doGet() method use the getWriter() method of the response object and its returns the PrintWriter object, which helps us to write on the browser. To delete all the rows from our database table there is a need for the connection between the database and the java program. After the establishment of the connection with the database, fire a query for deleting all the rows in the database table. This query will be fired inside the prepareStatement() method of the Connection object and returns the PreparedStatement object. If the rows has been deleted from the database table then print the message "all rows are deleted" otherwise "no rows has been deleted". The code of the program is given below: import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletDeletingAllRowsFromTable extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root",

"admin"); PreparedStatement pst = connection.prepareStatement("delete fro m emp_sal"); int i = pst.executeUpdate(); if (i==0){ pw.println("All rows are deleted"); } else{ pw.println("no rows has been deleted"); } } catch(Exception e){ pw.println("The exception is " + e); } } } XML File for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletDeletingAllRowsFromTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletDeletingAllRowsFromTable</url-pattern> </servlet-mapping> </web-app> Table in the database before deletion: mysql> select * from emp_sal; +----------+-------+ | EmpName | salary | +----------+-------+

| zulfiqar | 15000 | | vinod | 12000 | +----------+-------+ 2 rows in set (0.00 sec) The output of the program is given below:

Table in the database after deletion: mysql> select * from emp_sal; Empty set (0.02 sec)

How to add a column in a table Consider a situation where the requirement of the client gets changed and you have asked to modify the structure of the table. In reality it is the work of the database administrator but as a Java programmer you should know how you can modify the structure of the table. The problem is that we have to add a new column to our database by using the java program. There is no need to get panic. What we simply need is to use a query for adding a new column in the database table. To get the desired result firstly we need to make a connection with our database. After connection has been established pass the query in the prepareStatement() for adding new column in the database. This method will return the PreparedStatement object. By the object of the PreparedStatement we will call the executeUpdate() which will tell the status of the table. The code of the example is given below: import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletAddingNewColumn extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement ("alter table emp_details add column sal int(5)"); int i = pst.executeUpdate(); if (i==1){ pw.println("Column has been added"); } else{ pw.println("No column has been added"); }

} catch(Exception e){ pw.println("The exception is " + e); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletAddingNewColumn</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletAddingNewColumn</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

How to delete a table in mysql Consider a situation where we need to delete a table from a database. To delete a table from the database firstly we need to make a connection with the database. When the connection has been established pass a query for deleting a table inside the prepareStatement() method and it will return the PreparedStatement object. Now call the method executeUpdate() of the PreparedStatement interface which will helps us to know the status of the program. The code of the program is given below: import import import import javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class ServletDeletingTable extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("drop tabl e emp_sal"); int i = pst.executeUpdate(); if (i==0){ pw.println("Table has been deleted"); } else{ pw.println("Table has not been deleted"); } } catch(Exception e){ pw.println("The exception is " + e); } }

} XML File for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletDeletingTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletDeletingTable</url-pattern> </servlet-mapping> </web-app> Table in the database before deletion: mysql> select * from emp_sa +----------+--------+ | EmpName | salary | +----------+--------+ | zulfiqar | 15000 | | vinod | 12000 | +----------+--------+ 2 rows in set (0.00 sec) The output of the program is given below:

Table in the database after deletion:

mysql> select * from emp_sal; ERROR 1146 (42S02): Table 'zulfiqar.emp_sal' doesn't exist

changing column name We make a table for storing some type of data. Table keeps the data in the form of rows and columns. Column indicates the field while row indicate the data of the field. Now consider a scenario where we have a table and it consists some data and a situation arises where there is a need to change the name of the column. As this is not the work of the programmer to change the name of the field, but as a programmer we should be aware how we can change the name of the column. The name of the column of the column will be changed by using the simple query. But before going into it we should see what are the initial steps to get the desired results. First of all make a database connection with your program. When the connection has been established pass a query for changing the column name in the preparedStatement(). This will return the PreparedStatement object. The code of the program is given below: import import import import javax.servlet.*; javax.servlet.http.*; java.io.*; java.sql.*;

public class ServletChangingColumnName extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("alter tabl e emp_details change firstname Name varchar(10)"); int i = pst.executeUpdate(); pw.println("The name of the column has been changed"); } catch(Exception e){

pw.println("The exception is " + e); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletChangingColumnName</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletChangingColumnName</url-pattern> </servlet-mapping> </web-app> The table in the database before changing of column name: mysql> select * from emp_details; +--------+----------+---------+----------+----------+-------+----------| userId | Name | surname | address1 | address2 | town | country | zipcode +--------+----------+---------+----------+----------+-------+----------| 73979 | zulfiqar | Ahmed | Moradabad | Delhi | Okhla | India | 110025 +--------+----------+---------+----------+----------+-------+----------1 row in set (0.00 sec) The output of the program is given below:

The table in the database after changing the column name: mysql> select * from emp_details; +--------+-----------+--------+-----------+----------+------+----------| userId | firstname | surname | address1 | address2 | town | country | zipcode +--------+-----------+--------+-----------+----------+------+----------| 73979 | zulfiqar | Ahmed | Moradabad | Delhi | Okhla | India | 110025 +--------+-----------+--------+-----------+----------+------+----------1 row in set (0.03 sec)

insert into statement in sql using servlets In this tutorial we are going to learn how we can insert a value from a html form in the table stored in the database. For inserting the values in the database table it is required to have a table in which we are going to insert the values. Now make one jsp page or html page where we will insert the values. In this program we have made one simple enquiry form which will get stored in the database table and when the data gets entered into the database then you will get a message. Make one submit button for inserting the values into the database. Firstly this values will go to the controller and retrieved the variables enter in the form by the method getParameter() method of the request object. Pass a query to insert the values retrieved from the html form. To set the values into the database use setString() method. To retrieve the values from the database use getString() method of the PreparedStatement object. The code of the program is given below: <html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windo ws-1252"> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> <title>New Page 1</title> </head> <body> <form method="POST" action="/sqlStatServlet/ServletUserEnquiryFor m"> <!--webbot bot="SaveResults" UFile="fpweb:///_private/form_results.txt" S-Format="TEXT/CSV" S-Label-Fields="TRUE" --> <p>User Id:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="userId" size="20"></p> <p>First Name:&nbsp;&nbsp; <input type="text" name="firstname" size="20"></p> <p>Surname: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="surname" size="20"></p> <p>Address1:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text"

name="address1" size="20"></p> <p>Address2:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="address2" size="20"></p> <p>Town:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp; <input type="text" name="town" size="20"></p> <p>City:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb sp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="country" size="20"></p> <p>Zip code:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <inpu t type="text" name="zipcode" size="20"></p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;& nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="submit" value="Submit" name="B1"></p> </form> </body> </html> ServletUserEnquiryForm.java import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletUserEnquiryForm extends HttpServlet{ public void init(ServletConfig config) throws ServletException{ super.init(config); } /**Process the HTTP Get request*/ public void doPost(HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException{ String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection=null; ResultSet rs; res.setContentType("text/html"); PrintWriter out = res.getWriter(); //get the variables entered in the form String uId = req.getParameter("userId"); String fname = req.getParameter("firstname"); String sname = req.getParameter("surname");

String address1 = req.getParameter("address1"); String address2 = req.getParameter("address2"); String town = req.getParameter("town"); String county = req.getParameter("country"); String zipcode = req.getParameter("zipcode"); try { // Load the database driver Class.forName("org.gjt.mm.mysql.Driver"); // Get a Connection to the database connection = DriverManager.getConnection(connectionURL, "root", "admin"); //Add the data into the database String sql = "insert into emp_details values (?,?,?,?,?,?,?,?)"; PreparedStatement pst = connection.prepareStatement(sql); pst.setString(1, uId); pst.setString(2, fname); pst.setString(3, sname); pst.setString(4, address1); pst.setString(5, address2); pst.setString(6, town); pst.setString(7, county); pst.setString(8, zipcode); int numRowsChanged = pst.executeUpdate(); // show that the new account has been created out.println(" Hello : "); out.println(" '"+fname+"'"); pst.close(); } catch(ClassNotFoundException e){ out.println("Couldn't load database driver: " + e.getMessage()); } catch(SQLException e){ out.println("SQLException caught: " + e.getMessage()); } catch (Exception e){ out.println(e); } finally { // Always close the database connection. try { if (connection != null) connection.close(); } catch (SQLException ignored){ out.println(ignored); }

} } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletUserEnquiryForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletUserEnquiryForm</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: Login.html form for the data input:

The output of the input data:

join tables mysql using servlets In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. To join the tables firstly it is important to make a connection between the java class and the database. In our program we are using the MySql database. To join the table it is important to have those tables in our database. First of all make a class named ServletJoiningTables. The name of the class should be such that it becomes clear that what the program is going to do. The logic of the program will be written inside the doGet() method which takes two arguments HttpServletRequest and HttpServletResponse. call the method getWriter() of the PrintWriter class, which is responsible for writing the contents on the browser. Our priority is to join the two tables so pass a query in prepareStatement() method which will return the PreparedStatement object. The result will be displayed to you by the object of the PrintWriter class. The code of the program is given below: import import import import java.sql.*; java.io.*; javax.servlet.*; javax.servlet.http.*;

public class ServletJoiningTables extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("SELECT * FROM "+"emp_details"+" NATURAL JOIN "+"Emp_sal"); ResultSet rs = pst.executeQuery(); pw.println("UserId" + "\t\t" + "Name" + "\t\t" + "Salary"+"<br>");

while(rs.next()){ String id = rs.getString("userId"); String name = rs.getString("Name"); String sal = rs.getString("salary"); pw.println(id + "\t\t" + name + "\t\t" + sal + "<br>"); } } catch (Exception e){ pw.println("The statement is not executed"); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletJoiningTables</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletJoiningTables</url-pattern> </servlet-mapping> </web-app> Tables emp_details and emp_sal in the database: mysql> select * from emp_details; +--------+----------+---------+-----------+---------+-------+---------+--------+ | userId | Name | surname | address1 | address2 | town | country | zipcode | +--------+----------+---------+-----------+---------+-------+---------+--------+ | 73979 | zulfiqar | Ahmed | Moradabad | Delhi | Okhla | India | 110025

| +--------+----------+---------+-----------+---------+-------+---------+--------+ 1 row in set (0.00 sec) mysql> select * from emp_sal; +----------+--------+ | EmpName | salary | +----------+--------+ | zulfiqar | 15000 | | vinod | 12000 | +----------+--------+ 2 rows in set (0.00 sec) Here we are getting data from the two tables in the database by combining them. The output of the program is given below:

Natural Left Join using servlets In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. This join will be natural left join. To join the tables firstly it is important to make a connection between the java class and the database. In our program we are using the MySql database. To join the table in a natural left join manner it is important to have those tables in our database. First of all make a class named ServletNaturalJoiningTables. The name of the class should be such that it becomes clear that what the program is going to do. The logic of the program will be written inside the doGet() method which takes two arguments HttpServletRequest and HttpServletResponse. call the method getWriter() of the PrintWriter class, which is responsible for writing the contents on the browser. Our priority is to join the two tables so pass a query in prepareStatement() method which will return the PreparedStatement object. The result will be displayed to you by the object of the PrintWriter class. The code of the program is given below: import import import import java.sql.*; java.io.*; javax.servlet.*; javax.servlet.http.*;

public class ServletNaturalJoiningTables extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("SELECT * FROM "+"emp_details"+" NATURAL LEFT JOIN "+"emp_sal");

ResultSet rs = pst.executeQuery(); pw.println("UserId" + "\t" + "Firstname" + "\t" + "Salary"+"<br>"); while(rs.next()){ String id = rs.getString("userId"); String name = rs.getString("Name"); String sal = rs.getString("salary"); pw.println(id + "\t\t" + name + "\t\t" + sal + "<br>"); } } catch (Exception e) { pw.println("The statement is not executed"); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletNaturalJoiningTables</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletNaturalJoiningTables</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Natural Right Join using servlets In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. This join will be natural right join. To join the tables firstly it is important to make a connection between the java class and the database. In our program we are using the MySql database. To join the table in a natural right join manner, it is important to have those tables in our database. First of all make a class named ServletNaturalRightJoiningTables. The name of the class should be such that it becomes clear that what the program is going to do. The logic of the program will be written inside the doGet() method which takes two arguments HttpServletRequest and HttpServletResponse. call the method getWriter() of the PrintWriter class, which is responsible for writing the contents on the browser. Our priority is to join the two tables so pass a query in prepareStatement() method which will return the PreparedStatement object. The result will be displayed to you by the object of the PrintWriter class. The code of the program is given below: import import import import java.sql.*; java.io.*; javax.servlet.*; javax.servlet.http.*;

public class ServletNaturalRightJoiningTables extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("SELECT * FROM "+"emp_details"+" NATURAL RIGHT JOIN "+"emp_sal");

ResultSet rs = pst.executeQuery(); pw.println("userId" + "\t" + "Firstname" + "\t" + "salary"+"<br>"); while(rs.next()){ String id = rs.getString("userId"); String name = rs.getString("Name"); String sal = rs.getString("salary"); pw.println(id + "\t\t" + name + "\t\t" + sal + "<br>"); } } catch (Exception e) { pw.println("The statement is not executed"); } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>ServletNaturalRightJoiningTables</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/ServletNaturalRightJoiningTables</url-pattern> </servlet-mapping> </web-app> The output of the program is given below:

Difference between Servlet 2.4 and Servlet 2.5 Features of Servlet 2.4 1. Upgraded supports for Http, J2SE, and J2EE: Servlet 2.4 depends on Http1.1 and J2SE 1.3. 2. Additional ServletRequest methods : In Servlet 2.4 four new methods are added in the ServletRequest o getRemotePort(): It returns the IP source port of the client. o getLocalName(): It returns the host name on which the request was recieved. o getLocalAddr(): It returns the IP address on which the request was recieved. o getLocalPort(): It returns the IP port number. 3. New Support for internationalization and charset choice: For the support of internationization Servlet 2.4 has added to new methods in the ServletReponse interface. o setCharacterEncoding(String encoding): The purpose of this method is to set the response's character encoding. This method helps us to pass a charset parameter to setContentType(String) or passing a Locale to setLocale(Locale). We can now avoid setting the charset in the setContentType("text/html;charset=UTF-8") as setCharacterEncoding() methods pairs with the preexisting getCharacterEncoding() method to manipulate and view the response's character encoding. getContentType(): It is responsible for returning the response's content type. The content type can be dynamically set with a combination of setContentType(), setLocale(), and setCharacterEncoding() calls, and the method getContentType() provides a way to view the generated type string. 4. New features has been added in RequestDispatcher: In Servlet 2.4 five new request attributes has been added to provide the extra information during a RequestDispatcher forward() call. This features has been added is Servlet 2.4 to know the true original request URI. The following request attributes are: o javax.servlet.forward.request_uri o javax.servlet.forward.context_path o javax.servlet.forward.servlet_path o javax.servlet.forward.path_info o javax.servlet.forward.query_string
o

5. SingleThreadModel interface has been deprecated: In Servlet 2.4 the SingleThreadModel interface has been deprecated. 6. HttpSession details and interaction with logins has been clarified: The new method HttpSession.logout() has been added in the Servlet 2.4. Now session allows zero or negative values in the <session-timeout> element to indicate sessions should never time out. If the object in the session can't be serialized in a distributed environment then it must throw an IllegalArgumentException. 7. Welcome file behavior and Classloading has been clarified: In servlet 2.4 welcome file can be servlets. 8. The web.xml file now uses XML Schema: Version 2.4 servers must still accept the 2.2 and 2.3 deployment descriptor formats, but all new elements are solely specified in Schema.

Features of Servlet 2.5 This version has been released on September 26, 2005 by the Sun MicroSystems. It is not necessary that all web servers and application servers support the features of Servlet 2.5. Still most of the popular containers like Tomcat 5.5 and JBoss 4.0 still support Servlet 2.4. The list of the added features is given below: 1. Dependency on J2SE 5.0: The minimum platform requirement for Servlet2.5 is JDK 1.5. Servet2.5 can't be used in versions below that JDK1.5. All the available features of Jdk1.5 like generics, autoboxing, an improved for loop etc, etc are guaranteed available to Servlet2.5 programmers. 2. Support For annotations: Annotations provide a mechanism for decorating java code constructs (classes, methods, fields, etc.) with metadata information. Annotations are mark code in such a way that code processors may alter their behavior based on the metadata information. 3. Several web.xml convenience: Servlet 2.5 introduces several small changes to the web.xml file to make it more convenient to use. For example while writing a <filter-mapping>, we can now use a asterisk in a <servlet-name> which will represent all servlets as well as Jsp. Previously we used to do

<filter-mapping> <filter-name>FilterName</filter-name> <servlet-name>FilterName</servlet-name> </filter-mapping> Now, <filter-mapping> <filter-name>FilterName</filter-name> <servlet-name>*</servlet-name> </filter-mapping> Previously in <servlet-mapping> or <filter-mapping> there used to be only one <url-pattern>, but now we can have multiple <url-pattern>, like <servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/abc/*</url-pattern> <url-pattern>/abc/*</url-pattern> </servlet-mapping> Apart from these changes, many more facilities added in web.xml. 4. A Handful of removed restrictions: Servlet 2.5 removed a few restrictions around error handling and session tracking. Now it has removed the restriction that the <error-page> could not call the setStatus() method to alter the error code that triggered them. In session tracking, Servlet 2.5 eased a rule that a servlet called by RequestDispatcher include() couldn't set response headers. 5. Some edge case clarifications: : The servlet2.4 specification says that before calling request.getReader() we must call request.setCharacterEncoding(). However there is no such clarification given why it is so. It has been described properly in Servlet 2.5.

Get And Post Method of Http GET The Get is one the simplest Http method. Its main job is to ask the server for the resource. If the resource is available then then it will given back to the user on your browser. That resource may be a HTML page, a sound file, a picture file (JPEG) etc. We can say that get method is for getting something from the server. It doesn't mean that you can't send parameters to the server. But the total amount of characters in a GET is really limited. In get method the data we send get appended to the URL so whatever you will send will be seen by other user so can say that it is not even secure. POST The Post method is more powerful request. By using Post we can request as well as send some data to the server. We use post method when we have to send a big chunk of data to the server, like when we have to send a long enquiry form then we can send it by using the post method. There are few more rarely used http methods including HEAD, PUT, TRACE, DELETE, OPTIONS and CONNECT.

Servlets Links 1. Java Servlet Technology: Servlets are the Java platform technology of choice for extending and enhancing Web servers. Servlets provide a componentbased, platform-independent method for building Web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server- and platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls and receive all the benefits of the mature Java language, including portability, performance, reusability, and crash protection.Today servlets are a popular choice for building interactive Web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually a component of Web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others. 2. Servlet Essential: This document explains the concepts of Java Servlets and provides a step-by-step tutorial for writing HTTP Servlets with complete source code for the example Servlets. The tutorial and the other chapters cover all facets of Servlet programming from a simple "Hello World" Servlet to advanced Servlet features like session tracking and Cookies. There are also appendices on compiling and running Servlets. The reader is assumed to have some basic knowledge of HTML and Java programming. 3. What is servlet: Servlets are modules of Java code that run in a server application (hence the name "Servlets", similar to "Applets" on the client side) to answer client requests. Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP and the word "Servlet" is often used in the meaning of "HTTP Servlet". Typical uses for HTTP Servlets include: Processing and/or storing data submitted by an HTML form. Providing dynamic content, e.g. returning the results of a database query to the client. Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts

for many concurrent customers and maps every request to the right customer. 4. Inter Servlet Communication: Servlets are not alone in a Web Server. They have access to other Servlets in the same Servlet Context (usually a Servlet directory), represented by an instance of javax.servlet.ServletContext. The ServletContext is available through the ServletConfig object's getServletContext method.A Servlet can get a list of all other Servlets in the Servlet Context by calling getServletNames on the ServletContext object. A Servlet for a known name (probably obtained through getServletNames) is returned by getServlet. Note that this method can throw a ServletException because it may need to load and initialize the requested Servlet if this was not already done.After obtaining the reference to another Servlet that Servlet's methods can be called. Methods which are not declared in javax.servlet.Servlet but in a subclass thereof can be called by casting the returned object to the required class type.Note that in Java the identity of a class is not only defined by the class name but also by the ClassLoader by which it was loaded. Web servers usually load each Servlet with a different class loader. This is necessary to reload Servlets on the fly because single classes cannot be replaced in the running JVM. Only a ClassLoader object with all loaded classes can be replaced. 5. Servlet mailing list: Servlet mailing lists are one of the best sources for up-to-theminute information about servlets and related technologies. This page lists the mailing lists you may want to join, with links for more information and to archives. Servlets.com offers three different mailing lists you can join to be notified when important content is added to the site. The first is servlets-announce, an announcement list. It's very low traffic. We post to the list only for major changes. The other two are weblog lists, for those interested in Jason Hunter's weblog so they can be notified when new entries are added. The first list, jhunter-blog, sends messages immediately when a new entry is added (about one per day). The second, jhunterblogweekly, sends one message per week for all entries during that week. For simplicity the mailing lists is not broken out by category, but posts are formatted for easy mail filtering per category. 6. Servlet ISPs: These days it seems there are servlet engines for nearly every web server, and now we're seeing servlets commonly offered as core value-add for Internet Service Providers (ISPs) and Web

Hosting companies. The megacorp ISPs and Hosting companies still don't offer servlets, though, probably because it's not something Joe Consumer cares about. Also because to host servlets effectively and efficiently requires a bit of expertise. That makes finding a good servlet provider somewhat challenging. On this page we try to help you on that endeavor by keeping track of all the ISPs that are known to host servlets. For each ISP we provide location and contact information, a short summary, and user reviews. The reviews should help you find out how the ISP you're looking at compares to others in terms of features, reliability, support, and overall score. Feel free to add one of your own. 7. Java Servlet: Over the past few years, Java servlets have taken the server-side programming community by storm. Now, with the introduction of Version 2.3 of the Servlet API, servlets are taking Java to a new level of software development for the Web. Servlets offer a fast, powerful, portable environment for creating dynamic web content. They can execute within the web server's process space and they persist between invocations, which gives them tremendous performance benefits over other solutions. Servlets have full access to the various Java APIs as well as third-party component classes, and are an integral part of the Java 2 Enterprise Edition (J2EE). Best of all, servlets are portable among operating systems and among servers-with servlets you can "write once, serve anywhere." 8. Oreilly servelt: The com.oreilly.servlet package is the "must have" class library for servlet developers. There are classes to help servlets parse parameters, handle file uploads, generate multipart responses (server push), negotiate locales for internationalization, return files, manage socket connections, and act as RMI servers, as well as a class to help applets communicate with servlets. Since the first edition, there are also new classes to help servlets send email messages, cache responses, and auto-detect servlet API support. The latest version is available online (with javadoc documentation) for download from http://www.servlets.com. Why did I write these classes? They started out as chapter examples in my book Java Servlet Programming being published by O'Reilly & Associates. Then one happy day I recognized they could, with a little modification, live on their own as reusable utility classes. That day, or maybe a few procrastinating days later, com.oreilly.servlet was born. 9. Jetty Java Servlet: Jetty is a 100% Java HTTP Server and Servlet Container. This means that you do not need to configure and run a separate web

server (like Apache) in order to use java, servlets and JSPs to generate dynamic content. Jetty is a fully featured web server for static and dynamic content. Unlike separate server/container solutions, this means that your web server and web application run in the same process, without interconnection overheads and complications. Furthermore, as a pure java component, Jetty can be simply included in your application for demonstration, distribution or deployment. Jetty is available on all Java supported platforms. 10. Servlet 2.4: Servlet 2.4 lacks some of the fireworks of past releases. Servlet 2.2 introduced the notion of self-contained Web applications. Servlet 2.3 added the power of filters and filter chains. Servlet 2.4, while adding several interesting features, has no superstars and spends more time polishing and clarifying the features that came beforea tying up of loose ends. This work's effect is that servers faithfully implementing 2.4 will be more interoperable than any past servers. But don't let me imply there's nothing new in Servlet 2.4! Here's a list of what's new: Servlets now require HTTP/1.1 and J2SE (Java 2 Platform, Standard Edition) 1.3, and can work with J2EE 1.4 ServletRequest has new methods to observe the client connection New support for internationalization and charset choice RequestDispatcher has new features and clarifications New ServletRequest listener classes and methods A deprecated SingleThreadModel HttpSession details and interaction with logins has been clarified Classloading and welcome-file behavior has been clarified The web.xml file now uses XML Schema and has added a slew of new elements 11. Java Servlet Programming: A few years ago, the hype surrounding applets put Java on the map as a programming language for the Web. Today, Java servlets stand poised to take Java to the next level as a Web development language. The main reason is that servlets offer a fast, powerful, portable replacement for CGI scripts. The Java Servlet API, introduced as the first standard extension to Java, provides a generic mechanism to extend the functionality of any kind of server. Servlets are most commonly used, however, to extend Web servers, performing tasks traditionally handled by CGI programs. Web servers that can support servlets include: Apache, Netscape's FastTrack and Enterprise Servers, Microsoft's IIS, O'Reilly's WebSite, and JavaSoft's Java Web Server. The beauty of servlets is that they execute within the Web server's process space and they persist between

invocations. This gives servlets tremendous performance benefits over CGI programs. Yet because they're written in Java, servlets are far less likely to crash a Web server than a C-based NSAPI or ISAPI extension. Servlets have full access to the various Java APIs and to third-party component classes, making them ideal for use in communicating with applets, databases, and RMI servers. Plus, servlets are portable between operating systems and between servers -- with servlets you can "write once, serve everywhere." 12. Generic Servlet : The GenericServlet class implements the Servlet interface and, for convenience, the ServletConfig interface. Servlet developers typically subclass GenericServlet, or its descendent HttpServlet, unless the servlet needs another class as a parent. (If a servlet does need to subclass another class, the servlet must implement the Servlet interface directly. This would be necessary when, for example, RMI or CORBA objects act as servlets.) The GenericServlet class was created to make writing servlets easier. It provides simple versions of the life-cycle methods init and destroy, and of the methods in the ServletConfig interface. It also provides a log method, from the ServletContext interface. The servlet writer must override only the service method, which is abstract. Though not required, the servlet implementer should also override the getServletInfo method, and will want to specialize the init and destroy methods if expensive servlet-wide resources are to be managed. 13. Servlet 2.3 Modal: introduced the changes coming in the Servlet API 2.3 and gave a short tutorial on the new servlet filter model. In this follow-on article, I'll dig deeper into servlet filters and look at several filters you can download for free on the Web. For each filter, I'll examine what it does, how it works, and where you can get it. You can use this article in two ways: to learn about some filters that are useful out of the box, or as an aid in writing your own filters. I'll start off with some simple examples and then move on to more advanced ones. At the end, I'll show you a file upload filter I wrote to support multipart requests. 14. Servelt Filter: a filter is an object that can transform a request or modify a response. Filters are not servlets; they don't actually create a response. They are preprocessors of the request before it reaches a servlet, and/or postprocessors of the response leaving a servlet. As you'll see later in the examples, a filter can: Intercept a servlet's invocation before the servlet is called Examine a request before a servlet is called Modify the request headers and request data by providing a

customized version of the request object that wraps the real request Modify the response headers and response data by providing a customized version of the response object that wraps the real response Intercept a servlet's invocation after the servlet is called 15. How Servlet Container Work: This article explains how a simple servlet container works. There are two servlet container applications presented; the first one is made as simple as possible and the second is a refinement of the first. The sole reason I do not try to make the first container perfect is to keep it simple. More sophisticated servlet containers, including Tomcat 4 and 5, are discussed in other chapters of How Tomcat Works.Both servlet containers can process simple servlets, as well as static resources. You can use PrimitiveServlet, located in the webroot/ directory, to test this container. More complex servlets are beyond the capability of these containers, but you can learn how to build more sophisticated servlet containers in the How Tomcat Works book. 16. Servlet Best Practice: In the first of three excerpts on Servlet best practices from Java Enterprise Best Practices, learn how to effectively work with Servlets. Since their introduction in 1996, servlets have dominated the server-side Java landscape and have become the standard way to interface Java to the Web. They are the foundation technology on which Java developers build web applications and, increasingly, web services. This chapter discusses best practices for servlet-based development and deployment. 17. Learning Servlet: A Servlet is an application program you write that runs on a web server. The servlet accepts and processes web requests through CGI (Common Gateway Interface) get or post requests. How it Works: A Servlet is actually a Java class you write that extends the javax.servlet.HttpServlet class. Here's how your servlet works: A Web server receives an HTTP GET or POST request from a browser (or other TCP client). The web server directs the HTTP request to the servlet engine (in the same way that direct CGI requests). If your servlet is not already in memory, the servlet engine loads it and initializes it. The servlet engine then encapsulates the HTTP request into a class called HttpServletRequest and delivers it to your servlet's doPost or doGet method. Your servlet responds by writing HTML into HttpServletResponse

which is sent back to the web server and delivered back to the TCP client. 18. Calendar Servlet 3.0: It is a Java servlet implements calendar. You can use it as a standard calendar system, for booking some resources etc. Calendar supports WAP/WML so you can use it even from your mobile phone. Calendar's users may by notified by e-mail about schedule changes. Calendar supports file based persistence your data will be saved in the flat file (files) or database based persistence. 1.How to Uses it: a) copy calendarPackage.jar into your WEB-INF/lib directory. b) define servlet in your web.xml file. <servlet> <servlet-name>CalendarServlet</servlet-name> <servlet-class>com.jsos.calendar.CalendarServlet</servletclass> </servlet> c) define a mapping for Calendar servlet in your web.xml file <servlet-mapping> <servlet-name>CalendarServlet</servlet-name> <url-pattern>/servlet/CalendarServlet</url-pattern> </servlet-mapping> 19. Java Chat Servlet: I Here is the jzChat V1.0 servlet (free). This servlet performs a 100% HTML/JavaScript chatroom. Guest users just have to enter a nickname for chatting. They can choose chat's look&feel. Private messages are allowed. Root user chooses chatroom's name and subject. Root also controls the chatroom : max. users, open, close, transcript, list or kickoff users, clear blacklist features are available. jzChat is protected against cross scripting attacks. Only root user could use "direct-HTML". Note that this chat could run in both framed and non-framed mode. 20. Java Servlet WiKipedia: The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to dynamic web content technologies such as CGI, PHP or ASP. Servlets can maintain state across many server transactions by using HTTP cookies, session variables or URL rewriting. The Servlet API, contained in the javax.servlet package hierarchy, 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.

Select Color In this program we are going to selected the various color and on the basis of the selection the output will be displayed to the user. To make this program firstly we need to make one html page. Inside the page we will have one select option in which we will have our colors. We will also have a submit, clicking on which the values we have entered will be transferred to the server. On the server we will create a session. The values which we have entered in the html form will be retrieved by the getParameterValues() of the request object. It returns the array of String. We will check the condition if there is any session available or not. If yes then we will set the attribute by using the setAttribute() method of the HttpSession object. The attribute we have set will be retrieved by the getAttribute method of the HttpSession object in the next page and the value will be displayed on the browser by the PrintWriter object. The code of the program is given below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO8859-1"> <title>Select the list of colors</title> </head> <body> <form action = "/ServletProject/ColorPage"> <select name = "colors" size = 5 multiple> <option selected>Green</option> <option>Red</option> <option>Yellow</option> <option>Blue</option> <option>Black</option> </select> <input type = "submit" name = "submit"> </form> </body> </html>

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * Servlet implementation class for Servlet: ColorPage * */ public class ColorPage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public ColorPage() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet (HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(); String colors[] = request.getParameterValues("colors"); if(session!=null) { session.setAttribute("color",colors); session.setMaxInactiveInterval(60); } pw.println("<html><body bgcolor =cyan>"); for(int i = 0; i<colors.length; i++) { pw.println("The selected colors are" + colors[i]+ "<br>"); } pw.println("<form action = /ServletProject/GetColors>"); pw.println("<input type = submit name= submit)>");

pw.println("</form></body></html>"); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * Servlet implementation class for Servlet: GetColors * */ public class GetColors extends HttpServlet { /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public GetColors() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet( HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(false); if(session == null)

{ pw.println("No session is available"); pw.println("We are creating a session for you. Creating....."); session = request.getSession(); } else { String getColors[] = (String[])session.getAttribute("color"); pw.println("<html><body bgcolor = cyan>"); for(int i= 0; i<getColors.length;i++) { pw.println("The selected colors are " + getColors[i] + "<br>"); } pw.println("<html><body>"); } } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost( HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } } The output of the program is given below:

sendRedirect In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not. If not then the servlet decides that the request can be handle by other servlet or jsp. Then the servlet calls the sendRedirect() method of the response object and sends back the response to the browser along with the status code. Then the browser sees the status code and look for that servlet which can now handle the request. Again the browser makes a new request, but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser. The URL will have the address of the new servlet. In all this process the client is unaware of the processing. Servlet Redirect forces the browser to do work.

Send Redirect in Servlet When we want that someone else should handle the response of our servlet, then there we should use sendRedirect() method. In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not. If not then the servlet decides that the request can be handle by other servlet or jsp. Then the servlet calls the sendRedirect() method of the response object and sends back the response to the browser along with the status code. Then the browser sees the status code and look for that servlet which can now handle the request. Again the browser makes a new request, but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser. In all this process the client is unaware of the processing. The output of the program is given below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO8859-1"> <title>Redirecting the page</title> </head> <body> <form action = "/ServletProject/SendRedirect" method = "post"> <tr> <td>Enter your name :</td> <td><input type = "text" name = "username"></td> </tr><br> <tr> <td>Enter your password :</td> <td><input type = "password" name = "password"></td> </tr><br> <tr> <td><input type = "submit" name = "submit"></td> </tr> </form> </body>

</html>

import import import import import

java.io.*; java.io.IOException; javax.servlet.ServletException; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class SendRedirect extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public SendRedirect() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String name = request.getParameter("username"); String password = request.getParameter("password"); if(name.equals("James")&& password.equals("abc")) { response.sendRedirect("/ServletProject/ValidUser"); } else { pw.println("u r not a valid user"); } } }

import import import import import

java.io.*; java.io.IOException; javax.servlet.ServletException; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

/** * Servlet implementation class for Servlet: ValidUser

* */ public class ValidUser extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public ValidUser() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter pw = response.getWriter(); pw.println("Welcome to roseindia.net<br>"); pw.println("how are you"); } } The code of the program is given below:

Random Redirector In this program we are going to make such a servlet which will be responsible to select a site randomly from the list of sites you have entered. Note that the selection of the site will be randomly. To make such a servlet firstly make a class named SiteSelectionServlet. Use the Vector class where you can store the sites which you want to select randomly and the other class Random which will helps you to select the site randomly. The code of the program is given below:

import import import import

java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class SiteSelectionInServlet extends HttpServlet { Vector sites = new Vector(); Random random = new Random(); public void init() throws ServletException { sites.addElement("http://www.roseindia.net"); sites.addElement("http://www.java.sun.com"); sites.addElement("http://www.rediffmail.com"); sites.addElement("http://www.yahoo.com"); sites.addElement("http://www.indiatimes.com"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int siteIndex = Math.abs(random.nextInt()) % sites.size(); String site = (String)sites.elementAt(siteIndex); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site);

} } The output of the program is given below:

Note: The selection will be random.

Servlet Context ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it. The information in the ServletContext will be common to all the components. Remember that each servlet will have its own ServletConfig. The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application. Web application initialization: 1. First of all the web container reads the deployment descriptor file and then creates a name/value pair for each <context-param> tag. 2. After creating the name/value pair it creates a new instance of ServletContext. 3. Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters. 4. The servlet and jsp which are part of the same web application can have the access of the ServletContext. The Context init parameters are available to the entire web application not just to the single servlet like servlet init parameters. How can we do the mapping of the Context init parameters in web.xml <servlet> <servlet-name>Mapping</servlet-name> <servlet-class>ContextMapping</servlet-class> </servlet> <context-param> <param-name>Email</param-name> <param-value>admin@roseindia.net</param-value> </context-param> In the servlet code we will write this as ServletContext context = getServletContext(); pw.println(context.getInitParameter("Email");

Thanks Jyoti, We have corrected the typo error.

Servlet Context Listener ServletContextListener is a interface which contains two methods: 1. public void contextInitialized(ServletContextEvent event) 2. public void contextDestroyed(ServletContextEvent event) When we implement any interface then we have to implement its all methods. This listener will help a application to start and shutdown the events. How the ServletContextListener is useful: 1. ServletContextListener is notified when the context is initialized. a). ServletContextListener gets the context init parameters from the ServletContext. b). It stores the database connection as an attribute, so that the other components in the web application can access it. 2. It will be notified when the context is destroyed. It closes the database connection.

ServletContextListener example Before going into the details of ServletContextListener we should understand what is ServletContext. ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it. The information in the ServletContext will be common to all the components. Remember that each servlet will have its own ServletConfig. The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application. ServletContextListener is a interface which contains two methods: 1. public void contextInitialized(ServletContextEvent event) 2. public void contextDestroyed(ServletContextEvent event) When we implement any interface then we have to implement its all methods. This listener will help a application to start and shutdown the events. How the ServletContextListener is useful: 1. ServletContextListener is notified when the context is initialized. a). ServletContextListener gets the context init parameters from the ServletContext. b). It stores the database connection as an attribute, so that the other components in the web application can access it. 2. It will be notified when the context is destroyed. It closes the database connection. The code of the program is given below:

import javax.servlet.*; import javax.servlet.http.*; public class MyServletContextListener implements ServletContextListener{ public void contextInitialized(ServletContextEvent event)

{ ServletContext sc = event.getServletContext(); String whatType = sc.getInitParameter("typeSelected"); Furniture f = new Furniture(whatType); sc.setAttribute("furniture", f); } public void contextDestroyed(ServletContextEvent event) { } }

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ListenerTester extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public ListenerTester() { super(); } public void doGet(HttpServletRequest request, } HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("context attributes set by the listener <br>"); Furniture f = (Furniture)getServletContext().getAttribute("furniture"); pw.println("The furniture you have selected is :" + f.getTypeSelected()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } } The output of the program is given below:

ServletContextAttributeListener As we know that the javax.servlet.ServletContext interface used to represents a Servlet's view of the web application it belongs to. All the servlets in an application can access the SevletContext. It means that we keep such information in the servlet context which are common to all the servlets. The elements of the ServletContext are stored in web.xml file. Whenever the container gets start it reads the web.xml file. Occurrence of <context-param> tag should appear before the Servlet tags. ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it. The information in the ServletContext will be common to all the components. Remember that each servlet will have its own ServletConfig. The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application. The listener ServletContextAttributeListener is an interface and extends the java.util.EventListener class. This listener come into existence when this interface receives notifications of changes to the attribute list on the servlet context of a web application. Remember one thing before gets notified by the container, you should make sure that the implementation class is configured in deployment descriptor for the web application. This listener is used when we want to know when a attribute has been added in a context, when a attribute has been removed and when it is replaced by another attribute. We can also say that this attribute is used when the developer is interested to be notified when the context attribute changes. Now you may be wondering what is an attribute. An attribute is an object set or you can simply say that it is name/value pair where the name refers to a String and a value refers to the Object. javax.servlet.ServletContextAttributeListener interface has following methods: 1. attributeAdded(ServletContextAttributeEvent event): It notifies whenever a new attribute is added to the servlet context. 2. attributeRemoved(ServletContextAttributeEvent event): It notifies whenever the attribute is removed from the servlet context.

3. attributeReplaced(ServletContextAttributeEvent event): It notifies whenever the attribute gets replaced on the servlet context. In the above methods you can see that we have used ServletContextAttributeEvent class as a parameter to the above methods. This class is a event class which is used for notifications when the changes are made to the attributes of ServletContext in an application. The class ServletContextAttributeEvent has two methods: 1. getName() : This method returns the name of the attribute that has been changed on the ServletContext. 2. getValue(): This method will return the value of the attribute that has been added, removed or replaced by other attribute.

HttpSessionListener Before going into the details of the SessionListener we should firstly know about the sessions. As we know that Http protocol is a "stateless" protocol. The term stateless means that it can't persist the information. It can't remember the previous transactions. Whenever a client makes a request for any resources to the server, the server receives the request and processes the request and sends back the response. After sending the response the server closes the connection and forgets about the previous requests. Whenever a client sends any request to the server, the server treats each request as a new request. To remove this we have been provided the facility of the session. In session tracking whenever a client sends a request to the server then server creates a unique id for that request and sends back the unique id to the client along with the response object, now whenever a client sends a request to the server it also sends a unique id with it so that the server can know from where the request is coming. Listeners listen the events. Whenever any event occurs it is listened by the listener. The listener will be controller by the web servers. HttpSessionListener is an interface which extends java.util.EventListener class. The main purpose of this listener is to notify whenever there is a change in the list of active sessions in a web application This interface has two methods: 1. sessionCreated(HttpSessionEvent event): It will notify when the session is created. 2. sessionDestroyed(HttpSessionEvent event): It will notify when the session gets invalidated. In the above methods we can see that we have used HttpSessionEvent as the parameter of both the methods. This class has only one method getSession() which returns the current session. The code of the program is given below: Make the entry of this file in the deployment descriptor file that is web.xml import javax.servlet.*; import javax.servlet.http.*;

public class MySessionListener implements HttpSessionListener { public MySessionListener() { } public void sessionCreated(HttpSessionEvent sessionEvent) { // Get the session HttpSession session = sessionEvent.getSession(); try { System.out.println("Session created: "+session); session.setAttribute("foo","bar"); } catch (Exception e) { System.out.println("Error in setting session attribute: " }+ e.getMessage()); } } public void sessionDestroyed(HttpSessionEvent sessionEvent) { // Get the session that was invalidated HttpSession session = sessionEvent.getSession(); // Log a message System.out.println("Session invalidated: "+session); System.out.println("The name is: " + session.getAttribute("foo")); } }

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ServletSessionListener extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session= request.getSession(); String str = (String)session.getAttribute("foo"); pw.println("The name is " + str); } }

The output of the program is given below:

HttpSessionListener example Before going into the details of the SessionListener we should firstly know about the sessions. As we know that Http protocol is a "stateless" protocol. The term stateless means that it can't persist the information. It can't remember the previous transactions. Whenever a client makes a request for any resources to the server, the server receives the request and processes the request and sends back the response. After sending the response the server closes the connection and forgets about the previous requests. Whenever a client sends any request to the server, the server treats each request as a new request. To remove this we have been provided the facility of the session. In session tracking whenever a client sends a request to the server then server creates a unique id for that request and sends back the unique id to the client along with the response object, now whenever a client sends a request to the server it also sends a unique id with it so that the server can know from where the request is coming. Listeners listen the events. Whenever any event occurs it is listened by the listener. The listener will be controller by the web servers. HttpSessionListener is an interface which extends java.util.EventListener class. The main purpose of this listener is to notify whenever there is a change in the list of active sessions in a web application This interface has two methods: 1. sessionCreated(HttpSessionEvent event): It will notify when the session is created. 2. sessionDestroyed(HttpSessionEvent event): It will notify when the session gets invalidated.

In the above methods we can see that we have used HttpSessionEvent as the parameter of both the methods. This class has only one method getSession() which returns the current session. The code of the program is given below: Make the entry of this file in the deployment descriptor file that is web.xml import javax.servlet.*; import javax.servlet.http.*; public class ListenerSession implements HttpSessionListener { public ListenerSession() { } public void sessionCreated(HttpSessionEvent sessionEvent) { // Get the session that was created HttpSession session = sessionEvent.getSession(); // Store something in the session, and log a message try { System.out.println("Session created: "+session); session.setAttribute("dog", "labrador"); session.setAttribute("name", "Diana"); } catch (Exception e) { System.out.println("Error in setting session attribute: " + e.getMessage()); } } public void sessionDestroyed(HttpSessionEvent sessionEvent) { // Get the session that was invalidated HttpSession session = sessionEvent.getSession(); // Log a message System.out.println("Session invalidated: "+session); System.out.println("The breed of the dog is: " + session.getAttribute("dog")); System.out.println("The name of the dog is : " + session.getAttribute("name")); } }

import javax.servlet.*; import javax.servlet.http.*;

import java.io.*; public class ServletListenerSession extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session= request.getSession(); String str = (String)session.getAttribute("dog"); String dogName = (String)session.getAttribute("name"); pw.println("The breed of the dog is " + str); pw.println("The name of the dog is " + dogName); } } The output of the example is given below:

HttpSessionAttributeListener As we know that the Session is used to maintain the session between request. Session object is responsible to hold the conversational state across multiple requests. The listener HttpSessionAttributeListener is an interface and extends the java.util.EventListener class. This listener will be called by the container whenever there there will be change to the attribute list on the servlet session of a web application. This listener is used when we want to know when a attribute has been added in a session, when a attribute has been removed and when it is replaced by another attribute. We can also say that this attribute is used when the developer is interested to be notified when the session attribute changes. Now you may be wondering what is an attribute. An attribute is an object set or you can simply say that it is name/value pair where the name refers to a String and a value refers to the Object. javax.servlet.http.HttpSessionAttributeListener interface has following methods: 1. attributeAdded(HttpSessionBindingEvent event): It notifies whenever a new attribute is added to the servlet session. 2. attributeRemoved(HttpSessionBindingEvent event): It notifies whenever the attribute is removed from the servlet session. 3. attributeReplaced(HttpSessionBindingEvent event): It notifies whenever the attribute gets replaced on the servlet session. In the above methods you can see that we have used HttpSessionBindingEvent class as a parameter to the above methods. This class is a event class which is used for notifications when the changes are made to the attributes of in a session. The class HttpSessionBindingEvent has two methods: 1. getName() : This method returns the name of the attribute that has been change in the session. 2. getValue(): This method will return the value of the attribute that has been added, removed or replaced by other attribute. 3. getSession(): This method will return the session that has been changed.

HttpSessionAttributeListener Example As we know that the Session is used to maintain the session between request. Session object is responsible to hold the conversational state across multiple requests. The listener HttpSessionAttributeListener is an interface and extends the java.util.EventListener class. This listener will be called by the container whenever there there will be change to the attribute list on the servlet session of a web application. This listener is used when we want to know when a attribute has been added in a session, when a attribute has been removed and when it is replaced by another attribute. We can also say that this attribute is used when the developer is interested to be notified when the session attribute changes. Now you may be wondering what is an attribute. An attribute is an object set or you can simply say that it is name/value pair where the name refers to a String and a value refers to the Object. javax.servlet.http.HttpSessionAttributeListener interface has following methods: 1. attributeAdded(HttpSessionBindingEvent event): It notifies whenever a new attribute is added to the servlet session. 2. attributeRemoved(HttpSessionBindingEvent event): It notifies whenever the attribute is removed from the servlet session. 3. attributeReplaced(HttpSessionBindingEvent event): It notifies whenever the attribute gets replaced on the servlet session. In the above methods you can see that we have used HttpSessionBindingEvent class as a parameter to the above methods. This class is a event class which is used for notifications when the changes are made to the attributes of in a session. The class HttpSessionBindingEvent has two methods: 1. getName() : This method returns the name of the attribute that has been change in the session. 2. getValue(): This method will return the value of the attribute that has been added, removed or replaced by other attribute. 3. getSession(): This method will return the session that has been changed. The code of the program is given below:

import javax.servlet.*; import javax.servlet.http.*; public class SessionAttributeListenerExample implements HttpSessionAttributeListener { public void attributeAdded(HttpSessionBindingEvent sessionBindingEvent) { // Get the session HttpSession session = sessionBindingEvent.getSession(); // Log some information System.out.println("[SessionAttr] "+new java.util.Date()+ " Attribute added, session "+session+": " +sessionBindingEvent.getName()+"="+ sessionBindingEvent.getValue()); } public void attributeRemoved(HttpSessionBindingEvent sessionBindingEvent) { // Get the session HttpSession session = sessionBindingEvent.getSession(); System.out.println(new java.util.Date()+" Attribute removed, session "+session+": "+sessionBindingEvent.getName()); } public void attributeReplaced(HttpSessionBindingEvent sessionBindingEvent) { // Get the session HttpSession session = sessionBindingEvent.getSession(); // Log some information System.out.println(new java.util.Date()+" Attribute replaced, session "+session+": "+sessionBindingEvent .getName()+"="+sessionBindingEvent.getValue()); } }

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class AttributeSessionForSession extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(); session.setAttribute("dog", "Labrador"); session.setAttribute("name", "moti"); session.setAttribute("age","5"); String str1 = (String)session.getAttribute("dog"); pw.println("The breed of the dog is " + str1); String str2 = (String)session.getAttribute("age"); pw.println("The age of the dog is " + str2); session.removeAttribute("name"); } } The output of the program is given below:

The output on the server will look like this:

httpsessionbindinglistener Before going into the details of the HttpSessionBindingListener we should firstly know about the sessions. As we know that Http protocol is a "stateless" protocol. The term stateless means that it can't persist the information. It can't remember the previous transactions. Whenever a client makes a request for any resources to the server, the server receives the request and processes the request and sends back the response. After sending the response the server closes the connection and forgets about the previous requests. Whenever a client sends any request to the server, the server treats each request as a new request. To remove this we have been provided the facility of the session. In session tracking whenever a client sends a request to the server then server creates a unique id for that request and sends back the unique id to the client along with the response object, now whenever a client sends a request to the server it also sends a unique id with it so that the server can know from where the request is coming. HttpSessionBindingListener is a interface which extends java.util.EventListener interface. The purpose of the this interface is to notify an object when it is bound to or unbound from a session. This interface has two methods: 1. valueBound(HttpSessionBindingEvent event): It notifies the object that is being bound to a session and is responsible for identifying the session. 2. valueUnBound(HttpSessionBindingEvent event): It notifies the object that is being unbound from a session and is responsible for identifying the session. In the above method we can see that we have used the class HttpSessionBindingEvent as a argument to the methods. The object is notified by an HttpSessionBindingEvent object This class has two methods: 1. getName(): It returns the name with which the object is bound or unbound from the session. 2. getSession(): This method returns the session to or from which the object is bound or unbound.

httpsessionbindinglistener example Before going into the details of the HttpSessionBindingListener we should firstly know about the sessions. As we know that Http protocol is a "stateless" protocol. The term stateless means that it can't persist the information. It can't remember the previous transactions. Whenever a client makes a request for any resources to the server, the server receives the request and processes the request and sends back the response. After sending the response the server closes the connection and forgets about the previous requests. Whenever a client sends any request to the server, the server treats each request as a new request. To remove this we have been provided the facility of the session. In session tracking whenever a client sends a request to the server then server creates a unique id for that request and sends back the unique id to the client along with the response object, now whenever a client sends a request to the server it also sends a unique id with it so that the server can know from where the request is coming. HttpSessionBindingListener is a interface which extends java.util.EventListener interface. The purpose of the this interface is to notify an object when it is bound to or unbound from a session. This interface has two methods: 1. valueBound(HttpSessionBindingEvent event): It notifies the object that is being bound to a session and is responsible for identifying the session. 2. valueUnBound(HttpSessionBindingEvent event): It notifies the object that is being unbound from a session and is responsible for identifying the session. In the above method we can see that we have used the class HttpSessionBindingEvent as a argument to the methods. The object is notified by an HttpSessionBindingEvent object This class has two methods: 1. getName(): It returns the name with which the object is bound or unbound from the session. 2. getSession(): This method returns the session to or from which the object is bound or unbound. The code of the program is given below:

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionBindingListenerExample extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the current session object, create one if necessary HttpSession session = req.getSession(); // Add a UserName session.setAttribute("name", new UserName(getServletContext())); out.println("This is the example of HttpSessionBindingListener"); } }

import javax.servlet.*; import javax.servlet.http.*; public class UserName implements HttpSessionBindingListener { ServletContext context; public UserName(ServletContext context){ this.context = context; } public void valueBound(HttpSessionBindingEvent event) { context.log("The value bound is " + event.getName()); } public void valueUnbound(HttpSessionBindingEvent event) { context.log("The value unbound is " + event.getName()); } } The output of the program is given below:

ServletRequestAttributeListener This listener is used when we want to know when a attribute has been added in a request, when a attribute has been removed and when it is replaced by another attribute. We can also say that this attribute is used when the developer is interested to be notified when the request attribute changes. Now you may be wondering what is an attribute. An attribute is an object set or you can simply say that it is name/value pair where the name refers to a String and a value refers to the Object. javax.servlet.ServletRequestAttributeListener interface has following methods: 1. attributeAdded(ServletRequestAttributeEvent event): It notifies whenever a new attribute is added to the servlet request. 2. attributeRemoved(ServletRequestAttributeEvent event): It notifies whenever the attribute is removed from the servlet request. 3. attributeReplaced(ServletRequestAttributeEvent event): It notifies whenever the attribute gets replaced on the servlet request. In the above methods you can see that we have used ServletRequestAttributeEvent class as a parameter to the above methods. This class is a event class which is used for notifications when the changes are made to the attributes of ServletRequest in an application. The class ServletRequestAttributeEvent has two methods: 1. getName() : This method returns the name of the attribute that has been changed on the ServletRequest. 2. getValue(): This method will return the value of the attribute that has been added, removed or replaced by other attribute.

Inserting Image in a database Table Consider a case where we want that along with the name of the person and its information, his image should also come with all these things. After going through this tutorial you can better understand the concept of inserting a image in the database table, so go through this example properly. To get the program working we need to use a doGet() method to write our business logic as it is server side programming so all the processing will be done by the container. First of all make a class named JdbcInsertImage, the name of the class should be such that the person can understand what the program is going to do. This class must extend the HttpServlet class which is an abstract method. Now inside the doGet() method call the method getWriter() of the class PrintWriter. To insert a image from our java program we need to make a connection between our java class and the MySql database which we are using. After the connection establishment we will pass a insertion query for the image in the prepareStatement() method of the Connection object which returns the PreparedStatement object. Note that the data type for the image we have used is mediumblob. It is case sensitive. As we have to insert an image file in our database so there is a need to use a File class of the java.io package. In the constructor of the File class pass the path of the file. To read the image file we will use FileInputStream class. To set the image in the database use the method setBinaryStream() of the PreparedStatement interface. If the image will be inserted in the database you will get the message "image has been inserted" otherwise "image is not inserted". The code of the program is given below:

import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class JdbcInsertImage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter();

String connectionURL = "jdbc:mysql://localhost:3306/roseindia"; java.sql.Connection connection=null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "root", "root"); PreparedStatement pst = connection.prepareStatement ("insert into image values(?,?)"); File file = new File("C:/apache-tomcat-5.5.20/webapps /mywork/grad_sm.gif"); FileInputStream fis = new FileInputStream(file); pst.setBinaryStream(1,fis,fis.available()); pst.setString(2, "Tim"); int i = pst.executeUpdate(); if(i!=0) { pw.println("image has been inserted"); } else { pw.println("image is not inserted"); } } catch (Exception e) { System.out.println(e); } } } The output of the program is given below:

Insert Image into Database Using Servlet This example illustrate the process of inserting image into database table using Servlet. This type of program is useful in social networking or HR application where it is necessary to save the uploaded photograph of the user. If the image is stored in the database you can easily retrieve using JDBC program. In the next section you will see a program to retrieve the image from database using Servlet. After retrieving the image from database you can display it on the browser. This type of program is really very useful, which makes your program very attractive. How to Compile Servlet program 1. Save your file ImageInsertInTable.java . 2. Open Command Prompt and set the class path so that it includes the servlet api jar file. The servlet api is available in servlet-api.jar file which you can take from tomcat's lib directory. 3. Map your servlet in web.xml file. Here is the mapping code that you can put in web.xml file: <servlet> <servletname>ImageInsertInTable</servle t-name> <servletclass>ImageInsertInTable</servlet -class> </servlet> <servlet-mapping> <servletname>ImageInsertInTable</servle t-name> <urlpattern>/ImageInsertInTable</urlpattern> </servlet-mapping> 4. Compile your servlet class file by using javac <file_name.java>. command prompt> javac ImageInsertInTable.java

5. Move the class file into WEB-INF/classes directory. 6. Run your program on the Browser by url-pattern which define in web.xml file. You should type http://localhost:8080/MyApplication/ImageInsertInTable in your browser to test the application. MySql Table Structure: Here is the table structure used to store the image into database. Please not the filed type used is blog. CREATE TABLE `pictures` ( `id` int(11) NOT NULL auto_increment, `image` blob, PRIMARY KEY (`id`) ) ImageInsertInTable.java import import import import java.sql.*; java.io.*; javax.servlet.*; javax.servlet.http.*;

public class ImageInsertInTable extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://192.168.10.59:3306/example" ; Connection con=null; try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection(connectionURL, "root", "root") ; PreparedStatement ps = con.prepareStatement("INSERT INTO pictu res VALUES(?,?)"); File file = new File("C:/apache-tomcat-

6.0.16/webapps/CodingDiaryExample/images/5.jpg"); FileInputStream fs = new FileInputStream(file); ps.setInt(1,8); ps.setBinaryStream(2,fs,fs.available()); int i = ps.executeUpdate(); if(i!=0){ pw.println("image inserted successfully"); } else{ pw.println("problem in image insertion"); } } catch (Exception e){ System.out.println(e); } } } Program description: The following code is actually used to save the image data into database. PreparedStatement ps = con.prepareStatement("INSERT INTO pictu res VALUES(?,?)"); File file = new File("C:/apache-tomcat6.0.16/webapps/CodingDiaryExample/images/5.jpg"); FileInputStream fs = new FileInputStream(file); ps.setInt(1,8); ps.setBinaryStream(2,fs,fs.available()); int i = ps.executeUpdate(); Output: When you run the application through browser it will display the following message, once image is successfully inserted into database.

Retrieve image from database using Servlet In this example we will show you how to develop a Servlet that connects to the MySQL database and retrieves the image from the table. After completing this tutorial you will be able to develop program for your java based applications that retrieves the image from database. You can use this type of program to retrieve the employee image in HR application. In case social networking site you can save the user's photo in database and then retrieve the photo for display. Our Servlet connects to the MySQL database and then retrieves the saved password. Here is the structure of MySQL table used in this program. In this example the Image field will be blob and access by image id. How to Compile Servlet program 1. Save your file same name as class name. 2. Map your servlet in web.xml file. 3. Open Command Prompt and give appropriate path of your class file. 4. Compile your servlet class file by using javac file_name.java . 5. Run your program on the Browser by url-pattern which is define in web.xml file. MySql Table Structure: CREATE TABLE `pictures` ( `id` int(11) NOT NULL auto_increment, `image` blob, PRIMARY KEY (`id`) ) Here is the Example: import import import import java.sql.*; java.io.*; javax.servlet.*; javax.servlet.http.*;

public class DisplayImage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://192.168.10.59:3306/example" ; java.sql.Connection con=null; try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con=DriverManager.getConnection(connectionURL,"root","root"); Statement st1=con.createStatement(); ResultSet rs1 = st1.executeQuery("select image from pictures whe re id='5'"); String imgLen=""; if(rs1.next()){ imgLen = rs1.getString(1); System.out.println(imgLen.length()); } rs1 = st1.executeQuery("select image from pictures where id='5'"); if(rs1.next()){ int len = imgLen.length(); byte [] rb = new byte[len]; InputStream readImg = rs1.getBinaryStream(1); int index=readImg.read(rb, 0, len); System.out.println("index"+index); st1.close(); response.reset(); response.setContentType("image/jpg"); response.getOutputStream().write(rb,0,len); response.getOutputStream().flush(); } } catch (Exception e){ e.printStackTrace(); } } } Output:

say hello in spanish In this program we are going to display "hello" in spanish along with the date. To make this program we need to make a class SayHelloToSpain. To main logic of the program will be written inside the doGet() method of the servlet. To print "hello" in servlet setHeader() method of the response object should be "es". Here "es" means the content language is spanish. The code of the program is given below: import import import import import javax.servlet.*; javax.servlet.http.*; java.io.*; java.text.*; java.util.*;

public class SayHelloToSpain extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); res.setHeader("Content-Language", "es"); Locale locale = new Locale("es", ""); DateFormat df = DateFormat.getDateTimeInstance (DateFormat.LONG,DateFormat.LONG,locale); df.setTimeZone(TimeZone.getDefault()); out.println("Hello spain will be written in this way"); out.println("En Espaol:"); out.println("\u00a1Hola Mundo!"); out.println(df.format(new Date())); } } The output of the program is given below:

Accessing Date In Servlet In this example, we are going to show how we can display a creation date of the session and last accessed date or time and id on our browser. It is very easy to display it on our browser by using the Date class of the java.util package. As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. The server invokes doGet() method whenever web server receives the GET request from the servlet. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException. getSession(): getSession() is a method. This is the method that uses HttpServletRequest object. When you call the method with its argument as true, the servlet reference implementation creates a session if necessary. To properly maintain the session, you must call getSession() before any output to response. getCreationTime(): getCreationTime() is a method. This is the method that returns the time when this session was created a long integer time. getLastAccessedTime(): getLastAccessedTime() is a method. This is the method that returns the last time the client sends request with this session. getId(): This is the method that returns a string containing the unique identifier assigned to this session. Here is the code of this program: import java.io.*;

import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class AccessedDateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(true); Date create = new Date(session.getCreationTime()); Date accessed = new Date(session.getLastAccessedTime()); pw.println("ID " + session.getId()); pw.println("Create: " + create); pw.println("Last Accessed: " + accessed); String dataName = request.getParameter("dataName"); if (dataName != null && dataName.length() > 0) { String dataValue = request.getParameter("dataValue"); session.putValue(dataName, dataValue); } String[] valueNames = session.getValueNames(); if (valueNames != null && valueNames.length > 0) { for (int i = 0; i < valueNames.length; i++) { String str = valueNames[i]; String str1 = session.getValue(str).toString(); pw.println(str + " = " + str1); } } } } Download of this program: XML file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>amar</servlet-name> <servlet-class>AccessedDateServlet</servlet-class>

</servlet> <servlet-mapping> <servlet-name>amar</servlet-name> <url-pattern>/AccessedDateServlet</url-pattern> </servlet-mapping> </web-app> Output of this program is given below.

Post Message In servlet In this example, we are going to implement posting massage to servlet. In the following program, you will learn how to post massage. Code Description: The following program uses getOutputStream() method. This is the method that defines an object to assist a servlet in sending a response to the client . The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method. ServletOutputStream is a constructor. This constructor provides an output stream for sending data to the client. A ServletOutputStream object is created using response.getOutputStream() method. The servlet extends the HttpServlet and overrides the doGet() method which is inherited from HttpServlet class. The server invokes doGet() method whenever web server receives the GET request from the servlet. In this example we are going to make one html in which we post the massage given by user. The controller will check if the username , password and comment entered by the user is blank then servlet will

display massage null, if the username, password and comment entered by the user are not blank then servlet will display the massage entered by the user. Html file for this program: <html> <head> <title>post servlet</title> </head> <body> <h2>Post Massage</h2> <form Action="/amar/PostServlet" Method="GET"> <p> Username: <input type="text" name="username" size="20"></p > <p> Password: <input type="password" name="password" size="20" ></p> <p> Comment: <textarea ROWS=2 COLS=50 height="100" NAME="c omment"></textarea></p><BR> <input type="submit" VALUE="submit"> <input type="reset" value="reset"> </form> </body> </html> Here is the code of this program: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class PostServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html");{ ServletOutputStream out = response.getOutputStream(); try { out.println("<html><head><title>" + "</title></head>"); out.println("<body><h1>" + "</h1>"); String name = request.getParameter("username" ); String password = request.getParameter("password" ); String comment = request.getParameter( "comment" ); out.println("Name:" + name + "<BR>"); out.println("Password:" + password + "<BR>");

out.println("Comment: " + comment + "<BR>"); } catch(Throwable t ) { out.println("<P><pre>"); t.printStackTrace( new PrintStream(out) ); out.println ("</pre><P>"); } out.println ("</body></html>"); } } } Download of this program: xml file of this program. <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>amar</servlet-name> <servlet-class>PostServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>amar</servlet-name> <url-pattern>/PostServlet</url-pattern> </servlet-mapping> </web-app> Output of this program.

Show Parameter In Servlet In this section, you will learn how to send and put all parameter names into the table. The following program uses two methods, which is described below. Code Description: Here, in this example, you will also see the use of getParameterNames() method and getParameterValues() method. The logic of the program will be written inside the doGet() method which takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException. First, it looks up all the parameter names via the getParameterNames() method of HttpServletRequest. This returns an Enumeration. Next, it loops down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement to get each entry. Since nextElement returns an Object, it casts the result to a String and passes that to getParameterValues, yielding an array of Strings. If that array is one entry long and contains only an empty string, then the parameter had no values, and the servlet generates an italicized "No Value" entry. The array takes more then one entry long, then the parameter had multiple values and they are displayed in a table list. Otherwise the one main value is just placed into the table. getParameterNames(): getParameterNames() is a method. This is the method that returns the parameter names for the request as an enumeration of string . getParameterValues: getParameterValues() is a method. This is the method that returns the values of the specified parameter for the request as an array of strings or null if the named parameter does not exit. Html file for this program: <html> <head> <title>Form Post</title> </head> <body bgcolor="#FFFFFF"> <h1 align="center">A Sample FORM using POST</h1>

<form action="/amar/ShowParameterServlet" method="GET"> Item Number: <input type="text" name="ItemNum"><br> Quantity: <input type="text" name="Quantity"><br> <hr> First Name: <input type="text" name="FirstName"><br> Last Name: <input type="text" name="LastName"><br> Address: <textarea NAME="address" ROWS=3 COLS=40></textarea><br> Credit Card:<br> <input type="RADIO" name="CardType" value="Visa">Visa<br> <input type="RADIO" name="CardType" value="Master Card">Mas ter Card<br> <input type="RADIO" name="CardType" value="India Express">Ind ia Express<br> Enter the Credit Card Number: <input type="password" name="CardNum"><br> Reenter the Credit Card Number: <input type="password" name="CardNum"><BR><BR> <center> <input type="submit" VALUE="Submit "> <input type ="reset" value= "Reset"> </center> </form> </body> </html> Here is the code of this program: import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class ShowParameterServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String title ="Reading all request parameter"; pw.println("<html><head><title>" + "<body bgcolor=\"#FFFFFF\">\n" + "<H1 align=center>" + title + "</H1>\n" + "<table border=1 align=center>\n" + "<TR bgcolor=\"#8AEAF4\">\n" + "<td>Parameter Name</td><td>Parameter Value(s)</td>\ n"); Enumeration Names = request.getParameterNames(); while(Names.hasMoreElements()) { String str = (String)Names.nextElement(); pw.println("<tr><td>" + str + "</td><td>"); String[] Values = request.getParameterValues(str); if (Values.length == 1) { String paramValue = Values[0]; if (paramValue.length() == 0) pw.print("<I>No Value</I>"); else pw.print(paramValue); } else { pw.println("<UL>"); for(int i=0; i<Values.length; i++) { pw.println("<LI>" + Values[i]); } pw.println("</UL>"); } } pw.println("</td></tr></table>\n</body></html>"); } } Download of this program: xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app>

<servlet> <servlet-name>amar</servlet-name> <servlet-class>ShowParameterServlet</servletclass> </servlet> <servlet-mapping> <servlet-name>amar</servlet-name> <url-pattern>/ShowParameterServlet</url-pattern> </servlet-mapping> </web-app> Output of this program.

Get Parameter Name From Servlet Request This example illustrates about how to get parameter from jsp page in your servlet. In the jsp (parameter.jsp) page we have taken three input fields having name as firstname, lastname and middle name. We can get values of these fields in our servlet page. When form is submitted the action will call the servlet "GetParameter".

Source code of parameter.jsp: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %> <b><font color="blue">Please Enter your First Name, Last Name and Middle Name:</font></b><br><br> <form name="frm" method="post" action="../GetParameter"> <table border = "0"> <tr align="left" valign="top"> <td>First Name:</td> <td><input type="text" name ="firstname" /></td> </tr> <tr align="left" valign="top"> <td>Middle Name:</td> <td><input type="text" name ="middlename" /></td> </tr> <tr align="left" valign="top"> <td>Last Name:</td> <td><input type="text" name ="lastname" /></td> </tr> <tr align="left" valign="top"> <td></td> <td><input type="submit" name="submit"/></td> </tr>

</table> </form> Running the above jsp program by this url: http://localhost:8080/CodingDiaryExample/JSP/parameter.jsp displays page like below:

Now, the following program illustrates about how to access values ("firstname", "middlename" and "lastname") of jsp file in servlet (GetParameter.java). Here is the source code of GetParameter.java: import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class GetParameter extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse respo nse) throws IOException, ServletException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String firstName = request.getParameter("firstname"); String middleName = request.getParameter("middlename"); String lastName = request.getParameter("lastname"); out.println("<b><font color='blue'>Your FirstName is : </font></b>" + "<b>"+ firstName +"</b>" + "<br>"); out.println("<b><font color='blue'>Your Middle Name is : </font></b>" + "<b>"+ middleName +"</b>" + "<br>"); out.println("<b><font color='blue'>Your Last Name is : </font></b>" + "<b>"+ lastName +"</b>"); } }

In the above servlet, get parameter by the HttpServletRequest object. The getParameter() method returns the value of a request parameter (passed as an argument like: "firstname", "middlename" and "lastname") as a String or null if the parameter does not exist. Mapping of servlet (GetParameter.java) in web.xml file: <servlet> <servletname>GetParameter</servle t-name> <servletclass>GetParameter</servlet -class> </servlet> <servlet-mapping> <servletname>GetParameter</servle t-name> <urlpattern>/GetParameter</urlpattern> </servlet-mapping> From the above lines in web.xml we are mapping the servlet with url. If we enters the values like in the figure below

then following output will be displayed.

How to connect to MySql Database from Servlet? In this example we will show you how to connect to MySQL database and perform select operation. You will learn the JDBC steps necessary to connect to the MySQL Database and execute the query. Here we are using the MySQL jdbc driver for making the connection. You can download the jdbc driver for MySQL from http://dev.mysql.com/downloads/connector/j/5.1.html and then put the driver jar file into the classpath. You have to first create the a table in MySQL database and then connect it through JDBC to show all the records present there. MySql Table Structure: CREATE TABLE `servlet` ( `id` int(11) NOT NULL auto_increment, `name` varchar(256) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*Data for the table `servlet` */ insert into `servlet`(`id`,`name`) values (1,'sandeep'),(2,'amit'),(3,'anusmita'), (4,'vineet'); Here is the code of Example: // *DataBase Connectivity from the Servlet. import java.io.*; import java.util.*; import javax.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBConnection extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse

response) throws IOException, ServletException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Servlet JDBC</title></head>"); out.println("<body>"); out.println("<h1>Servlet JDBC</h1>"); out.println("</body></html>"); // connecting to database Connection con = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); con =DriverManager.getConnection ("jdbc:mysql://192.168.10.59:3 306/example", "root", "root"); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM servlet"); // displaying records while(rs.next()){ out.print(rs.getObject(1).toString()); out.print("\t\t\t"); out.print(rs.getObject(2).toString()); out.print("<br>"); } } catch (SQLException e) { throw new ServletException("Servlet Could not display records.", e); } catch (ClassNotFoundException e) { throw new ServletException("JDBC Driver not found.", e); } finally { try { if(rs != null) { rs.close(); rs = null; } if(stmt != null) { stmt.close(); stmt = null; } if(con != null) {

con.close(); con = null; } } catch (SQLException e) {} } out.close(); } } Program Description: The following query is used to fetch the records from database and display on the screen. stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM servlet"); // displaying records while(rs.next()){ out.print(rs.getObject(1).toString());//You can also user rs.getString(1); out.print("\t\t\t"); out.print(rs.getObject(2).toString());//You can also user rs.getString(2); out.print("<br>"); } Other JDBC statement you can understand easily. Output:

Servlet Error Message based on user input In this example user is presented with a screen to enter the name. If the entered name exists in the database its displays the sucess message otherwise it displays the error message. So, you can use Servlet to check the user input against database and display the message to the user. This example illustrate how to ensure that user input is correct by validating against the database. In this example any error on the user end is checked by the servlet. If user submits his data then servlet checks user existence in database by connecting to the database, if data is found correct then servlet sends a message to the user for successfully entering the correct data but if data is not correct then sends a message to user for wrong entry of data. This example illustrates how to show error message on the page when user enters wrong entry for any specific field on the page. For this create a page "test.jsp" which renders an input field to enter the name of the user. Here is the code for test.jsp: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %> <font color="blue">Please Enter Your Name To check the error massege</font><br><br> <form name="frm" method="post" action="../ErrorMessage"> <table border = "0"> <tr align="left" valign="top"> <td>Name:</td> <td><input type="text" name ="name" /></td> </tr> <tr align="left" valign="top"> <td></td> <td><input type="submit" name="submit" value="submit"/></td> </tr> </table> </form> The above code displays the page as below:

Now, we will create a servlet to check whether the user has entered the name as "sandeep" in the input field of the page. This servlet checks the name in the database and if it finds the name in the database then displays the greeting text indicating that the user has entered successfully, otherwise it displays the error message on the page showing the wrong entry. Here is the code for servlet "ErrorMessage.java" import import import import import import import import import import java.io.*; java.util.*; javax.sql.*; javax.servlet.*; javax.servlet.http.*; java.sql.Connection; java.sql.DriverManager; java.sql.ResultSet; java.sql.SQLException; java.sql.Statement;

public class ErrorMessage extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse respo nse) throws IOException, ServletException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); Connection con = null; Statement stmt = null; ResultSet rs = null; String jspname = request.getParameter("name"); String name= new String(""); try { Class.forName("com.mysql.jdbc.Driver"); con =DriverManager.getConnection ("jdbc:mysql ://192.168.10.59:3306/example", "root", "root"); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM servlet where name='"+jspname+"'");

while(rs.next()){ name=rs.getString("name"); } rs.close(); stmt.close(); }catch(Exception e){ System.out.println(e); } Boolean isResponseCorrect = Boolean.FALSE; if(jspname.equals(name)){ isResponseCorrect=true; out.println("<b><font color='green'>You are successfully enter the valid name!</font></b>"); } else{ isResponseCorrect=false; out.println("<b><font color='red'>This name is Not A Valid Name. Try Again!</font></b>"); } } } If the user enters the name "piyush"( not "sandeep" or "vineet" or "amit" or "anusmita" which is in database)

then it displays the error message like in the picture below.

If user enters correct name i.e. "sandeep".

then a successful message is displayed.

Quintessential Servlet Example program for Quintessential servlet Quintessential servlet is not any special kind of servlet. It is just a proper and appropriate way to write a servlet. This quintessential servlet means that servlet is having accurate way of code written for an organizations servlet. The word "Quintessential" means appropriate, best, classical, essential format of code writing . This example implements a servlet that handles GET requests. The example of this "Quintessential servlet" is given as below:

package com.mycompanyname; import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class MyServletName extends HttpServlet { // // // This method is called by the servlet container just before this servlet is put into service. Note that it is possible that more than one instance of this servlet can be created in the same VM.

public void init() throws ServletException { // Initialization code getServletContext().log("getinit init"); // Get the value of an initialization parameter String value = getServletConfig().getInitParameter("param 1");

// Get all available intialization parameters java.util.Enumeration enum = getServletConfig().getInitParameterNames(); for (; enum.hasMoreElements(); ) { // Get the name of the init parameter String name = (String)enum.nextElement(); // } // } // // This method is called by the servlet container to process a GET request. There may be many threads calling this method simultaneously. The int parameters can also be retrieved using the servlet context value = getServletContext().getInitParameter("param1"); Get the value of the init parameter value = getServletConfig().getInitParameter(name);

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); out.println("<html><head><title>A Simple Servlet</title></head><body>"); out.println("Today is "+(new java.util.Date())); out.println("</body></html>"); out.close(); } // // This method is called by the servlet container just after this servlet is removed from service.

public void destroy() {

// } }

Shutdown code...

Logging Filter Servlet Example Example program to demonstrate Logging Filter This example illustrates how one can write Logging Filter servlet to provide control over log file. You can have additional controls over these log files and these all are available to use by implementing "Filter" class. Filters are very important in servlet access and handling due to number of reasons, for example, it encapsulates recurring tasks in a reusable unit, modularizing codes so that they become easy to manage, transforming request from a servlet to JSP page. Most common task for a web application is to format data sent back to client since most clients require different format (e.g in WML,XML etc.) rather than only HTML so to accomplish these tasks of clients, Filtering is important to develop a fully featured Web Application. Filters can perform many different tasks, in which logging is one of the most important task. You can create filter class by implementing javax.servlet.Filter, which has three methods as follows:

void init(FilterConfig filterConfigObject) throws ServletException void destroy() void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchainObject) throws IOException, ServletException

init(FilterConfig) is called once by the server to get prepared for service and then it calls doFilter() number of times for request processing. In this example there is LoggingFilterExample servlet which is writing Remote Address, URI , Protocol of calling JSP file into log file as server calls LoggingFilterExample via logging.jsp. Source code for LoggingFilterExample.java is given as below: 1. LoggingFilterExample.java mport java.io.*; import javax.servlet.*; import javax.servlet.http.*; public final class LoggingFilterExample implements Filter { private FilterConfig filterConfigObj = null;

public void init(FilterConfig filterConfigObj) { this.filterConfigObj = filterConfigObj; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String remoteAddress = request.getRemoteAddr(); String uri = ((HttpServletRequest) request).getRequestURI(); String protocol = request.getProtocol(); chain.doFilter(request, response); filterConfigObj.getServletContext().log("Logging Filter Servlet called"); filterConfigObj.getServletContext().log("******* *******************"); filterConfigObj.getServletContext().log("User Logged ! " + User IP: " + remoteAddress + " Resource File: " + uri + " Protocol: " + protocol); } public void destroy() { } } LoggingFilterExample writes content in log file by the following method:

filterConfigObj.getServletContext(). log() 2. logging.jsp <%@ page language="java" %> <html> <head> <title>Logging Filter Example</title> </head> <body>

<h1>Logging Filter</h1> This filter writes log file of Tomcat Web Server. <hr> See log file of Web server. <br> </body> </html> When this JSP file is called by the server then through the filter mapping LoggingFilterExample filter would be called and it will write content into log file of your web server. To do working we have to do mapping in the web.xml deployment descriptor. <filter> and <filtermapping> element requires <filter-name> to tell the name of filter to which you want to map a servlet or URL pattern. This mapping is as follows: 3. web.xml <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/ xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <display-name>Welcome to Tomcat</displayname> <description>Welcome to Tomcat</description> <filter> <filter-name>LoggingFilterExample</filtername> <filter-class>LoggingFilterExample</filterclass> </filter> <filter-mapping> <filter-name>LoggingFilterExample</filtername> <url-pattern>/logging.jsp</url-pattern> </filter-mapping> </web-app>

To run this example you have to follow these few steps given as below: 1. Create and Save LoggingFilterExample.java 2. Compile and put this LoggingFilterExample.java into classes folder 3. Create and save logging.jsp 4. Do the filter-mapping in web.xml 5. Start Tomcat web server 6. Type following URL into address bar http://localhost:8080/vin/logging.jsp Output: By typing above URL, the opened page would be like this

and now go and see your tomcat's logs/localhost.<current date>.log file. Last few lines in this file would be like this.

Context Log Example Using Servlet This example illustrates about how to use of Context Log in servlet. Context Log is used to write specified message to server log file when servlet is called. In the following JSP page (message.jsp) we have simply taken a text area where user give his/her message and post the form. After posting the form, the servlet ContextLogExample is called. Source code of the message.jsp is given below:

Source code of message.jsp: <%@page language="java" session="true" contentType="text/html;charset=ISO-88591"%> <br> <form name="frm" method="post" action=../ContextLogExample> <table border = "0"> <tr align="left" valign="top"> <td>Give your Message:</td> </tr> <tr> <td><TEXTAREA NAME="message" COLS=30 ROWS=6></TEXTAREA></td> </tr> <tr align="left" valign="top"> <td><input type="submit" name="submit" value="submit"/></td> </tr> </table> </form> Running the jsp page (message.jsp) on this url: http://localhost:8080/JavaExample/JSP/message.jsp the will displays as below:

In the following servlet (ContextLogExample) we get parameter of jsp page in "message" variable and set this message to the log file by log() method of ServletContext interface The Source code of ContextLogExample.java is given below: import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class ContextLogExample extends HttpServle t{ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String message = request.getParameter("message") ; ServletContext context = getServletContext(); if(message == null || message.equals("")){ context.log("No message received:", new IllegalStateException("Parameter not Found")); }else{ context.log("Parameter Found: Successfully received your message: " + message); } out.println("<html><head><title>Context Log Example</title></head><body>"); out.println("<h2><font color='green'>Successfully send your Message</font></h2>"); out.println("</body></html>"); }

} Mapping of servlet (ContextLogExample.java) in web.xml <servlet> <servletname>ContextLogExample</servle t-name> <servletclass>ContextLogExample</servlet -class> </servlet> <servlet-mapping> <servletname>ContextLogExample</servle t-name> <urlpattern>/ContextLogExample</urlpattern> </servlet-mapping> User enters the message in the text area that is sent to the servlet (ContextLogExample)

Servlet sets the message in the log file which is shown like below:

Response Filter Servlet Example This Example shows how to use of response filter in Java Servlet. Filter reads own initial parameters and adds its value to the response. Use the init-param child element of the filter element to declare the initialization parameter and its value. Inside the filter, access the init parameter by calling the FilterConfig object's getInitParameter method.

Here is the source code of ResponseFilterExample.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ResponseFilterExample implements Filter{ private FilterConfig config = null; public void doFilter(ServletRequest request, ServletResponse respons e, FilterChain filterchain)throws IOException, ServletException{ filterchain.doFilter(request, response); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<b>Filter Received Your Message Successfully:</b>" + config.getInitParameter("response")); } public void destroy() { } public void init(FilterConfig config) { this.config = config; } } The above code initialized the FilterConfig object in its init methods, which is called once when the web container creates an instance of the filter. The code then gets the value of the filter's init parameter by calling: config.getInitParameter("response"). Mapping for the filter in web.xml: <filter> <filter-

name>ResponseFilterExample</filte r-name> <filterclass>ResponseFilterExample</filter -class> <init-param> <paramname>response</param-name> <param-value>Hello Response Filter Example!</param-value> </init-param> </filter> <filter-mapping> <filtername>ResponseFilterExample</filte r-name> <urlpattern>/JSP/response.jsp</urlpattern> </filter-mapping> The source code of response.jsp: <html> <head> <title>Response Filter Example</title> </head> <body> <h2><font color="green">Response Filter and Initialized Parameters</font></h2> <br> </body> </html> Running the program by this url: http://localhost:8080/JavaExample/JSP/response.jsp the message will display below

IP Filter Example The filter provides a basic security mechanism for a firewall to determining what traffic passes through the firewall based on IP address details. This protects the secure network from outsiders. A filter is an object that perform filtering tasks on request and response. A FilterConfig object used by a servlet container used to pass information to a filter during initialization. Filters are registered in web.xml (deployment descriptor) of a web application. The most easiest and effective way of minimize the risk from out side attacks is to filter incoming requests based on the IP address of the client. For example, if you have two web addresses that make requests using 192.168.10.146 and 127.0.0.1 and wish to restrict the servlet requests only from 127.0.0.1 then following program will help you. Here is the Source Code of IPFilterExample.java import import import import import import import import import import import import java.io.*; java.util.*; javax.servlet.*; java.io.IOException; java.util.StringTokenizer; javax.servlet.Filter; javax.servlet.FilterChain; javax.servlet.FilterConfig; javax.servlet.ServletException; javax.servlet.ServletRequest; javax.servlet.ServletResponse; javax.servlet.http.HttpServletResponse;

public class IPFilterExample implements Filter{ public IPFilterExample() {} public final static String IP = "193.168.10.146"; private FilterConfig filterConfig; public void init(FilterConfig config) throws ServletException{ this.filterConfig = config; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>IP Filter Example</title></head>"); String userip = request.getRemoteAddr();

HttpServletResponse httpResponse = null; if (response instanceof HttpServletResponse){ httpResponse = (HttpServletResponse) response; } if (IP.equals(userip)) { httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,"You are not allowed to access the servlet!"); } else { filterchain.doFilter(request, response); out.println("<body><h3><font color='green'>Passed successfully from IP Filter<font></h3></body></html>"); } } public void destroy() {} } Here is the source code of CallIpFilter Servlet. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CallIpFilter extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse respo nse) throws ServletException,IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<html>"); pw.println("<head><title>IP Filter Example</title></title>"); pw.println("<body>"); pw.println("<h1>Welcome, calling servlet successful</h1>"); pw.println("</body></html>"); } } Mapping of Filter (IPFilterExample) and Servlet (CallIpFilter) in web.xml <filter> <filtername>IPFilterExample</filter -name> <filter-

class>IPFilterExample</filterclass> </filter> <filter-mapping> <filtername>IPFilterExample</filter -name> <urlpattern>/CallIpFilter</urlpattern> </filter-mapping> <servlet> <servletname>CallIpFilter</servletname> <servletclass>CallIpFilter</servletclass> </servlet> <servlet-mapping> <servletname>CallIpFilter</servletname> <urlpattern>/CallIpFilter</urlpattern> </servlet-mapping> Running the servlet by this url: http://localhost:8080/ServletExample/CallIpFilter from IP 193.168.10.146. The message will display as below:

But when, user access from IP address 127.0.0.1 then he could not access the servlet (CallIpFilter) because IP Filter does not allow to access for this IP address and status report will display as below:

Working with Tomcat Server This section explains how to work with Tomcat Server Apache Tomcat is a famous Servlet container developed at Apache Software Foundation. This software is released under under the Apache Software License. Anyone can use it for the development as well as deployment of the applications. Tomcat is the official reference of implementation of java Servlets and java Server Pages. Tomcat is very easy to install and configure. Anyone can learn it very fast and start using the Tomcat server for the development and deployment of the web applications. These days many web hosting companies are providing Tomcat support on their server. So, if you develop the application in Java technology you can get any host and then deploy it on the internet. Earlier it was a difficult task to get a good host for hosting. So, let's get started with the Tomcat server. 1) Installation and Configuration- Apache Tomcat Server is free software available for download at www.apache.org and www.jakarta.apache.org.The current version of tomcat server is 6.0. This server supports Java Servlets 2.5 and Java server Pages 2.2. JDK is also free software available for download at www.java.sun.com. Its current version is 6.0. Learn Tomcat Installation in detail. You will also find the description on how to run example with tomcat. Deploying Servlets On Tomcat Server To deploy servlets on Tomcat Server, following steps are to be taken for example given below. 1. Create web application To develop an application using servlets or jsp, a directory structure is to be maintained for the example given below. Step1: Create a web application folder (servlet-examples) under tomcat webapps directory. The path will be C:\apache tomcat\webapps\servlets-examples. Step2: Create a WEB-INF folder which should be created under servlets-examples.

Step3: Create web.xml file and classes folder under the WEB_INF folder. 2. Compile the servlet Program- Create a servlet program and compile it on the command Prompt .The procedure is not different from any java program. The set of classes required for writing servlets is available in servlet-api.jar which is put into CLASSPATH. 3. Copy the Servlet class(Hello) into classes folder, which is under WEB-INF folder. 4. Edit web.xml to include servlet's name and url pattern. <servlet> <servletname>Hello</servletname> <servletclass>Hello</servlet-class> </servlet> <servlet-mapping> <servletname>Hello</servletname> <url-pattern>/Hello</urlpattern> </servlet-mapping> 5. Run Tomcat Server and execute your servlet- To run the server Go to C:\apache tomcat\bin\startup.bat and double click on it , the server will start up. After assuring that the server is running successfully, you can run your servlet. To execute your servlet, open your web browser and type the url which you have mentioned in your web.xml. The url will be like this: http://localhost:8080/servlets-examples/Hello Let's see an example Servlet "Hello". Here is the code of "Hello.java".

import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("hello"); out.println("</body>"); out.println("</html>"); } } Output of program:

Você também pode gostar