0% found this document useful (0 votes)
46 views11 pages

Differences Between Servlets and JSP

Uploaded by

hitharth08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views11 pages

Differences Between Servlets and JSP

Uploaded by

hitharth08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

In Java, JSP stands for Jakarta Server Pages( (formerly Java Server Pages).

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.

Differences between servlets and JSP:

Servlet JSP

Servlet is a java code. JSP is a HTML-based code.

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

JSP is slower in terms of compilation because


Servlet is faster than JSP in compilation
first it has to be translated and then complied

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.

Session management is not enabled by In JSP session management is automatically


default, user have to enable it explicitly. enabled.
Servlet JSP

In JSP business logic is separated from


In Servlet implementation business logic and
presentation logic by using JavaBeans
presentation logic is combined.
technology

Modification in Servlet is a time-consuming


JSP modification is fast, just need to click the
compiling task because it includes reloading,
refresh button.
recompiling and restarting the server.

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.

Packages can be imported anywhere in the


Packages are to be imported on the top of
JSP program (i.e, bottom , middleclient-side,
the program.
or top )

Cannot create custom tags Can use JSP API to create custom JSP tags

Before the execution, JSP is compiled in Java


Servlets are hosted and executed on Web
Servlets and then it has a similar lifecycle as
Servers.
Servlets.

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.

• The process starts from the JSP page translation


• Generated java Servlet files have complied into a java Servlet class.
• After compilation, the class loading is done in a web container, and this is where the execution phase
gets start.
• In the Initialization phase, jspInit() is called after the instance was created.
• Then jspService() is called to serve the request.
• jspDestroy() is called to relinquish/release the resources.
JSP Tags : also known as Scriptlet tags or Scripting elements are used to insert java code inside the jsp.
They are used to perform various tasks such as
• declaring variables and methods
• writing expressions
• calling other JSP pages.

The different types of scripting elements are

JSP Tag Brief Description Tag Syntax


Directive <%@ directives %>
Commands the JSP virtual engine to perform a specific task
Declaration <% ! variable dceclaration &
Declares and defines methods, objects and variables that are
method definition %>
available to other components of JSP pgm.
Scriplet <% some Java code %>
Contains commonly used java control statements and loops
Expression Used for an expression statement whose result replaces the <%= an Expression %>
expression tag when JSP virtual engine resolves JSP tags.

Comment Used for documentation and for commenting out parts of <%- - any Text - -%>
JSP code.

Directive tag: there are 3 commonly used directives:


1. page - used to import java packages into JSP program , specify the programming language etc.
2. include – inserts a specified file into JSP program
3. taglib - specifies a file that contains a tag library

Eg for each tag :

<%@ page import = “ import java.sql.*; “ %>


<%@ include file = “ jsp\ addck.jsp“ %> → includes addck.jsp file located in jsp directory
<%@ taglib uri = “mytags.tld” %> → loads mytags.tld library

JSP Expression tag: It evaluates and convert the expression to a string.


Eg for expression tag :

The square root of 5 is <%= Math.sqrt(5) %>


Current time is: <%= new java.util.Date() %>

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.

Creating a simple JSP Page


• JSP simply puts Java inside HTML pages.
• You can take any existing HTML page and change its extension to “.jsp” instead of “.html”.
• Now load the new file, with the “.jsp” extension, in your browser.

✓ 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 :

Adding dynamic content via expressions:


JSP has ability to embed Java. Put the following text in a file with .jsp extension (let us call it hello.jsp) ,
place it in your JSP directory, and view it in a browser.
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>

❖ 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.

Sample code showing different types of JSP Tags:

<%-- s6.jsp --%> <%-- Comment Tag --%>

<%@ page language="java" %> <%-- Directive Tag --%>


<%! int count = 0; %> <%-- Declaration Tag --%>
<% count++; %> <%-- Scriptlet Tag --%>
Welcome! You are visitor number<%= count %> <%-- Expression Tag --%>
Output:

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:

Pgm to illustrate the use of conditional statements


using jsp tags. Pgm to display the result.
Request String
The browser generates a user request string whenever the Submit button is selected. user request string
consists of the URL and the query string.

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 (?).

below is the sample URL with query string:

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.

The request object is an instance of HttpServletRequest , response object is an instance of


HttpServletResponse. The out object is an instance of the JspWriter that is used to send a response to the
client.
Copying the values from the multi-valued filed is handled using getParameterValues() method. Its usage in
JSP pgm is given below:
Example of JSP request implicit object – Pgm to demonstrate how parameters
are accessed from html using jsp
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>

Output

JSP cookie handling


A cookie is a small piece of information created by a JSP program that is stored on the client's hard disk by
the browser. Cookies are used to store various kinds of information, such as user preferences and an ID that
tracks a session with a JSP database system.

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>

Read.jsp – reads a cookie

<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.

Code- 2 reads session attributes.

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.

You might also like