Web Technologies
Web Technologies
UNIT IV
JAVA SERVER PAGES
Introduction to JSP: The Problem with Servlet. The Anatomy of a JSP Page, JSP Processing. JSP
Application Design with MVC Setting Up and JSP Environment, JSP Declarations, Directives,
Expressions, Code Snipplets, implement objects, Requests, Using Cookies and Session for Session
The Servlet technology and JavaServer Pages (JSP) are the two main technologies for
developing java Web applications. When first introduced by Sun Microsystems in 1996, the
Servlet technology was considered superior to the reigning Common Gateway Interface
(CGI) because servlets stay in memory after they service the first requests. Subsequent
requests for the same servlet do not require instantiation of the servlet‘s class therefore
enabling better response time.
Servlets are Java classes that implement the javax.servlet.Servlet interface. They are
compiled and deployed in the web server. The problem with servlets is that you embed
HTML in Java code. If you want to modify the cosmetic look of the page or you want to
modify the structure of the page, you have to change code. Generally speaking, this
is left to the better hands (and brains) of a web page designer and not to a Java developer.
PrintWriter pw = response.getWriter();
pw.println("<html><head><title>Testing</title></head>"); pw.println("<body
bgcolor=\"# ffdddd\"> ");
As seen from the example above this method presents several difficulties to the web
developer:
1. The code for a servlet becomes difficult to understand for the programmer.
2. The HTML content of such a page is difficult if not impossible for a web designer to
understand or design.
3. This is hard to program and even small changes in the presentation, such as the page‘s
background color, will require the servlet to be recompiled. Any changes in the
HTML content require the rebuilding of the whole servlet.
4. It's hard to take advantage of web-page development tools when designing the
application interface. If such tools are used to develop the web page layout, the
generated HTML must then be manually embedded into the servlet code, a process
which is time consuming, error prone, and extremely boring.
5. In many Java servlet-based applications, processing the request and generating the
response are both handled by a single servlet class.
6. The servlet contains request processing and business logic (implemented by methods ),
and also generates the response HTML code, are embedded directly in the servlet code.
JSP solves these problems by giving a way to include java code into an HTML page using
scriptlets. This way the HTML code remains intact and easily accessible to web designers,
but the page can sill perform its task.
In late 1999, Sun Microsystems added a new element to the collection of Enterprise Java
tools: JavaServer Pages (JSP). JavaServer Pages are built on top of Java servlets and
designed to increase the efficiency in which programmers, and even nonprogrammers, can
create web content.
Instead of embedding HTML in the code, you place all static HTML in a JSP page, just as in
a regular web page, and add a few JSP elements to generate the dynamic parts of the page.
The request processing can remain the domain of the servlet, and the business logic can be
handled by JavaBeans and EJB components.
A JSP page is handled differently compared to a servlet by the web server. When a servlet is
deployed into a web server in compiled (bytecode) form, then a JSP page is deployed in its
original, human-readable form.
When a user requests the specific page, the web server compiles the page into a servlet and
from there on handles it as a standard servlet.
This accounts for a small delay, when a JSP page is first requested, but any subsequent
requests benefit from the same speed effects that are associated with servlets.
The Problem with Servlet
• Servlets are difficult to code which are overcome in JSP. Other way, we can say, JSP is
almost a replacement of Servlets, (by large, the better word is extension of Servlets),
where coding decreases more than half.
• In Servlets, both static code and dynamic code are put together. In JSP, they are
separated. For example,In Servlets:
out.println(―Hello Mr.‖ + str + ‖ you are great man‖);
where str is the name of the client which changes for each client and is known as dynamic
content. The strings, ―Hello Mr.‖ and ―you are great man‖ are static content which is the
same irrespective of client. In Servlets, in println(), both are put together.
• In JSP, the static content and dynamic content is separated. Static content is written in
HTML and dynamic content in JSP. As much of the response comprises of static content
(nearly 70%) only, the JSP file more looks as a HTML file.
• Programmer inserts, here and there, chunks of JSP code in a running HTML developed
by Designer. As much of the response delivered to cleint by server comprises of static
content (nearly 70%), the JSP file more looks like a HTML file. Other way we can say,
JSP is nothting but Java in HTML (servlets are HTML
• in Java); java code embedded in HTML.
• When the roles of Designer and Programmer are nicely separated, the product
development becomes cleaner and fast. Cost of developing Web site becomes cheaper as
Designers are much paid less than Programmers, especially should be thought in the
present competitive world.
• Both presentation layer and business logic layer put together in Servlets. In JSP, they can
be separated with the usage of JavaBeans.
• The objects of PrintWriter, ServletConfig, ServletContext, HttpSession and
RequestDispatcher etc. are created by the Programmer in Servlets and used. But in JSP,
they are builtin and are known as "implicit objects". That is, in JSP, Programmer never
creates these objects and straightaway use them as they are implicitly created and given
by JSP container. This decreases lot of coding.
• JSP can easily be integrated with JavaBeans.
• JSP is much used in frameworks like Sturts etc.
• With JSP, Programmer can build custom tags that can be called in JavaBeans directly.
Servlets do not have this advantage. Reusability increases with tag libraries and JavaBean
etc.
• Writing alias name in <url-pattern> tag of web.xml is optional in JSP but mandatory in
Servlets.
• A Servlet is simply a Java class with extension .java written in normal Java code.
• A Servlet is a Java class. It is written like a normal Java. JSP is comes with some
elements that are easy to write.
Anatomy of JSP
JSP Processing
Once you have a JSP capable web-server or application server, you need to know the
following information about it:
• Where to place the files
• How to access the files from your browser (with an http: prefix, not as file:)
Of course, it is not very useful to just write HTML pages with a .jsp e xtension! We now
proceed to see what makes JSP so useful
Adding dynamic content via expressions
As we saw in the previous section, any HTML file can be turned into a JSP file by changing
its extension to .jsp. Of course, what makes JSP useful is the 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 sequences
<%= and %> enclose Java expressions, which are evaluated at run time.
This is what makes it possible to use JSP to generate dyamic HTML pages that change in
response to user actions or vary from user to user.
JSP Expressions start with Syntax of JSP Scriptles are with <%= and ends with %>.
Between these this you can put anything and that will convert to the String and that will be
displayed.
Example: <%="Hello World!" %> Above code will display 'Hello World!'
2. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in
_jspService method by the JSP engine.
Syntax of JSP Scriptles are:
<% //java codes
%>
JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code in the
JSP Scriptlets. JSP Engine places these code in the _jspService() method. Variables available
to the JSP Scriptlets are:
3. Directives
A JSP "directive" starts with <%@ characters. In the directives we can import packages,
define error handling pages or the session information of the JSP page.
Syntax of JSP directives is:
<%@directive attribute="value" %>
a. page: page is used to provide the information about it. Example: <%@page
language="java" %>
b. include: include is used to include a file in the JSP page. Example: <%@ include
file="/header.jsp" %>
c. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to
defined our own tags). Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
Page tag attributes are:
a. language="java"
This tells the server that the page is using the java language. Current JSP specification
supports only java language. Example: <%@page language="java" %>
b. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import
more than one packages. Example: %@page language="java" import="java.sql.*" %
c. session="true"
When this value is true session data is available to the JSP page otherwise not. By default this
value is true.
4. Declarations
This tag is used for defining the functions and variables
to be used in theJSP. Syntax of JSP Declaratives are:
<%!
//java codes
%>
JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code
in the JSP Declaratives. Variables and functions defined in the declaratives are class level and
can be used anywhere in the JSP page.
Example
<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%!
Date theDate = new Date(); Date getDate()
{
System.out.println( "In getDate() method" ); return theDate;
}
%>
Hello! The time is now <%= getDate() %>
</BODY>
</HTML>
Using a Literal
<HTML>
<HEAD>
<TITLE>Using a Literal</TITLE>
</HEAD>
<BODY>
<H1>Using a Literal</H1>
<%
out.println("Number of days = "); out.println(365);
%>
</BODY>
</html>
Declaration Tag Example
<%!
String name = "Joe";
String date = "8th April, 2002";
%>
<HTML>
<TITLE>Declaration Tag Example</TITLE>
<BODY>
This page was last modified on <%= date %> by <%= name %>.
</BODY>
</HTML>
Embedding Code
<%!
String[] names = {"A", "B", "C", "D"};
%>
<HTML>
<HEAD><TITLE>Embedding Code</TITLE></HEAD>
<BODY>
<H1>List of people</H1>
<TABLE BORDER="1">
<TH>Name</TH>
<% for (int i=0; i<names.length; i++) { %>
<TR><TD><%= names[i]%></TD></TR>
<% } %>
</TABLE>
</BODY>
</HTML>
Use out
<%@ page language="java" %>
<HTML>
<HEAD><TITLE>JSP Example</TITLE></HEAD>
<BODY>
<H1>Quadratic Equation: y = x^2</H1>
<TABLE BORDER="1">
<TH>x</TH><TH>y</TH>
<%
for (int i=0; i<10; i++)
out.print("<TR><TD WIDTH='100'>" + i + "</TD><TD WIDTH='100'>" + (i*i) +
"</TD></TR>");
%>
</TABLE>
</BODY>
</HTML>
Casting to a New Type
<HTML>
<HEAD>
<TITLE>Casting to a New Type</TITLE>
</HEAD>
<BODY>
<H1>Casting to a New Type</H1>
<%
float float1;
double double1 = 1;
float1 = (float) double1;
Creating a String
<HTML>
<HEAD>
<TITLE>Creating a String</TITLE>
</HEAD>
<BODY>
<H1>Creating a String</H1>
<%
String greeting = "Hello from JSP!";
out.println(greeting);
%>
</BODY>
</HTML>
Creating an Array
<HTML>
<HEAD>
<TITLE>Creating an Array</TITLE>
</HEAD>
<BODY>
<H1>Creating an Array</H1>
<%
double accounts[];
accounts = new double[100]; accounts[3] = 119.63;
out.println("Account 3 holds $" + accounts[3]);
%>
</BODY>
</HTML>
Finding a Factorial
<HTML>
<HEAD>
<TITLE>Finding a Factorial</TITLE>
</HEAD>
<BODY>
<H1>Finding a Factorial</H1>
<%
int value = 6, factorial = 1, temporaryValue = value;
while (temporaryValue > 0) { factorial *= temporaryValue; temporaryValue--;
}
out.println("The factorial of " + value + " is " + factorial + ".");
%>
</BODY>
</HTML>
function button2()
{
document.form1.buttonName.value = "button 2" form1.submit()
}
function button3()
{
document.form1.buttonName.value = "button 3" form1.submit()
}
// -->
</SCRIPT>
</BODY>
</HTML>
basic.jsp
<HTML>
<HEAD>
<TITLE>Determining Which Button Was Clicked</TITLE>
</HEAD>
<BODY>
<H1>Determining Which Button Was Clicked</H1> You clicked
<%= request.getParameter("buttonName") %>
</BODY>
</HTML>
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>
basic.jsp
<HTML>
<HEAD>
<TITLE>Reading Checkboxes</TITLE>
</HEAD>
<BODY>
<H1>Reading Checkboxes</H1>
<%
if(request.getParameter("check1") != null) { out.println("Checkbox 1 was checked.<BR>");
}
else {
out.println("Checkbox 1 was not checked.<BR>");
}
if(request.getParameter("check2") != null) { out.println("Checkbox 2 was checked.<BR>");
}
else {
out.println("Checkbox 2 was not checked.<BR>");
}
if(request.getParameter("check3") != null) { out.println("Checkbox 3 was checked.<BR>");
}
else {
out.println("Checkbox 3 was not checked.<BR>");
}
%>
</BODY>
</HTML>
Business logic is the term used for the manipulation of an application's data, such as
customer, product, and order information. Presentation refers to how the application data is
displayed to the user, for example, position, font, and size. And finally, request
processing is what ties the business logic and presentation parts together.
In MVC terms, presentation should be separated from the business logic. Presentation of that
data (the View) changes fairly often. Just look at all the face- lifts many web sites go through
to keep up with the latest fashion in web design. Some sites may want to present the data in
different languages or present different subsets of the data to internal and external users.
cookies:
A cookie is a small piece of information created by a JSP program that is stored in the client‘s
hard disk by the browser. Cookies are used to store various kind of information such as
username, password, and user preferences, etc.
Different methods in cookie class are:
1.String getName()- Returns a name of cookie
2.String getValue()-Returns a value of cookie
3.int getMaxAge()-Returns a maximum age of cookie in millisecond
4. String getDomain()-Returns a domain
5.boolean getSecure()-Returns true if cookie is secure otherwise false
6.String getPath()-Returns a path of cookie
7.void setPath(Sting)- set the path of cookie
8.void setDomain(String)-set the domain of cookie
9.void setMaxAge(int)-set the maximum age of cookie
10.void setSecure(Boolean)-set the secure of cookie.
Creating cookie:
Cookie are created using cookie class constructor.
Content of cookies are added the browser using addCookies() method.
Reading cookies:
Reading the cookie information from the browser using getCookies() method.
Find the length of cookie class.
Retrive the information using different method belongs the cookie class
PROGRAM: To create and read the cookie for the given cookie name as “EMPID” and
its value as”AN2356”.
Program:
<%!
HttpSession h=req.getSesssion(true);
Date d=(Date) h.getAttribute(“Date”);
out.println(―last date and time‖+d);
Date d1=new Date();
d1=h.setAttribute(“date”,d1);
out.println(―current date and time=‖+d1);
%>