Web Development using JSP & Servlet

So today we are talking about JSP and Servlet on web development. So before starting we have to know about client-server architecture.

Client-server architecture, a computer network architecture in which many clients request and receive service from a centralized server. Client computers provide an interface to allow a computer user to request the server's services and display the results which the server returns. Servers wait for requests to arrive from clients and then respond to them. Ideally, a server provides a standardized transparent interface to clients so that clients need not be aware of the specifics of the system that is providing the service.

In this web-world client send the request to the server and the server will respond. So there are two kinds of requests one is static requests and another is dynamic requests. If the client sent a dynamic request the request goes to the helper application which is present in the server. This Helper Application is also known as Web Container and in this web container, servlets are presents. Examples of web containers are Apache Tomcat, GlassFish, Jboss, Websphere, etc.

Servlets: It is a java file that takes the request from the client on the internet to fetch the value and it can process that request and provide the response in the format of the HTML page.

So when a request comes for XYZ.html in the server if there is no page called XYZ.html so the request is going to the deployment descriptor in the deployment descriptor we are mapping for which request which servlet to called. The file where we are doing this mapping called web.xml. The mapping is done by two tags one is servlet tag another is the servlet-mapping tag. In the servlet tag, we mention the class name and in the servlet-mapping tag, we are giving the url-pattern. By this mapping, the request is going to the servlet.

Example:

<servlet>
<servlet-name>comingsoon</servlet-name>
<servlet-class>mysite.server.ComingSoonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>comingsoon</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

There is also another way to mapping which is introduced in servlet 3.0 is annotation.

@WebServlet(urlPatterns = "/helloworld")
public class HelloWorldExample extends HttpServlet {

private static final long serialVersionUID = 1 L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter printWriter = resp.getWriter();
printWriter.print("helloworld");
}
}

So now we know how the servlet called but we have to know how we can create a servlet. As we previously discussed that servlet is a normal java class so we have to extend that java class to HttpServlet class and then the class will be able to take requests from the server, process that request, and send the response to the client. The response is in HTML format. The servlet helps to create dynamic web pages and also use for writing business logic because servlets are secure.

Advantages of Servlet:-

1. Better performance: because it creates a thread for each request, not process.

2. Portability: because it uses Java language.

3. Robust: JVM manages Servlets, so we don’t need to worry about the memory leak, garbage collection, etc.

4. Secure: because it uses java language.

Life Cycle of Servlet:-

  1. init
  2. service
  3. destroy

Working:-

a. Init:- When a servlet is run the first time then it calls the init method, Init method is used to initialize all the necessary properties required for the servlet.

b. Service:- To process the request, and send the response Servlet calls the service method. The service method invokes the doGet and doPost method.

doGet():-

  1. URL is used to send data.
  2. The request is not secured.
  3. The request is more efficient than Post.
  4. we can bookmark the URL.

doPost():-

  1. A large amount of data can be sent.
  2. Post is more secure.
  3. The request is less efficient.
  4. we can’t bookmark the URL.

We normally use post to send the data into the server and use get to fetch the data from the server.

c. Destroy:- It is called once just like the init method. When we want to destroy the servlet.

JSP(Java Server Pages):

In servlets, if we want to design and show that design into a webpage we have to write all the HTML tags inside java code more specific we have to create the object of printWriter, and using the object we have to write the HTML code and it was very difficult to manage. To solve this issue the concept of JSP is introduced where the developer can write the HTML code CSS code inside it. The only motive of JSP to create a front-end part of a web application also it has certain features that give the 9 implicit objects free we don't need to create that object. JSP also gives services like JSTL. It is used for view purposes we can’t write the business logic inside JSP pages and servlets are used as a controller and all the business logic is written in it.

But the problem with JSP that the web containers can’t run JSP pages so it is converted to servlet first and then it executes so it takes time to execute.

Example of JSP to Servlet Conversion:-

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="java.servlet.*;"%>  //directive tag
<% response.addDateHeader("Expires", 0); %>// scriptlet tag

<html><head><title>JSP</title></head>
<body><h1>Hello World!</h1>
<%! private int hits = 0; %>//declaration tag
You are visitor number <% synchronized(this) { out.println(++hits); } %>// scriptlet tag
since the last time the service was restarted.
<p>
This page was last updated: <%= new java.util.Date().toLocaleString() %>//expresion tag
</body></html>
import javax.servlet.*;//directive tag


public class HelloWorld2$jsp extends HttpJspBase {
private int hits = 0;//declaration tag

private static boolean _jspx_inited = false;

public void Service(HttpServletRequest request, HttpServletResponse response)// scriptlet tag
throws java.io.IOException, ServletException
{
JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
String _value = null;
try {
if (_jspx_inited == false)
synchronized (this) {
if (_jspx_inited == false) {
_jspx_init();
_jspx_inited = true;
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
response.addDateHeader("Expires", 0);
out.write("\r\n<html><head><title>JSP</title></head>\r\n<body><h1>Hello World!</h1>\r\n");
out.write("\r\nYou are visitor number ");
synchronized(this) { out.println(++hits); }
out.write("\r\nsince the last time the server was restarted.\r\n<p>\r\nThis page was last updated: ");
out.print( new java.util.Date().toLocaleString() );//expresion tag
out.write("\r\n</body></html>");

} catch (Throwable t) {
if (out != null && out.getBufferSize() != 0) out.clearBuffer();
if (pageContext != null) pageContext.handlePageException(t);
} finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
}
}
}

The above code snippet is an example that how a JSP page is converted to the servlet.

In this example we have seen some tags, so let's talk about that.

  1. Directive tag:- This tag is used to import, include anything to that current jsp page, and also with the help of this tag we can use some external tag also. By using <% ……%> this syntax on the JSP page we can do the above mention task.
  • <%@ page … %>: page tags use to specifies language, session, errorPage,import autoFlush etc.
  • <%@ include … %>: include is used to include page.
  • <%@ taglib … %>: Taglib is used to specifies the tag libraries.

2. Declaration tag:- This tag is used to declare variables or statements on the JSP page. In servlet, it is present inside of class but outside of service method. to declare something globally we use <%! …%> this tag called the declaration tag.

3. Scriplet tag:- Inside this tag we are writing the java code, when the JSP is converted to servlet whatever we write in it is going to the service method in servlet. By the use of <%….%> this tag, we are writing java code on the JSP page.

4. Expression tag:- This tag is used to print anything on the screen. by the help of <%=…%> this tag.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store