Differences Between Servlets and JSP
Differences Between Servlets and JSP
It is a server-side technology
which is used for creating dynamic web applications. Its design and functionality is similar to java Servlets.
A JSP is called by a client to provide a web service, when once the request is processed, JSP responds by
sending the results to the client.
Java Servlets and JavaServer Pages (JSP) are part of the Java EE(Enterprise Edition) platform and are
technologies used for creating dynamic web pages in Java
JSP differs from servlets in the way in which it is written. JSP is written using both HTML tags and JSP
tags. JSP tags are used to insert JAVA code into HTML pages. JSP combine HTML, Java code, and JSP tags .
So JSP is first converted into a servlet by the JSP container before processing the client’s request.
JSP contains two types of text: static data and dynamic data.
• static data can be expressed in any text-based format (like HTML, XML and WML)
• dynamic content can be expressed by JSP elements.
Servlet JSP
In Servlet, coding is difficult as compared to JSP. JSP is easy to code since it is tag based.
Servlet plays a controller role in MVC JSP is the View component in the MVC
approach. approach
Servlet can accept requests from all protocol JSP only accepts HTTP requests.
In Servlet can override the service() method. JSP cannot override its service() method.
It does not have inbuilt implicit objects. JSP includes inbuilt implicit objects.
There is no method for running JavaScript on While running the JavaScript at the client
the client side in Servlet. side in JSP, client-side validation is used.
Cannot create custom tags Can use JSP API to create custom JSP tags
Faster performance; users execute directly on Slower execution; users must compile into
web servers Servlets before executing
JSP is best suited for developing view content and designing applications that rely more heavily on HTML code,
using the presentation layer to help the application and user interact more effectively.
Servlets are often used as controller classes and are more applicable when designing and developing a web
application's business layer. The business layer is between the presentation and data access layers and involves
business logic, security, and supporting site architecture.
Java Server Pages(JSP) Life Cycle
The Java Server Pages (JSP) Life Cycle involves several stages from the initial creation of a JSP file to its
processing by the servlet container:
1. Translation: When a JSP file is accessed for the first time, the servlet container translates it into a Java
servlet. This involves converting JSP elements into Java code & creates a servlet class corresponding to
JSP.
2. Compilation: The generated servlet code is compiled into bytecode by the servlet container's compiler.
This bytecode is then loaded and executed by the Java Virtual Machine (JVM) when the JSP is accessed
by clients.
3. Initialization: After compilation, the servlet container loads the compiled servlet class and initializes it
by calling jspInt() . jspInt() is identical to init() method of servlet. It initializes objects and variables that
are used throughout the life cycle of JSP and also allocates necessary resources.
4. Request Processing: container invokes the servlet's service() method and retrieves the connection to
HTTP. The servlet then processes the request, generates dynamic content, and sends the response back
to the client.
5. Destruction: When the JSP is no longer needed or when the servlet container shuts down, the servlet is
destroyed. The servlet container calls the servlet's destroy() method, allowing it to release any held
resources and perform cleanup tasks like disconnecting from DB. Destroy() method is called
automatically when JSP terminates normally. It is not called when JSP terminates abruptly such as when
server crashes.
OR (in brief)
The lifecycle of JSP is grouped in phases.
Comment Used for documentation and for commenting out parts of <%- - any Text - -%>
JSP code.
Features of JSP:
✓ It does not require advanced knowledge of JAVA
✓ It is capable of handling exceptions
✓ Easy to use and learn
✓ It contains tags which are easy to use and understand
✓ Implicit objects are there which reduces the length of code
✓ It is suitable for both JAVA and non JAVA programmer
✓ Difficult to debug for errors.
✓ First time access leads to wastage of time
✓ It’s output is HTML which lacks features.
✓ You will see the same output, but it will take longer! But only the first time.
✓ If you reload it again, it will load normally.
✓ What is happening behind the scenes is that your JSP is being turned into a Java file, compiled, and
loaded. This compilation only happens once, so after the first load, the file doesn’t take long to
load anymore. (But every time you change the JSP file, it will be re-compiled again.)
hello.JSP :
❖ Notice that each time you reload the page in the browser, it comes up with the current time.
❖ The character sequence enclosed within <%= and %> contains Java expressions, which are
evaluated at run time.
❖ This enables JSP to generate dynamic HTML pages that change in response to user actions or vary
from user to user.
pgm to define and call method using JSP tags. Pgm to find square of a given number
<HTML>
<%-- s4.jsp --%> <%-- Comment Tag --%>
<HEAD>
<TITLE> JSP - DEFINING AND CALLING METHOD </TITLE>
</HEAD>
<BODY>
<%! int x=3;
int sqr (int n)
{
return n*n;
}
%>
<P> square of <%=x%> i s : <%=sqr(x)%> </P>
</BODY>
</html>
Output:
getQueryString() – Used for getting the query string associated to the JSP page URL. It is the string
associated to the URL after question mark sign (?).
This query string has to be parsed to extract value of fields using method getParameter(name) of JSP
request object. The getParameter() method requires an argument, which is the name of the field whose
value you want to retrieve
To retrieve the value of empid field of the above request string, the statement to be included in the JSP
program is :
<%! String eid = request.getParameter(empid); %>
Which copies the value of empid field from the request string (or object) into a string object eid.
There are 9 pre-defined implicit objects provided in JSP. Few of them used in every JSP pgm are:
1. Request
2. Response
3. Session
4. out.
• Other 5 are config, page context, application, exception , page object.
These objects are created by the programmer in servlets. But in JSP, they are built-in and are known as
implicit objects.
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
Output
Cookie class methods, response and request object are used to create and read a cookie.
1. addCookie() method, writes the cookie to the client's response.
2. getCookies() method, extracts and returns all the cookies from the client's request as an array
of Cookie objects
3. get Name() and getValue() methods, retrieves the name and value from each object of the
array of Cookie objects
JSP pgm to create and read cookie
J2.jsp file – creates a cookie with cookie name as EMPID and value “AN2356” given through browser
<html>
<head>
<title>JSP create cookie Page</title>
</head>
<body>
<%
String id = request.getParameter("empid");
Cookie ck= new Cookie("EMPID",id);
response.addCookie(ck);
%>
<a href ="read.jsp">click here to read cookie </a>
</body>
</html>
<html>
<head>
<title>JSP read cookie Page</title>
</head>
<body>
<%
Cookie [] c = request.getCookies();
for(int i=0;i< c.length; i++)
{
out.println("<br>Cookie name = " + c[i].getName()+ "<br>");
out.println("Cookie value = "+ c[i].getValue());
}
%>
</body>
</html>
Its corresponding html file is
Session Objects
✓ A JSP database system is able to share information among JSP programs within a session by using a
session object.
✓ Each time a session is created, a unique ID is assigned to the session and stored as a cookie.
✓ The unique ID enables JSP programs to track multiple sessions simultaneously while maintaining data
integrity of each session
✓ In addition to the session ID, a session object is also used to store other types of information, called
attributes.
✓ An attribute can be login information, preferences, or even purchases placed in an electronic
shopping cart.
Let's say that you built a Java database system that enables customers to purchase goods online. A JSP
program dynamically generates catalogue pages of available merchandise. A new catalogue page is
generated each time the JSP program executes. The customer selects merchandise from a catalogue page,
then jumps to another catalogue page where additional merchandise is available for purchase.
JSP database system must be able to temporarily store purchases made from each catalogue page;
otherwise, the system is unable to execute the checkout process. This means that purchases must be
accessible each time the JSP program executes.
There are several ways in which you can share purchases. You might store merchandise temporally in a table,
but then you'll need to access the DBMS several times during the session, which might cause performance
degradation.
A better approach is to use a session object and store information about purchases as session attributes.
Session attributes can be retrieved and modified each time the JSP program runs.
Code-1- creates a session attribute. illustrates how to assign information to a session attribute, In this
example, the program creates and initializes two String objects. One String object is assigned the name of
the attribute and ·the other String object is assigned a value for the attribute. Next, the program calls the
setAttribute() method and passes this method the name and value of the attribute.
The program begins by calling the getAttribute ames() method that returns names of all the attributes as an
Enumeration.
Next, the program tests whether or not the getAttributeNames() method returned any attributes. If so,
statements within the while loop execute, which assigns the attribute name of the current element to the
AtName String object. The AtName String object is then passed as an argument to the getAttribute()
method, which returns the value of the attribute. The value is assigned to the AtValue String object. The
program then sends the attribute name and value to the browser.