JSP and Servlet

Krishna Bankar
7 min readMar 7, 2021

Java Back-end web application development Technology

  1. Introduction
  2. Servlet
  3. JSP
  4. Other Related Topics
  5. Conclusion
  6. References
  7. Introduction :

Servlet and JSP are java back-end web development technology. Back-end Development refers to the server-side development. It focuses on databases, scripting, website architecture. It contains behind-the-scene activities that occur when performing any action on a website.

Java web application development with three tier architecture

Code written by back-end developers helps browsers to communicate with database information. Servlet mostly used for application controller. Whole business logic is written inside Servlet. JSP is mostly used for UI development at server-side. View are shown on HTML and JSP pages. When we talk about MVC patter application View is HTML and JSP, controller is Servlet and model is java Data Access Object like java been class and database activities classes.

2. Servlet :

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. To make custom servlet it is mendatory to extend HTTPServlet.

Servlet life cycle : It contains three methods :
a. init() : This methods used to initialize Servlet class.
b. service() : This methods used to process client request and respond.
b. destroy() : This methods is used to destroy Servlet at the end of class.

Servlet life cycle

There are two types of Servlet’s Generic Servlet and HTTPServlet :
a. Generic Servlet : It is used to handle any type of request and overriding service method is mendatory.
b. HTTPServlet : It is used to handle only HTTP request and it is required to overrid doGet and doPost method.

There are some helpful methods for Servlet ;
a. PrintWriter().getWriter().println(“string”) : used to writte anything on web page / on browser.
b. request.setAttribute(variable, value); : used to set value with some variable that can be get in another Servlet.
c. request.getAttribute(variable); : used to get value sent by another Servlet.

There are two methods to send request / data from one Servlet to another Servlet :
a. RequestDispatcher dispatcher = request.getRequestDispatcher(“Servlet”) : it contains some methods like :
— dispatcher.forward(request, response); used to forward request and carry data from one Servlet to another Servlet.
— dispatcher.include(request, response); used to include another Servlet with current Servlet content.
b. response.sendRedirect(request, response); used to send request to different url page that is not part of our local application.
— response.sendRedirect(“servlet-pattern”);
— request.getParameter() : used to get value from parameter.
— xxx.parseXxx() : used to parse value in xxx formate.

There are two ways to send values one Servlet to another Servlet :
— HttpSession : used to carry/set object’s from one Servlet to another Servlet through out the sesson.
— it has some sesson id too.
— sesson uses doGet method.
— Cookie : used to set array of object’s in response as cookie from one Servlet to another Servlet.
— there is no order of cookie in array.

3. JSP (Java Server Pages) :

It stands for Java Server Pages. It is a server side technology. In this JSP tags are used to insert JAVA code into HTML pages. It is an advanced version of Servlet Technology. It is a Web based technology helps us to create dynamic and platform independent web pages. A JSP file is a server-generated web page. It is similar to an . ASP or . PHP file, but contains Java code instead of ActiveX or PHP. The code is parsed by the web server, which generates HTML that is sent to the user’s computer.

JSP Life cycle :
This is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.

JSP life cycle

— JSP like working with HTML
— JSP provides so may Implecite objects like :
— PrintWriter out;
— HttpServletRequest request;
— HttpServletResponse response;
— HttpSession session;
— PageContext pageContext;
— ServletContext application;
— ServletConfig config;
— in HTML action we need to specify file.jsp
— all java code embided inside <% java code %>

There are four types of JSP tags :
i. directive tag : Three types of directive tags :
a. @page directive :
— add something for entire this page.
— used to import java packages with cama ‘,’ seperator.
— eg: <%@page import=”package1, package2, …”%>
b. @include directive :
— used to include other jsp page with current jsp page.
— <%@ include file=”fileName.jsp”%>
c. @taglib directive :
— we can work with different types of tags.
— <%@ taglib uri=”url” prefix=”someText” %>
— <someText : customTag>
note : directive contains atrribute1=”value1" atrribute2=”value2" …;
— some of atrributes and thier values are :
— language=”scripting language like java”
— extends=”ClassName”
— import=”fully qualified package”
— sesson=”true/false”
— autoFlush=”true/false” : to flush current used buffer.
— contentType=”ctingo”
— errorPage=”pageName.jsp”
— isErrorPage=”true/false”
— info=”information”
— isELIgnored=”true/false”
— isThreadSafe=”true/false”
ii. declaration tag : used to declaration java members within Servlet but outside service method.
— <%! variables, methods etc %>
iii. scriptlet tag : used to process java code that is consider inside service method.
— <% java code for processing %>
iv. expression tag : used to print on brower like out.println().
— <%=javaMember%> : it can be variables or method call.

JSTL : jsp standard tag liebrary.
— EL expression : ${<attributeName>}
— to used JSTL we need to add jstl liebrary to pom.xml and then build with mavin :
— <! — https://mvnrepository.com/artifact/jstl/jstl
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
— JSTL contains liebrary like :
— core
— function
— sql

4. Other Related Topics :

i. There are two ways to send values one Servlet to another Servlet :
— HttpSession : used to carry/set object’s from one Servlet to another Servlet through out the sesson.
— it has some sesson id too.
— sesson uses doGet method.
— Cookie : used to set array of object’s in response as cookie from one Servlet to another Servlet.
— there is no order of cookie in array.

ii. web.xml :
— contains web container used to despatch request.
— contains url-mapping for Servlet and Class.
— ServletContext : used to set parameter and its value in web.xml and that can be used by all Servlet globaly.
— <init-param> parameter and value </init-param>
— ServletConfig : used to set parameter and its value in web.xml in side a particular Servlet and it can be used ony by this Servlet.
— <context-param> parameter and value </context-param>

iii. Tomcate server :
— Tomcate server is web container used to handle client request and sessons.

iv. Servlet Configuration Annotation : without writting code in web.xml we can we can write Annotation in Servlet to dispatch request.
@WebServlet(“/<actionServletName>”)
— note : Annotation does not contains ‘;’ at the end.

v. Mavin Dependency for jdbc Driver : add these dependencies in pom.xml and then build with mavin dependencies. Used to download liebrary dynamicaly.
— for mysql database :
— <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
— for postgres database :
— <dependencies>
<! — https://mvnrepository.com/artifact/org.postgresql/postgresql
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.19</version>
</dependency>

vi. MVC : model view controler
— model is used to hold processed data.
— view is used to display data on brower like jsp pages.
— controler is used to process data / client request that is processed in servlet.

vii. Filter : used to filter client request for protection and Servlet security.
— client request goes to first deployement descripter that is web.xml.
— web.xml redirect request to filter Servlet. or We can use Annotation also.
— filter Servlet filter request and redirect to the Servlet.
— There are two types of filter config:
— filterConfig for a specific Filter.
— filterConfig for a specific Servlet.

viii. JDBC connection :
— with MySQL :
— Class.forName(“com.mysql.cj.jdbc.Driver”);
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/<yourDBname>”, “<userName>”, “<password>”);
— with PostgreSQL :
— Class.forName(“org.postgresql.Driver”);
Connection connection = DriverManager.getConnection(“jdbc:postgresql://localhost:5432/<yourDBname>”, “<userName>”, “<password>”);

ix. Clear cookie in browser or do not store cookie or prevent to access back page :
— response.setHeader(“Cache-Control”, “no-store”, “must-revalidate”); // HTTP 1.1
— response.setHeader(“pragma”, “no-cache”); // HTTP 1.0
— response.setHeader(“Expires”, “0”); // Proxies

x. Prevent direct access jsp / servlet with session object :
— setAttribute at login page :
HttpSession session = request.getSession();
session.setAttribute(“attribute”, value);
— getAttribute at login forwarded page :
— in jsp session.getAttribute(“attribute”);
— in servlet HttpSession session = request.getSession();
session.getAttribute(“attribute”);

5. Conclusion :

Servlet and JSP are used as back-end technology in web app development. In web application MVC patter; JSP and HTML works as View, Servlet works as Controller and java been class used as Model that is used to hold database result and send View based on Controller request. Client sends request from brower or any client device, at first request goes to web.xml that is also called request dispatcher. It send request to the requested Servlet.

Web.xml contains mapping for requested Servlet. Some time we can have Filter in between request dispatcher that is web.xml and actual Servlet. Filter is used for security purpose, It checks some condition to forward this request to actual Servlet. It can have multiple Filter’s for different condition check or can not have Filter that is optional. Filter is same as Servlet class but to intercept between web.xml and actual Servlet.

6. References :

References for further reading :
— Youtube tutorial JSP and Servlet : https://www.youtube.com/watch?v=OuBUUkQfBYM
https://www.javatpoint.com/servlet-tutorial
https://beginnersbook.com/2013/05/servlet-tutorial/
https://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html
https://www.javatpoint.com/jsp-tutorial
https://www.tutorialspoint.com/jsp/index.htm
https://beginnersbook.com/jsp-tutorial-for-beginners/

--

--