0% found this document useful (0 votes)
30 views

Module 2

The document discusses Java Server Pages (JSP) technology. It provides an overview of JSP including how JSP pages are converted to servlets and the JSP lifecycle. It also discusses the need for JSP, advantages of JSP over servlets, basic JSP syntax including scripting elements, directives, actions, and invoking Java code with scripting elements.

Uploaded by

Every Thing
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)
30 views

Module 2

The document discusses Java Server Pages (JSP) technology. It provides an overview of JSP including how JSP pages are converted to servlets and the JSP lifecycle. It also discusses the need for JSP, advantages of JSP over servlets, basic JSP syntax including scripting elements, directives, actions, and invoking Java code with scripting elements.

Uploaded by

Every Thing
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/ 14

Module-2 Java Server Pages 18MCA41

Introduction to JSP

2.1 Overview of JSP: JSP Technology


 JSP technology is used to create dynamic web applications. JSP pages are easier to
maintain then a Servlet.
 JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while
JSP adds Java code inside HTML using JSP tags.
 JSP enables us to write HTML pages containing tags, inside which we can include
powerful Java programs.
 JSP pages are converted into Servlet by the Web Container. The Container translates
a JSP page into servlet class source(.java) file and then compiles into a Java Servlet
class.

 There are three main types of JSP constructs that you embed in a page:
o scripting elements
o directives
o actions
2.1.1 lifecycle of JSP
JSP pages are saved with .jsp extension which lets the server know that this is a JSP page and
needs to go through JSP life cycle stages.

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 1


Module-2 Java Server Pages 18MCA41

2.2 Need of JSP


 JSP provides an easier way to code dynamic web pages.
 JSP does not require additional files like, java class files, web.xml etc
 Any change in the JSP code is handled by Web Container (Application server like
tomcat), and doesn't require re-compilation.
 JSP pages can be directly accessed, and web.xml mapping is not required like in
servlets.

2.2 Advantages of JSP


 Extension to Servlet
o JSP technology is the extension to servlet technology. We can use all the
features of servlet in JSP. In addition to, we can use implicit objects, predefined
tags, expression language and Custom tags in JSP, that makes JSP development
easy.
 Easy to maintain
o JSP can be easily managed because we can easily separate our business logic
with presentation logic. In servlet technology, we mix our business logic with
the presentation logic.
 Fast Development: No need to recompile and redeploy
o If JSP page is modified, we don't need to recompile and redeploy the project.
The servlet code needs to be updated and recompiled if we have to change the
look and feel of the application.
 Less code than Servlet
o In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that
reduces the code. Moreover, we can use EL, implicit objects etc

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 2


Module-2 Java Server Pages 18MCA41

2.4 Basic syntax


There are four different types of elements you can use in JSP.

 Scripting elements
 Comments
 Directives
 Actions
Scripting elements

 There are three types of scripting elements in JSP


o Scriptlets - A scriptlet tag is used to execute java source code in JSP.
 General form:

<% java source code %>

 Example:

1. <html>
<body>
<% out.print("welcome to jsp"); %>
2. </body>
3. </html>

o Declarations—is used to declare fields and methods.


 General form:

<%! field or method declaration %>

 Example

<html>
<body>
<%! int data=50 %>
</body>
</html>

o Expressions—Contains a Java expression that the server evaluates. The result


of the expression is inserted into the Web page.

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 3


Module-2 Java Server Pages 18MCA41

 General form:

<%= Java Expression %>

 Example:

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

 Comments or Template text


o In many cases, a large percentage of your JSP page just consists of static HTML,
known as template text. In almost all respects, this HTML looks just like normal
HTML, follows all the same syntax rules, and is simply “passed through” to the
client by the servlet created to handle the page.
o If you want a comment to appear in the JSP page use the below form

<%-- JSP Comment --%>

 Directives
o JSP directives let you give directions to the server on how a page should be
processed. There are three directives in JSP.
Directive Description
<%@page...%> defines page dependent properties such as
language, session, errorPage etc.
<%@ include…%> defines file to be included.
<%@ taglib…%> declares tag library used in the page

 Actions
o The action tags are used to control the flow between pages and to use Java
Bean. The Jsp action tags are given below.
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include
mostly.
jsp:fallback can be used to print the message if plugin is working. It is
used in jsp:plugin.

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 4


Module-2 Java Server Pages 18MCA41

Extra questions

 Difference between get() and post

GET POST
HTTP The request contains only Along with request line and header it also
Request the request line and HTTP contains HTTP body.
header
Parameter The form elements are The form elements are passed in the body of
Passing passed to the server by the HTTP request.
appending at the end of the
URL
Size The parameter data is Can send huge amount of data to the server.
limited(the limit depends
on the container)
Usage Generally used to fetch Generally used to process the sent data
some information from the
host.

 sendRedirect
o In case of sendRedirect() method, the request is transferred to another resource
to a different domain or the different server for further processing
o When developers use the sendRedirect(), the web-container transfers the
request to a client or a browser so that the URL given inside
the sendRedirect() method is visible as a new request to the client
o In case of sendRedirect() call, the old request and response object is lost because
it is treated as a new request by the browser
o In browser’s address bar, developers are able to see the new redirected address
i.e. it is not transparent
o sendRedirect() is slower as one extra round trip is required i.e. The complete
new request is created and the old request object is lost
o In case of sendRedirect() call, if developers want to store the data they will do
it in a Session object or pass it along the value with the URL

 sendError
o The javax.servlet.http.HttpServletResponse class has two
versions of the sendError( ) method:
 one that takes an int parameter representing the HTTP response
code (such as 500), and the other taking an int parameter and
a String error message.
 The String parameter is used to display a message to the client if an
error page is not configured for that particular response code.

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 5


Module-2 Java Server Pages 18MCA41

2.5 Invoking java code with JSP scripting elements

 JSP Scripting element are written inside <% %> tags. These code inside <% %> tags
are processed by the JSP engine during translation of the JSP page. Any other text in
the JSP page is considered as HTML code or plain text.

2.6 Creating Template Text


 JSP document consists of static text (usually HTML), known as template text.
 There are two minor exceptions to the “template text is passed straight through” rule.
First, if you want to have in the output, you need to put in the template text. Second, if
you want a comment to appear in the JSP page but not in the resultant document, use
o <%-- JSP COMMENTS --%>
 HTML comments of the form are passed through to the client normally
o <!-- HTML COMMENTS -->

2.7 Invoking java code from JSP


 There are a number of different ways to generate dynamic content from JSP, as
illustrated in the below figure.

2.7.1 Types of JSP Scripting Elements


 JSP scripting elements allows to insert Java code into the servlet that will be generated
from the JSP page. There are three forms:

1. Expressions of the form, which are evaluated and inserted into the servlet’s
output.
2. Scriptlets of the form, which are inserted into the servlet’s _jspService
method (called by service).
3. Declarations of the form, which are inserted into the body of the servlet class,
outside any existing methods.
4. Directive is used to provide instructions to the container.

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 6


Module-2 Java Server Pages 18MCA41

2.8 Limiting java code in JSP


 There are two options
o Put 25 lines of Java code directly in the JSP page
o Put those 25 lines in a separate Java class and put 1 line in the JSP page that
invokes it
 Why is the second option much better?
o Development- Write the separate class in a Java environment (editor or IDE),
not an HTML environment
o Debugging- If there are syntax errors, it is immediately seen at compile time.
o Testing. You can write a test routine with a loop that does 10,000 tests and
reapply it after each change.
o Reuse. You can use the same class from multiple pages.

2.9 Using jsp expressions


 A JSP expression is used to insert values directly into the output. It has the following
form.
o <%= Java Expression %>
 The expressions are
o evaluated,
o converted to a string, and
o inserted in the page.
 This evaluation is performed at runtime (when the page is requested) and thus has full
access to information about the request.
 For example, the following shows the usage of expression.
o Current time: <%= new java.util.Date( ) %>
o To display user name :<%= “welcome” + request.getParameter(“uname)”%>
o To evaluate the expression <%= 2*10 %>

2.9.1 Predefined Variables (or implicit objects)


 To simplify these expressions, a number of predefined variables (or “implicit objects”).
are used.
 These Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being
explicitly declared.
 For example you can retrieve HTML form parameter data by using request variable,
which represent the HttpServletRequest object.

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 7


Module-2 Java Server Pages 18MCA41

The “request” object is implicit


here, associated with
HttpServletRequest object
<%
String user = request.getParameter(“user”);
%>

The ”out” object is implicit in JSP,


associated with JspWriter object

Hello, <% out.println(user); %>

 Following are the JSP implicit object:

Implicit Object Description


Request The HttpServletRequest object associated with the request.
response The HttpServletRequest object associated with the response
that is sent back to the browser
Session The HttpSession object associated with the session for the
given user of request.
Out The JspWriter object associated with the output stream of the
response.
Application The ServletContext object for the web application.
Exception The exception object represents the Throwable object that was
thrown by some other JSP page.

2.9.1.1 Jsp/Servlet Correspondence


o It is actually quite simple: JSP expressions basically become print (or write)
statements in the servlet that results from the JSP page.
o Whereas regular HTML becomes print statements with double quotes around
the text, JSP expressions become print statements with no double quotes.
o Instead of being placed in the doGet method, these print statements are placed
in a new method called _jspService that is called by service for both GET and
POST requests.
o out in a JSP page is a JspWriter, so you have to modify the slightly simpler
PrintWriter that directly results from a call to getWriter. So, don’t expect the
code your server generates to look exactly like this.

Example: Sample JSP Expression: Random Number

<H1>A Random Number</H1>


<%= Math.random() %>

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 8


Module-2 Java Server Pages 18MCA41

Representative Resulting Servlet Code: Random Number

public void _jspService(HttpServletRequest request,


HttpServletResponse response)
}throws ServletException, IOException {

HttpSession session = request.getSession();


JspWriter out = response.getWriter();

out.println("<H1>A Random Number</H1>");


out.println(Math.random());
...

2.9.2 Example: JSP Expression

<!DOCTYPE html>
<html>
<head><title>JSP Page</title></head>
<body>
<h1>JSP Expression</h1>
<UL>
<li>Current time: <%= new java.util.Date() %></li>
<li>Server: <%= application.getServerInfo() %></li>
<li>Session ID: <%= session.getId() %></li>
<li> Expression Evaluation: <%= 2 * 6% ></li>
</UL>
</body>
</html>

2.10 Comparing servlets and jsp

JSP Servlet
JSP is a web page scripting language that can Servlets are already compiled which also
generate dynamic content creates dynamic web content
JSP runs slower compared to servlet as it takes Servlets run faster compared to JSP.
compilation time to convert into java Servlets

It’s easier to code in JSP than in Java Its little much code to write here.
Servlets.

In MVC, jsp act as a view. In MVC, servlet act as a controller.


JSP are generally preferred when there is not servlets are best for use when there is
much processing of data required. more processing and manipulation
involved.

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 9


Module-2 Java Server Pages 18MCA41

The advantage of JSP programming over There is no such custom tag facility in
servlets is that we can build custom tags which servlets.
can directly call Java beans.

We can achieve functionality of JSP at client There are no such methods for servlets.
side by running JavaScript at client side.

Example in Servlet: ThreeParams.java

public class ThreeParams extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println("<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "\n" +

" <LI><B>param2</B>: "


+ request.getParameter("param2") + "\n" +

" <LI><B>param3</B>: "


+ request.getParameter("param3") + "\n" +

"</UL>\n" +
"</BODY></HTML>"); } }

Example in JSP: ThreeParams.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">


<HTML>
<HEAD>
<TITLE>Reading Three Request Parameters</TITLE> </HEAD>
<BODY>
<H1>Reading Three Request Parameters</H1>
<UL>
<LI><B>param1</B>: <%= request.getParameter("param1") %>
<LI><B>param2</B>: <%= request.getParameter("param2") %>
<LI><B>param3</B>: <%= request.getParameter("param3") %>
</UL>
</BODY></HTML>

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 10


Module-2 Java Server Pages 18MCA41

2.11Writing scriptlets.
 Scriptlet Tag allows to write java code inside JSP page
 Scriptlet tag implements the _jspService method functionality by writing
script/java code.
 Scriptlets have the following form:

<% Java Code %>

 Scriptlets have access to the same automatically defined variables as do expressions


(request response, session, out, etc.). So, for example, if you want to explicitly send
output to the resultant page, you could use the out variable, as in the following example.

<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
---------------------------------------------------------
Or combination of a scriptlet and a JSP expression, as below
<% String queryData = request.getQueryString(); %>
Attached GET data: <%= queryData %>
---------------------------------------------------------
Or single JSP expression, as here
Attached GET data: <%= request.getQueryString() %>

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 11


Module-2 Java Server Pages 18MCA41

Scriptlets Example: Printing even number

<html>
<head><title>Even number program in JSP</title></head>
<body>
<%
for(int i=0;i<=10;i++)
{
if((i%2)==0)
{
out.print("Even number :"+i);
out.print("<br>");
}
}
out.println(“<br><br><br>First 10 odd numbers are”);
for(i=0;i<=10;i++)
{
if(i%2!=0)
{
out.println(i);
}
}
%>
</body>
</html>

2.12 For example, Using Scriptlets to make parts of jsp conditional


 Another use of scriptlets is to conditionally output HTML or other content that is not
within any JSP tag.
 Key to this approach are the facts that
(a) code inside a scriptlet gets inserted into the resultant servlet’s _jspService
method (called by service) exactly as written and
(b) that any static HTML (template text) before or after a scriptlet gets converted
to print statements.
 This behavior means that scriptlets need not contain complete Java statements and
that code blocks left open can affect the static HTML or JSP outside the scriptlets. For
example, consider the JSP fragment that contains mixed template text and scriptlets.

<body>
<% if (Math.random() < 0.5) { %>
<H1>Have a <I>nice</I> day!</H1>
<% } else { %>
<H1>Have a <I>lousy</I> day!</H1>
<% } %>
</body>

 You probably find the bold part a bit confusing, Simply follow the rules for how JSP
code gets converted to servlet code. Once you think about how this example will be

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 12


Module-2 Java Server Pages 18MCA41

converted to servlet code by the JSP engine, you get the following easily understandable
result.

if (Math.random() < 0.5) {


out.println("<H1>Have a <I>nice</I> day!</H1>");
} else {
out.println("<H1>Have a <I>lousy</I> day!</H1>");
}

 Overuse of this approach can lead to JSP code that is hard to understand and maintain.
Avoid using it to conditionalize large sections of HTML, and try to keep your JSP pages
as focused on presentation (HTML output) tasks as possible.

2.13 Using declarations


 A JSP declaration lets you define methods or fields that get inserted into the main body
of the servlet class (outside the _jspService method that is called by service to process
the request).
 Declaration is made inside the servlet class but outside the service method.
 A declaration has the following form:

<%! Field or Method Definition %>

 Since declarations do not generate output, they are normally used in conjunction with
JSP expressions or scriptlets.
 In principle, JSP declarations can contain field (instance variable) definitions, method
definitions, inner class definitions, or even static initializer blocks: anything that is legal
to put inside a class definition but outside any existing methods.
 In practice, however, declarations almost always contain field or method definitions.
 Example:

<H1>Some Heading</H1>
<%!
private String randomHeading() {
return("<H2>" + Math.random() + "</H2>");
}
%>
<%= randomHeading() %>

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 13


Module-2 Java Server Pages 18MCA41

2.14 Declaration Example:


 JSP snippet prints the number of times the current page has been requested.

<%! private int accessCount = 0; %>

Accesses to page since server reboot:


<%= ++accessCount %>

Prepared By: Raghu Prasad K, AP Dept. Of MCA, RNSIT 14

You might also like