Understanding Servlet and JSP

Aditya Gawraw
4 min readNov 12, 2023

--

Java used to build backend and dynamic HTML pages as response via servlet and JSP

MVC Architecture for Java Servlet and JSP
MVC Architecture for Servlet and JSP

Web Basics

Before learning about Servlet and JSP let's brush over web basics like server, client, HTTP, etc.

Server: Servers are programs running on specific machines that serve the clients which are other computers. Based on the service they provide servers can be of many types such as web servers, database servers, file servers, mail servers, etc. Each of them handles requests in the form of different protocols like HTTP/HTTPS, FTP, SMTP, etc.

Client: The client can be any computer that is capable of sending requests and receiving responses.

HTTP: Hypertext Transfer Protocol is a protocol used to transfer data like HTML documents. It's a set of rules that servers and clients follow on how communication is made between them and data is transferred between them over a network.

Servlet

Servlets are Java programs that handle requests and provide responses to the web server. A servlet can be used to provide dynamic web pages. In Java servlet is an interface that only defines life cycle methods.

GenericServlet class implements the Servlet interface but we can not use any requests made in HTTP. For handling HTTP requests we can use the HttpServlet class which extends the GenericServlet class. For handling different kinds of requests we use different user-defined classes extending HttpServlet class.

Servers contain web containers or servlet containers where the objects of servlets are created. Web containers handle the life cycle of servlet objects.

Web container loads the servlet objects if a request related to that servlet is received for the first time. Otherwise, it continues with the later stages of the life cycle of the servlet. For handling multiple requests web container makes different threads and runs them separately.

In general, we use HttpServlet class objects to handle all the HTTP requests. Some of the methods of the HttpServlets class are:

  1. doGet(): It is used to handle GET method requests.
  2. doPost(): It is used to handle POST method requests.
  3. service(): It can be used to handle all kinds of HTTP methods such as GET, POST, DELETE, PUT, etc.
@WebServlet("/welcomeUser")
public handlePageRequest extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse response){
String name = request.getParameters("name");
String email= request.getParameters("email");

PrintWriter out = response.getWriter();
out.println("hello "+name);
}
}

Deployment Descriptor: It is the configuration file that contains the information about servlet mapping for web containers. It is stored in XML format in a file called web.xml. We can now use annotations to map the servlets which saves many lines of code.

<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

Some Important topics used in Servlets:

  1. PrintWriter: It is a class that can be used to print formatted output in response. The response object of HttpServletResponse has a method called getWriter() which returns a writer object.

2. RequestDispatch: It can be used to send requests and responses to another resource on the same server like Servlets or JSP file.

3. sendRequest(): It can be used to redirect the request and response object to a servlet or JSP which might be on another server.

4. ServletContext: For an application if we are using some value many times in different servlets then we can define that value inside the servlet context. These values can be retrieved by using the getInitParameter(name) method and values can be initialized inside the web.xml file.

5. ServletConfig: During into() method invocation a config object is passed as a parameter with is used to configure some value inside the servlet only. This value can be used anywhere inside the servlet object and different config objects are instantiated for different servlets. The same getInitParameter(name) method can be used to retrieve the value from the config object.

JSP(Java Server Page)

We can write HTML code inside servlets and send it as a response via PrintWrite object but it’s very inconvenient. JSP provides a way to write Java code inside the HTML page so that it becomes easy to write the logic and style the page.

JSP contains different tags to write Java code inside HTML such as:

  1. Scriptlet: In this tag, we can write any amount of Java code. The code inside the scriptlet is placed inside the service method of the implicitly generated object.
<% 
// java code
%>

2. Declaration: It can be used to write variables and methods. The code inside the declaration tag is placed outside the service() method.

<%! 
// field or method declaration
%>

3. Expression: It can be used to print the output stream in the response. We can also use out.print() method to achieve the same result but the expression tag reduces the amount of code and can be used to output in the middle of HTML tags.

<%= 
// output statement
%>

JSP container provides implicit objects from servlets to make it more useful. Some of these pre-defined objects are as follows:

  1. request: Instance of HttpServletRequest class.
  2. response: Instance of HttpServletResponse class.
  3. out: Instance of JspWriter class.
  4. session: Instance of HttpSession class.
  5. exception: Instance of the Exception class.

Why use servlet if all functionality can be achieved by JSP?

At compile time all jsp file code is first converted to Java code. Servlets are originally written in Java form. Because of this writing logical code related to requests, responses, database connections, etc. in servlets makes it faster for the server to respond than writing in JSP.

--

--