Category Archives: Servlet Tutorial

Servlet Tutorial

Servlet Pagination

Servlet Pagination

In our last article we did CRUD example , the data was too much for single page so it will load more when we use it on single page. Solution for this problem is pagination, we used to divide our large number of data into pages so that database query will take less time to execute. We are going to use same table which is done in previous article. So let’s start example now.

Example :-

Lets create a simple example to demonstrate pagination of records –
index.html

First we need index.html file which will be our welcome page. Check below code.

Emp.java

This is our model class means Java bean class, we have used same like previous article, please check below code.

EmpDBHandler.java

This is our Database handler class, same as previous article except one method (i.e. getRecords()) which is used for pagination check below code for more details.

ViewEmpServlet.java

This is our servlet class where pagination is going to do work, please check below code for this thing.

AddServlet.java

This same as previous article, From here we will add employee, please check below code.

 

Output:-

We are done with coding part now check the output in below images, you can also implement this thing in our CRUD example, just need to add one more method in DB handler class and get this thing.

Screen 1:-

page_1

Screen 2:-

page_2

Screen 3:-

image005

Servlet CRUD

Servlet CRUD

CRUD (Create,Read,Update,Delete) is the most important part of any application or project. In this article we will learn about CRUD. Let’s get understand it by an example.

Example :-

Before doing coding part we need to create database and table for the storage, in this example I have used mysql which is in phpmyadmin of Xampp. Check below image for table structure.

image001

Here test is database name and emp_management is the table name.

Let’s start coding part. First we need to create project for this, index.html file will be auto created. Check below code for that and also other classes.

Note: Don’t forget to add MySQL JDBC Driver in your project like below image.
image003

index.html

Emp.java

This is our java bean class, from here we will set and get the data.2. Emp.java : This is our java bean class, from here we will set and get the data.

EmpDBHandler.java

This is very important part of this project, from here we will handle our all queries of database, database connection also be here. Check below code.

AddServlet.java

From this class we will add employee which will inserted to database. Check below code.

ViewEmpServlet.java

It will show employees list in the form of table which are added by you, from here you can also delete and update user details. Check below code.

DeleteEmpServlet.java

When you run this project you will find an option in “View Employee” screen that is delete, which will redirect to DeleteEmpServlet.java class and delete the entry from table. Check below code.

UpdateEmpServlet.java

This is the class from where you can update the details of employee, You will get the form here which will be filled by previous entries of employee, when you edit and submit the details , it will redirect to the UpdateEmpServlet2.java class, which will update the data in the table. Check below code for this class.

UpdateEmpServlet2.java

As I explained above that this servlet will be used for update the employee details in the table, check below code for this class.

Output:-

So we are done with coding now check one by one screenshots of this project.

Index2.html

image005

After Adding Employee

image007

Database screenshot after adding employee.

image009

 

View Employee screenshot.

image011

Update Screenshot : On Update screeshot.

image013

After update and add one more employee.

image015

Delete: Post deletion result will be like below image

image017

After insertion of multiple records.

image019

So we are done with this project, link of this project is below. You can simply download this project by below link. Here we can see there are many records in table so in next article we will make them in pagination. In short we will divide our data in pages. Check Next article for this.

Download Complete Code

Servlet URL Rewriting

Servlet URL Rewriting

Using the url rewriting we can append parameter in url and can send our data to next servlet. We send the parameter in key-value pair. It works even cookie is disabled but it works only with links.

The format will be like below code:

here name is key and w3adda.com is value.

Example:-

Let’s understand it by an simple example.

index.html

This will be our welcome file. Check below code.

First.java

From this servlet class we will append our parameter in url. Check below code.

Second.java

Here we will get parameter of given url. Check below code.

Output:-

The below images will show output of this code.

Screen 1:-

This is our index.html file output.

image001

Screen 2:-

Below image is our First.java file output.

image003

Screen 3:-

In the Second servlet file we will get this parameter by the request.getParameter() method. Check below image.

image005

 

Servlet HttpSession Login Logout

Servlet HttpSession Login Logout

In previous article we have gone through with methods of HttpSession interface. Also we have tried an example for that, here we are going to do login and logout with session. Let’s get understand more about HttpSession Interface.
We need to create some html, servlet classes for this, get understand about them one by one.

index.html

This will be our Welcome page, here we keep three links first one will be for Login, second Logout and last one will be Profile, like below code.

link_session.html

This is our link page, suppose we clicked directly on profile without login so this page will show us or even we did logout. Check below code.

login_session.html

This will call from index.html file or link_session.html file, when user will click on Login button.

LoginSession.java

This is our Login file, here I have taken “w3adda1234” as a password, if password matched so it stores the attribute into the session. Check below code.

 

ProfileSession.java

With the help of session.getAttribute(“name”) we will get the value of attribute which is stored in the session. Check below code.

LogoutSession.java

From here we will destroy session. Check below code.

Output:-

As we are done with code, so let’s run this and get output like below images.

Screen 1:-

image001

Screen 2:-

image003

Screen 3:-

image005

Screen 4:-

image007

Screen 5:-

image009

sdfsdf

Servlet HttpSession

Servlet HttpSession Interface

This interface provides a way to identify the user. Servlet container uses this interface for the creation of session between HTTP client and HTTP server. HttpSession can perform binding of objects, also it can be view and manipulate information of session.

HttpSession Interface Methods

There are some important methods which are used in this interface.

HttpSession getSession(): This method returns the current session which is associated with this request.

HttpSession getSession(Boolean create): This method returns the current session which is associated with this request when it Boolean value is false, it create new when it is true.

void setAttribute(String name, String value): This method is used to set the attribute in session.

lang.Object getAttribute(String name): This method is used to return the value of given parameter from session.

lang.String getId(): This method is used to returns the string of session unique identifier.

void invalidate(): This method Invalidates this session then unbinds any objects bound to it.

Long getLastAccessedTime(): This method returns the last time the client sent the request associated with this session.

Long getCreationTime(): This method returns the time when this session was created.

Example:-

Let’s understand it by an example.

index.html

This will be our welcome file from which we will send the user name.

FirstSession.java

From this servlet we will store our session from below method.

Check below code for this servlet.

SecondSession.java

From this servlet file we will get the session data with the help of below code.

Check below code of this servlet file.

Output:-

Check output of this code.

Screen 1:-

image001

Screen 2:-

image003

Screen 3:-

image005

Servlet Hidden Form Field

Servlet Hidden Form Field

Hidden form field can be used for session management for a particular client. In this case a hidden textfield is used to maintain the state of an user. We store the information in hidden form field and get it from another servlet.

Syntax :-

The syntax which is using to store the data in hidden field is below.

The advantage of this thing over cookie: It works even cookie is disabled.

There are also some disadvantage of this thing: We need extra form submission on each page, it maintained from server side.

Example: Let’s understand it by an example.

  1. html: This will be our welcome file for hidden form field.

2. FirstServlet.java: From this servlet file we will store hidden data. Check below code.

3. SecondServlet.java: We will get our hidden data here. Check below code.

Output :-

When we will run this simple code so we will get output like below images.

index.html

This is output of index.html file.

image001

This will come when we will click on go button of index.html file.

image003

This output comes for SecondServlet class, here we got our hidden field data.

image005

Servlet Cookie Example

In previous article we have learned about cookies, it’s methods and constructor. In this article we are going to implement this thing in our browser.

Let’s understand it by login logout example, we have to create some class. Follow the below steps.

index.html

First we need to create index.html file. Check below code.

login.html

Lets create login.html file which we are going to use and put the following code in it.

LoginServlet.java

From this Servlet java class we are going to add cookies to our web browser.

ProfileServlet.java : This is the profile servlet class from which we will get the cookie. Check below code.

LogoutServlet.java : This servlet is used for logout the session and cookie’s age will be replaced by 0. Have a look on method for age of cookies which are discussed in previous article of cookies.

 

Output:-

Lets run this example You will get output like below images.

Screen 1:-

This will be our index.html file output. If we click on profile this will give output like second image.

image002

Screen 2:-

This will come when we directly click on Profile button.

image004

Screen 3:-

This will come on when successfully logged in . now when we click on Profile button, we will get our cookies result. Check next screenshot.

image005

 

Screen 4:-

When we have data in cookies. So this will come.

image007

Screen 5:-

on Successfully logout the below image will appear.

image009

Servlet Cookies

Servlet Cookies

Cookies are the small amount of information which are sent by the servlet to a web Browser . Browser saves this information and later on it sends to server. Cookies are commanly used for session management because value of cookies can uniquely identify a client. Cookies can be name, a single value and optional attributes like a comment, path , domain qualifiers etc. The servlet method which is used to add cookies to a web browser is HttpServletResponse.addCookie(javax.servlet.http.Cookie) and Cookies can be retrieved by request, the method for getting this thing is HttpServletRequest.getCookies().

Types of Cookies

There are two types of cookies in servlet.

Non-persistant cookie :- This type of cookie removed when user closes the browser and valid only for single session.

Persistent cookie :- This type of cookie is not removed each time on closing of browser. This is removed only when user logout. This is valid for multiple session.

Constructor Summary:

Cookie(java.lang.String name, java.lang.String value): This constructor is used to construct a cookie with specified name and value.

There are some important methods which are used to handle cookies, let’s understand them.

java.lang.object clone(): It overrides the standard java.lang.object.clone method which is used return a copy of this cookie.

int getMaxAge(): This method is used to return maximum age of cookie, specified in seconds, By default. When age is -1 it means the cookie will persist until browser shutdown.

java.lang.String getName(): This method is used to return name of cookie.

java.lang.String getPath() : This method is used to return the path on the server to which the browser returns this cookie.

boolean getSecure(): This method is used to returns true if the browser is sending cookies only over a secure protocol, or false If the browser can send cookies using any protocol.

java.lang.String getValue(): This method is used to returns the value of cookie.

void setMaxAge(int exp): This method is used to sets the maximum age of cookie in seconds.

void setPath(java.lang.String uri): This method is used to specifies the path for the cookie.

void setSecure(boolean flag): It indicates to the browser whether the cookie should only be sent using secure protocol, such as HTTPS or SSL.

void setValue(java.lang.String newValue):This method is used to assigns a new value to a cookie after the cookie protocol this cookie complies with.

Example:-

Example:-

Example:-

Servlet on Netbeans

Servlet on Netbeans

We have discussed servlet methods and also seen some example of Servlet in our previous article. Now let’s create a simple project in Netbeans IDE and understand Servlet step by step.

Step 1:- First we need to create a project so click on File in netbeans as like below image.

image001

Step 2:- In Second step you have to click on New Project and then need to on Java Web after that select Web Application as like below image.

image003

Step 3:- After selecting Name and Location of Project, you have to click on Next And then Finish. Check below image for reference.

image005

Step 4:- You will get default index.html file. We will do some modification in this file later. In this step we will create servlet, for this please check below images.

image007

Do right click on default Package and then select Servlet. You will get screen like below image.

image009

Enter Your Servlet Name and then click Next. Check below Image.

image011

Note: Make Sure you have clicked on check box because it use for declare your servlet in web.xml file. We are all set with Servlet creation. Click on Finish.

Step 5:- Index.html: This file will be our welcome file, on click button it will redirect to our TestServlet.java class. Check below code.

Output :-

This file output will look like below image.

image013

Step 6:-

TestServlet.java: This is our Test Servlet class, Please check below code.

Output :-

So we are done with this example, have a look to output image.

image015

 

Servlet HttpServlet

Servlet HttpServlet Class

The HttpServlet class is a sub class of GenericServlet Class, It means it extends GenericServlet class and also it implements Serializable interface. It provides some specific methods like doGet, doPost, doHead, doTrace ,doDelete etc.

Syntax:-

HttpServlet Class Methods

public void service(ServletRequest req,ServletResponse res) :- This method used to dispatches client request to the protected service method.

protected void service(HttpServletRequest req, HttpServletResponse res):- This is method which receives standard HTTP from the public service method and dispatch them to the doXXX() methods(depends upon incoming http request).

3.protected void doGet(HttpServletRequest req, HttpServletResponse res):- This method called by the server(via service method) to allow a servlet to handle GET request.

4 protected void doPost(HttpServletRequest req, HttpServletResponse res):- This method called by the server(via service method) to allow a servlet to handle POST request.

protected void doHead(HttpServletRequest req, HttpServletResponse res):- This method receives an HTTP Head request from the protected service method and handle the request.

6.protected void doOptions(HttpServletRequest req, HttpServletResponse res):- This method called by the server(via service method) to allow a servlet to handle OPTIONS request.

7.protected void doPut(HttpServletRequest req, HttpServletResponse res) :- This method called by the server(via service method) to allow a servlet to handle PUT request.

8.protected void doTrace(HttpServletRequest req, HttpServletResponse res):- This method called by the server(via service method) to allow a servlet to handle TRACE request.

9.protected void doDelete(HttpServletRequest req, HttpServletResponse res):- This method called by the server(via service method) to allow a servlet to handle DELETE request.

10.protected long getLastModified(HttpServletRequest req):- This method returns the time the HttpServletRequest object was last modified.

Servlet SendRedirect

SendRedirect in Servlet

The word send redirect saying everything that this method is used to redirect the response to another resources such as jsp, servlet, html file. This method can accept relative URL as well as absolute URL. This is the method of HttpServletResponse interface.

When to use sendRedirect() method:

  • For the redirection of client request to another Website.
  • For the redirection of errors to another resources such as servlet , JSP or Html file.
  • For sending any existing HTML form on the server to client.

Difference Between forward() and sendRedirect() method

These two methods are commonly used to send the request to another resources but there are some difference between both method. Which are given below.

  1. forward() method execute at server side but sendRedirect() method execute at client side.
  2. forward() method is used to sends the same request and response to another resources but sendRedirect() method sends always new request.
  3. forward() method can transfer the resources only within server but sendRedirect() method can transfer the resources within and outside the server.
  4. forward() method consume only one call but sendRedirect() consume Two request and response calls.
  1. We can not see forwarded message but we can see redirected address.
  2. The forward() method is faster than sendRedirect().

Syntax:-

Example:-

Let’s understand it by an simple example. The required files are.

welcome.html :-

Using this file we will send the request to servlet.

SearchDemo.java :-

This is the servlet file where we have used sendRedirect() method. Check below code.

Output :-

Check below Images for output of this sample code.

This is the output of welcome.html file, it will send request to servlet on click of Search button.

image001

Below image is the output of sendRedirect() method of Servlet

image003

 

 

Servlet ServletContext

Servlet ServletContext Interface

At the time of deploying the project servlet container create ServletContext object. It defines a set of methods that a servlet uses to communicate with it’s servlet container. This object used to get configuration information from web.xml file, Remember one thing there is only one ServletContext object per web application. If any information is going to share into many servlet so its better to use <context-param> in the web.xml file. Like below code.

Usage :-

There are many important usage of ServletContext Interface. Here I have discussed some of them.

  • We can set,get and remove attributes from the web.xml file with the help of ServletContext Interface.
  • This object is used to get configuration information from the web.xml file.
  • This object is used to provides an interface between the servlet container and servlet.
  • It also provides inter-application communication.
  • it is available to all Servlets and JSPs files which are part of web app.

ServletContext Interface Methods

There are so many methods are in ServletContext Interface, some of them are listed below.

public String getInitParameter(String name):- This methods is used to returns the parameter value by the specified name.

public Enumeration getInitParameterNames() : This method is used to returns the an Enumeration which contains the names available within servlet context.

public void setAttribute(String name,Object object) :- This method is used to binds an object to a given attribute name in the servlet context.

public Object getAttribute(String name) :- This method returns the servlet container attribute with the given name, or if there is no attributes it returns null.

public void removeAttribute(String name) :- This method is used to remove the attribute with the given name from the servlet context.

ServletContext getServletContext() :- It returns a ServletContext object .

public String getServerInfo() :- This method returns the name and version of the servlet container.

Example:-

Let’s understand this interface by an example.

ServletContextExample.java :-

In this servlet we get the data with the help of getServletContext() method (which returns the object of ServletContext interface) and the data is initialized in the web.xml file. Check below code:

Web.xml :-

follow the below code to set <context-param>.

Output :-

The output of this code will look like below image.

image001