Introduction to Java Servlets & JSP

Chinmaya Sahoo
6 min readDec 7, 2020

Servlets

Today we all are aware of the need of creating dynamic web pages i.e the ones which have the capability to change the site contents according to the time or are able to generate the contents according to the request received by the client.

In Java there is a way to generate dynamic web pages and that is by using servlets.

Servlets are the java programs that runs on the web application server. It is u used to handle the requests of the user by web server, process the requests and produce response also send the responses to the web server.

Properties of Servlets :

  • Servlets work on the server-side.
  • Servlets are capable of handling complex requests obtained from web server.

This whole process follows some procedures,

  1. The client request to the web server.
  2. Web server receive the request.
  3. Web server send the request to the corresponding servlet.
  4. Servlet process the request and generate response according to the request and then send the response to the web server.
  5. Web server send the response back to the client and displays on the client browser screen.
visual representation of the whole process

How to create a servlet file

To create a servlet we just have to right click on the dynamic web project that we have created and select new and then select servlet option.

Or we can do like this also, create a normal class and extends that class to HttpServlet.

HTTP methods —

There are many methods available under http, but we are going to discuss the most important ones.

After creating a servlet file we can see that there are multiple methods which are already created by the servlet container like doGet and doPost etc.

Let’s understand what are these methods are,

doGet

We use this method when the user wants to fetch or try to get some data from the web server in the request

doPost

This method is used when the user requests for some specific data or try to get some data from the web server.

example

Let us take a scenario like we have to show a form to the client on his web browser and it is equivalent to GET method. we should show our form in the doGet method. When the user clicks submit, is equivalent to POST method in which we send data back to server. Hence in the doPost method, we retrieve the data using getParameter method.

From the above example we can create a login form, starting from creating a index.html page as follows

<!DOCTYPE html>
<html>
<body>
<form action=login method="post">
Please enter username and password:<br>
Username: <input type="text" name="username"><br>
Password <input type="text" name="password"><br>
<input type="submit">
</form>
</body>
</html>

We can also create this page using servlet,

public void showLoginForm(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Login</title>");
out.println("</head>");
out.println("<body>");
out.println("<br>Please enter username and password");
out.println("<form method=post>");
out.println("<br>Username: <input type=text name=username>");
out.println("<br>Password: <input type=text name=password>");
out.println("<br><input type=submit>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}

Deployment Description (web.xml)

It is a file that manages the requests that means it has all the information about like for which request and response which servlet file should be called.

Let’s take previous example, when user entered all details and click submit button, all the information should be processed and stored into a server. For which one servlet file should perform the operations.

Here the loginServlet file should be called which will process the requests, but out application does not know that we have to inform it. we can do this in web.xml file.

<servlet>
<servlet-name>servletdemo</servlet-name>
<servlet-class>com.chinmaya.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletdemo</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>

The 2 tags, <servlet> and <servlet-mapping> are bound to each other by a common sub-tag <servlet-name> which can be any name. Hence whenever a /login path is requested, from the web.xml it will be able to retrieve to correct servlet class which is LoginServlet (notice you have to provide package name with class name) from the common servlet name tag.

Web Annotation

Another way to link servlet class to url is to use web annotation. In the LoginServlet class, just before the class name, add the following: @WebServlet(“/login”).

Request Dispatcher

Suppose we have to call another servlet within one servlet, We can achieve this by using RequestDispatcher.

Let us take previous example, create a welcome page for the user, and the call should go from LoginServlet file then we have to add the following lines in the LoginServlet file.

RequestDispatcher rd = req.getRequestDispatcher("welcome");
req.setAttribute("username", username);
rd.forward(req, res);

We have sent the request to another file, but there should be another file to receive this request. Let’s create an WelcomeServlet named file.

public class WelcomeServlet extends HttpServlet{

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { String username = (String) req.getAttribute("username");

PrintWriter out = res.getWriter();
out.println("Hello: " + username);
}
}

Send Redirect

In RequestDispatcher we are calling another servlet from one servlet and the user does not know about this how internally the request is working.

But what if there comes an scenario where we have to inform an user that he/she is being redirected to another page, here we can use sendRedirect.

It will inform the user that he/she is being redirected to another page, We can follow the steps

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if (username.isEmpty() || password.isEmpty()) {
showLoginForm(req, res);
} else {
res.sendRedirect("welcome?user=" + username);
}
}

Here we are sending the request to WelcomeServlet.

public class WelcomeServlet extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

String username = req.getParameter("username");

PrintWriter out = res.getWriter();
out.println("Hello " + username);
}
}

And here we are fetching that request for further process.

JSP

JSP refers to java server pages. It is used to create dynamic web pages. We can say that it is an extension to java servlet because it provides more functionality than servlet.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because we can separate designing and development.

We can see to build a form in Server, we have to wrap each line of the HTML with PrintWriter and it can be quite a hassle. We can further improve this by using JSP.

Let us create a JSP file We can see to build a form in Server, we have to wrap each line of the HTML with PrintWriter and it can be quite a hassle. We can further improve this by using JSP.which will work similar like WelcomeServlet.java file

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome Page</title>
</head>
<body>
<%
String username = request.getParameter("user");
out.println("Hello user: " + username);
%></body>
</html>

Just like in servlet we were calling another servlet file from one servlet, here also we can call the new jsp file from servlet using RequestDispatcher and sendRedirect.

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if (username.isEmpty() || password.isEmpty()) {
showLoginForm(req, res);
} else {
res.sendRedirect("WelcomePage.jsp?user="+username);
}

}

Conclusion

Java Server Pages (JSP) is a server-side programming technology that allows the creation of a dynamic, platform-independent method for developing Web-based applications.

JSP have access to the whole family of Java APIs, including the JDBC API to access enterprise databases. JavaServer Pages (JSP) is a technology for creating Web pages that support dynamic content. This helps programmers embed java code in HTML pages by making use of specific JSP tags, most of which begin with <% and end with %>.

Servlets implement a component-based, platform-independent method for developing Web-based applications, without the performance restrictions of CGI programs. Servlets have access to the complete family of Java APIs, including the JDBC API to access enterprise databases. Servlets are platform independent because they are drafted in Java.Java security manager on the server implements a set of limitations to preserve the resources on a server machine.

--

--