Writing Hello World
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:
|
web.xml file for this program:
|
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.
The code the program is given below:
|
XML File for this program
|
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:
|
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:
|
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:
|
web.xml file for this program:
|
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:
|
web.xml file for this program:
|
The output of the program is given below:
|
nooping 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:
|
|
|
| web.xml file for this program:
|
|
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:
|
XML File for this program:
|
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:
|
web.xml file of this program:
|
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:
Please enter your username and password Username Password |
LoginServlet.java
|
web.xml file for this program:
|
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
Which of the whisky you like most |
GetParameterValues.java
|
web.xml file for this program:
|
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 java.io.*;
|
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:
Enter your name Enter your password
|
|
|
web.xml file for this program:
|
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 : . 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:
|
web.xml file for this program:
|
The output of the program is given below:
|
Pre- Existing Session
In this example we are going to find out whether the session is pre-existing 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
|
web.xml file for this program:
|
The output of the program is given below:
|
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:
|
web.xml file for this program:
|
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:
| |
Enter your name : | |
Enter your password : | |
import java.io.*;
|
import java.io.*;
|
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 java.io.*;
|
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
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
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.
ServletContextListener
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 java.io.*;
|
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
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.*;
|
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.*;
|
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.*;
|
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.*;
|
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:
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 javax.servlet.*;
|
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:
|
XML file for this program:
|
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:
Username: Password: Comment:
"submit" VALUE= "submit" >
"reset" value= "reset" >
|
Here is the code of this program:
" |
xml file of this program.
|
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:
|
Here is the code of this program:
|