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

Web Technologies

Uploaded by

likhithamitte123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Web Technologies

Uploaded by

likhithamitte123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Web Technologies III B.

Tech II Sem (R15)

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.

Dept. of CSE, MRCET Page | 113


Web Technologies III B.Tech II Sem (R15)

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.

Dept. of CSE, MRCET Page | 114


Web Technologies III B.Tech II Sem (R15)

• JSP needs no compilation by the Programmer. Programmer deploys directly a JSP


source code file in server where as incase of Servlets, the Programmer compiles
manually a Servlet file and deploys a .class file in server.
• JSP is so easy even a Web Designer can put small interactive code (not knowing much
of Java) in static Web pages.
• First time when JSP is called it is compiled to a Servlet. Subsequent calls to the same
JSP will call the same compiled servlet (instead of converting the JSP to servlet),
Ofcourse, the JSP code would have not modified. This increases performance.

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

You should be able to create a simple file, such as


<HTML>
<BODY>
Hello, world
</BODY> </HTML>
Know where to place this file and how to see it in your browser with an http:// prefix.
Since this step is different for each web-server, you would need to see the web-server
documentation to find out how this is done. Once you have completed this step, proceed to
the next.

Dept. of CSE, MRCET Page | 115


Web Technologies III B.Tech II Sem (R15)

Your first JSP


JSP simply puts Java inside HTML pages. You can take any existing HTML page and change
its extension to ".jsp" instead of ".html". In fact, this is the perfect exercise for your first JSP.
Take the HTML file you used in the previous exercise. Change its extension from ".html" to
".jsp". 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 everytime you change the JSP file, it will be re-
compiled again.)

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.

Explain about JSP Elements


In this lesson we will learn about the various elements available in JSP with suitable
examples. In JSP elements can be dividedinto 4 different types.
These are:
1. Expressions
We can use this tag to output any data on the generated page. These data are automatically
converted to string and printed on the output stream.
Syntax of JSP Expressions are: <%="Any thing" %>

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!'

Dept. of CSE, MRCET Page | 116


Web Technologies III B.Tech II Sem (R15)

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:

a. Request: Request represents the clients request and is a subclass of


HttpServletRequest. Use this variable to retrieve the data submitted along the request.
Example: <% //java codes
String userName=null; userName=request.getParameter("userName");
%>
b. Response: Response represents the server response and is a subclass of
HttpServletResponse.
<% response.setContentType("text/html"); %>

c. Session: represents the HTTP session object associated with the


request. Your Session ID: <%= session.getId() %>
d. Out: out is an object of output stream and is used to send any output to the client.

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.

Dept. of CSE, MRCET Page | 117


Web Technologies III B.Tech II Sem (R15)

Example: <%@page language="java" session="true" %>


d. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the
page. Example: <%@page session="true" errorPage="error.jsp" %>
e. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set
of the JSP. Example: <%@page contentType="text/html;charset=ISO-8859-1" %>

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>

Expalin about Jsp programs?


A Web Page with JSP code
<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>
<BODY>
<% out.println("Hello there!"); %>
</BODY>
</HTML>

Dept. of CSE, MRCET Page | 118


Web Technologies III B.Tech II Sem (R15)

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>

Dept. of CSE, MRCET Page | 119


Web Technologies III B.Tech II Sem (R15)

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;

out.println("float1 = " + float1);


%>
</BODY>
</HTML>

Creating a String
<HTML>
<HEAD>
<TITLE>Creating a String</TITLE>
</HEAD>

<BODY>
<H1>Creating a String</H1>

Dept. of CSE, MRCET Page | 120


Web Technologies III B.Tech II Sem (R15)

<%
String greeting = "Hello from JSP!";
out.println(greeting);
%>
</BODY>
</HTML>

Use for loop to dis play string array


<%@ page session="false" %>
<%
String[] colors = {"red", "green", "blue"};
for (int i = 0; i < colors.length; i++) { out.print("<P>" + colors[i] + "</p>");
}
%>

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>

Using Multidimensional Arrays


<HTML>
<HEAD>
<TITLE>Using Multidimensional Arrays</TITLE>
</HEAD>
<BODY>
<H1>Using Multidimensional Arrays</H1>
<%
double accounts[][] = new double[2][100];
accounts[0][3] = 119.63;
accounts[1][3] = 194.07;

Dept. of CSE, MRCET Page | 121


Web Technologies III B.Tech II Sem (R15)

out.println("Savings Account 3 holds $" + accounts[0][3] + "<BR>"); out.println("Checking


Account 3 holds $" + accounts[1][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>

Get Form Button Value


<HTML>
<HEAD>
<TITLE>Using Buttons</TITLE>
</HEAD>
<BODY>
<H1>Using Buttons</H1>
<FORM NAME="form1" ACTION="basic.jsp" METHOD="POST">
<INPUT TYPE="HIDDEN" NAME="buttonName">
<INPUT TYPE="BUTTON" VALUE="Button 1" ONCLICK="button1()">
<INPUT TYPE="BUTTON" VALUE="Button 2" ONCLICK="button2()">
<INPUT TYPE="BUTTON" VALUE="Button 3" ONCLICK="button3()">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
function button1()
{
document.form1.buttonName.value = "button 1" form1.submit()
}

Dept. of CSE, MRCET Page | 122


Web Technologies III B.Tech II Sem (R15)

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>

Read Form Checkboxes


index.jsp
<HTML>
<HEAD>
<TITLE>Submitting Check Boxes</TITLE>
</HEAD>
<BODY>
<H1>Submitting Check Boxes</H1>
<FORM ACTION="basic.jsp" METHOD="post">
<INPUT TYPE="CHECKBOX" NAME="check1" VALUE="check1" CHECKED>
Checkbox 1
<BR>
<INPUT TYPE="CHECKBOX" NAME="check2" VALUE="check2">
Checkbox 2
<BR>
<INPUT TYPE="CHECKBOX" NAME="check3" VALUE="check3">
Checkbox 3

Dept. of CSE, MRCET Page | 123


Web Technologies III B.Tech II Sem (R15)

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

Model View Controller


JSP technology can play a part in everything from the simplest web application to
complex enterprise applications. How large a part JSP plays differs in each case, of course.
Let introduce a design model called Model- View-Controller (MVC), suitable for both simple
and complex applications.
MVC was first described by Xerox in a number of papers published in the late 1980s. The
key point of using MVC is to separate logic into three distinct units: the Model, the View,
and the Controller. In a server application, we commonly classify the parts of the
application as business logic, presentation, and request processing.

Dept. of CSE, MRCET Page | 124


Web Technologies III B.Tech II Sem (R15)

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

JSP program to create a cookie


<%!
Cookie c=new Cookie(―EMPID‖,‖AN2356‖);
response.addCookie(c);
%>

Dept. of CSE, MRCET Page | 125


Web Technologies III B.Tech II Sem (R15)

JSP program to read a cookie


<%!
Cookie c[]=request.getCookies();
for(i=0;i<c.length;i++)
{
String name=c[i].getName();
String value=c[i].getValue();
out.println(―name=‖+name);
out.println(―value=‖+value);
}
%>

Session object(session tracking or session uses)

The HttpSession object associated to the request


Session object has a session scope that is an instance of javax.servlet.http.HttpSession class.
Perhaps it is the most commonly used object to manage the state contexts.
This object persist information across multiple user connection.
Created automatically by
Different methods of HttpSession interface are as follows:

1.object getAttribute(String)-Returns the value associated with the name passed as


argument.
2.long getCreationTime()-Returns the time when session created.
3.String getID()-Returns the session ID
4.long getAccessedTIme()-returns the time when client last made a request for this session.
5.void setAttribute(String,object)-Associates the values passed in the object name passed.

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);
%>

Dept. of CSE, MRCET Page | 126

You might also like