UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary...

28
CS518 Internet Programming And Tools Unit IV MTech CSE (PT, 2011-14) SRM, Ramapuram 1 hcr:innovationcse@gg UNIT IV SERVER SIDE PROGRAMMING Introduction to Java Servlets – overview and architecture – Handling HTTP get & post request – session Tracking – Multi-tier application - Implicit objects – Scripting – Standard actions – Directives – Custom Tag libraries. Static HTML Contents (Web Pages) Hyper text transfer protocol is a simple request or response protocol, in which a web browser asks for a document and the web server returns the document in the form of an HTML data stream proceeded by a few descriptive headers. This static approach, creating and reading web pages is useful to display static information like online documentation, corporate profile, etc. The text document were static requesting user has no ability to impact the content delivered from the web server Dynamic Web page The term dynamic describes the process of generating HTML pages according to the information requested by the user to the web server. Here the web server gets the request from the user, process it and generates the results, convert into HTML and send it to the client’s web browser.

Transcript of UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary...

Page 1: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 1 hcr:innovationcse@gg

UNIT IV SERVER SIDE PROGRAMMING

Introduction to Java Servlets – overview and architecture – Handling HTTP get & post request –

session Tracking – Multi-tier application - Implicit objects – Scripting – Standard actions –

Directives – Custom Tag libraries.

Static HTML Contents (Web Pages)

Hyper text transfer protocol is a simple request or response protocol, in which a web browser

asks for a document and the web server returns the document in the form of an HTML data

stream proceeded by a few descriptive headers.

This static approach, creating and reading web pages is useful to display static information

like online documentation, corporate profile, etc.

The text document were static requesting user has no ability to impact the content delivered

from the web server

Dynamic Web page

The term dynamic describes the process of generating HTML pages according to the

information requested by the user to the web server.

Here the web server gets the request from the user, process it and generates the results,

convert into HTML and send it to the client’s web browser.

Page 2: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 2 hcr:innovationcse@gg

Client Side Scripting

Scripting is referred to be location where the code is processed

CSS is the code runs on the client machine

When a user requests the web page, the HTML and all related script codes within that web

page are downloaded to the user’s browser

Example: Ordering / Application forms – contains validations (except secure transactions), all

are CSS only; Secure transactions requires Server side scripting

Advantages of CSS

Work on the server is reduced since the processing is done at the client side itself

Network traffic is reduced due to fewer number of request / reply on the action between the

browser and the web server

Faster when compared to SSS

Disadvantage

The code is completely visible to the user, hence security violations is there

Server Side Scripting

The script code is processed on the web server before it is sent to the client’s web browser

The user requests an URL and this request is sent to the web server

If the requested page has any server side coding, it is processed and the page can be

returned as pure HTML.

The browser parses it and the contents are displayed in the browser itself.

The browser does not know how to read any kind of script.

Therefore it is processed on the server side only and returns only HTML streams of data

Advantages

Code is protected

Company secrets, coding standards are hidden from anonymous users

Disadvantages

Comparatively slower (If the requested web server is busy / not available)

Page 3: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 3 hcr:innovationcse@gg

Server side technologies

The various server side scripting technologies are

1. CGI – Common Gateway Interface

Standard

Span an external program to handle requests

2. PERL

Is a common scripting language for CGI under Unix

But any programming language can access or use CGI/PERL

3. Servlets

Create Java objects that the server uses to satisfy the requests

Object is created only once and will be persistent till server shut down

Object used any number of times

And also run on many platforms without any change of the servlets written on one

machine

4. ASP

Active Sever page is a server side technology of Microsoft, normally SQL server is used for

all the database related activities with the support of Microsoft technologies like NET

5. JSP

Is a template for web page that uses Java code to generate a HTML document dynamically

JSP run on server side component called JSP container which translates the equivalent

JAVA servlets and scripts

JSP Advantages

a. They have built in support of HTTP session and also full support of Java technology

b. No special client side setup is required

c. Possibility of auto recompilation when necessary

d. JSP have great compatibility with web development tools

6. Cold Fusion – Popular solution for different target mode of servers

Popular solution that targets different servers like ASP

Cold Fusion uses special tags to delimits its code

The tags start with “CF” and ends with “/CF”

The file extensions are saved as .cfml

It also supports notations and session variables

These variables are also created by any client and resides in the user computer to provide

a good place to store and the data pertains to a specific user in a web form

Page 4: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 4 hcr:innovationcse@gg

7. PHP – Personal Home Page (Linux environment, combination of MySQL)

PHP is also a common SSS technology widely used in Linux environment with .PHP

extension

Is combined with MySQL

Other Popular Web severs

1. Apache

2. Tomcat

3. Netscape Enterprise

4. Website Professional Commerce Server / 400

5. Domino

6. Personal Web Server

7. Internet Information Server

8. Java Web Server

JAVA SERVLETS

Servlets

A Servlet is a Java programming language class used to extend the capabilities of servers that

can be accessed by a host application via a request-response programming model.

Servlets are dynamically loaded module that services the request from a web server

It runs entirely inside the Java Virtual Machine (JVM)

It does not depend on browsers capability because servlet is running on the server side

Servlets and Java Server Pages are complementary APIs, both providing a means for

generating dynamic Web content.

Servlets, look and act like programs.

Architecture

A servlet is a Java class implementing the

javax.servlet.Servlet interface that runs within a

Web or application server's servlet engine,

servicing client requests forwarded to it through

the server.

Page 5: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 5 hcr:innovationcse@gg

Life cycle methods

A servlet life cycle can be defined as the entire process from its creation till the destruction.

The following are the paths followed by a servlet

o The servlet is initialized by calling the init () method.

o The servlet calls service() method to process a client's request.

o The servlet is terminated by calling the destroy() method.

o Finally, servlet is garbage collected by the garbage collector of the JVM.

The init() method

The init method is designed to be called only once.

It is called when the servlet is first created, and not called again for each user request.

So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the

servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each

user request resulting in a new thread that is handed off to doGet or doPost as

appropriate.

The init() method simply creates or loads some data that will be used throughout the life

of the servlet.

Signature of the init method,

public void init() throws ServletException {

// Initialization code...

}

The service() method

The service() method is the main method to perform the actual task.

The servlet container (i.e. web server) calls the service() method to handle requests

coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and

calls service.

The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and

calls doGet, doPost, doPut, doDelete, etc. methods as appropriate

Signature of the service method,

public void service(ServletRequest request,

Page 6: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 6 hcr:innovationcse@gg

ServletResponse response)

throws ServletException, IOException{

}

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no

METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

}

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it

should be handled by doPost() method.

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

}

The destroy() method

The destroy() method is called only once at the end of the life cycle of a servlet.

This method gives your servlet a chance to close database connections, halt background

threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection.

The destroy method definition looks like this:

public void destroy() {

// Finalization code...

}

Example

package wellho;

import javax.servlet.*;

import javax.servlet.http.*;

Page 7: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 7 hcr:innovationcse@gg

import java.io.PrintWriter;

import java.io.IOException;

public class demolet extends HttpServlet implements

SingleThreadModel

{

private static final String CONTENT_TYPE = "text/html;

charset=windows-1252";

public void init(ServletConfig config) throws ServletException

{

super.init(config);

}

/**

* Process the HTTP doGet request.

*/

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException

{

String var0show = "";

try

{

var0show = request.getParameter("showthis");

}

catch(Exception e)

{

e.printStackTrace();

}

response.setContentType(CONTENT_TYPE);

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head><title>demolet</title></head>");

out.println("<body>");

out.println("<p>The servlet has received a GET.</p>");

out.println("</body></html>");

out.close();

}

/**

* Process the HTTP doPost request.

*/

public void doPost(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException

{

String var0show = "";

try

{

var0show = request.getParameter("showthis");

}

catch(Exception e)

{

e.printStackTrace();

Page 8: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 8 hcr:innovationcse@gg

}

response.setContentType(CONTENT_TYPE);

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head><title>demolet</title></head>");

out.println("<body>");

out.println("<p>The servlet has received a POST</p>");

out.println("</body></html>");

out.close();

}

}

JSPS

A Java Server Page contain a mixture of HTML, Java scripts, JSP elements, and JSP directives

The elements in a Java Server Page will generally be compiled by the JSP engine into a

servlet

The advantage of Java Server Pages is that they are document-centric.

A Java Server Page can contain Java program fragments that instantiate and execute Java

classes, but these occur inside an HTML template file and are primarily used to generate

dynamic content.

Some of the JSP functionality can be achieved on the client, using JavaScript.

The power of JSP is that it is server-based and provides a framework for Web application

development.

JSP Steps

1. JSP Code is converted into servlet code and saved under the extension .java in a separate

location

2. The servlet code is compiled to a .class file by using a Java compiler

3. The class file is interpreted and the HTML output is generated

4. The HTML output is returned to the client browser

JSP Architecture

Page 9: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 9 hcr:innovationcse@gg

JSP Lifecycle

SESSION TRACKING

HTTP is a "stateless" protocol

Each time a client retrieves a Web page, the client opens a separate connection to the Web

server and the server automatically does not keep any record of previous client request.

Three ways to maintain session between web client and web server

o Cookies

o Hidden Form Fields

o URL Rewriting

Cookies

A webserver can assign a unique session ID as a cookie to each web client and for subsequent

requests from the client they can be recognized using the received cookie.

This may not be an effective way because many time browser does not support a cookie

Hidden Form Fields

A web server can send a hidden HTML form field along with a unique session ID

<input type="hidden" name="sessionid" value="12345">

when the form is submitted, the specified name and value are automatically included in the

GET or POST data.

Each time when web browser sends request back, then session_id value can be used to keep

the track of different web browser

clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so

hidden form fields also cannot support general session tracking

URL Rewriting

You can append some extra data on the end of each URL that identifies the session, and the

server can associate that session identifier with data it has stored about that session.

Example: http://tutorialspoint.com/file.htm;sessionid=12345

The session identifier is attached as sessionid=12345 which can be accessed at the web

server to identify the client.

URL rewriting is a better way to maintain sessions and works for the browsers when they

don't support cookies

Page 10: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 10 hcr:innovationcse@gg

Drawback is that you would have generate every URL dynamically to assign a session ID

though page is simple static HTML page.

The session Object

JSP makes use of servlet provided HttpSession Interface

By default, JSPs have session tracking enabled and a new HttpSession object is instantiated

for each new client automatically

The JSP engine exposes the HttpSession object through the implicit session object.

The programmer can immediately begin storing and retrieving data from the object without

any initialization or getSession()

Disabling session tracking requires explicitly turning it off by setting the page directive

session attribute to false as follows:

o <%@ page session="false" %>

Important methods available through session object

S.N. Method & Description

1

public Object getAttribute(String name)

This method returns the object bound with the specified name in this session, or null if no object

is bound under the name.

2

public Enumeration getAttributeNames()

This method returns an Enumeration of String objects containing the names of all the objects

bound to this session.

3

public long getCreationTime()

This method returns the time when this session was created, measured in milliseconds since

midnight January 1, 1970 GMT.

4 public String getId()

This method returns a string containing the unique identifier assigned to this session.

5

public long getLastAccessedTime()

This method returns the last time the client sent a request associated with this session, as the

number of milliseconds since midnight January 1, 1970 GMT.

6

public int getMaxInactiveInterval()

This method returns the maximum time interval, in seconds, that the servlet container will keep

this session open between client accesses.

7 public void invalidate()

This method invalidates this session and unbinds any objects bound to it.

8

public boolean isNew(

This method returns true if the client does not yet know about the session or if the client chooses

not to join the session.

9 public void removeAttribute(String name)

This method removes the object bound with the specified name from this session.

10 public void setAttribute(String name, Object value)

This method binds an object to this session, using the name specified.

11

public void setMaxInactiveInterval(int interval)

This method specifies the time, in seconds, between client requests before the servlet container

will invalidate this session.

Page 11: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 11 hcr:innovationcse@gg

Session Tracking Example

<%@ page import="java.io.*,java.util.*" %>

<%

// Get last access time of this web page.

Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";

Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");

String userIDKey = new String("userID");

String userID = new String("ABCD");

// Check if this is new comer on your web page.

if (session.isNew()){

title = "Welcome to my website";

session.setAttribute(userIDKey, userID);

session.setAttribute(visitCountKey, visitCount);

}

visitCount = (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount + 1;

userID = (String)session.getAttribute(userIDKey);

session.setAttribute(visitCountKey, visitCount);

%>

<html>

<head>

<title>Session Tracking</title>

</head>

<body>

<table border="1" align="center">

<tr>

<td>Time of Last Access</td>

<td><% out.print(lastAccessTime); %></td>

</tr>

<tr>

<td>User ID</td>

<td><% out.print(userID); %></td>

</tr>

<tr>

<td>Number of visits</td>

<td><% out.print(visitCount); %></td>

</tr>

</table>

</body>

</html>

Output

Page 12: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 12 hcr:innovationcse@gg

MULTI-TIER APPLICATION

1-Tier Architecture

2-Tier Architecture

3-Tier Architecture

1-Tier Architecture

All 3 layers are on the same machine

All code and processing kept on a single machine

Presentation, Logic, Data layers are tightly connected

Scalability: Single processor means hard to increase volume of processing

Portability: Moving to a new machine may mean rewriting everything

Maintenance: Changing one layer requires changing other layers

2-Tier Architecture

Database runs on Server

o Separated from client

o Easy to switch to a different database

Presentation and logic layers still tightly connected

o Heavy load on server

o Potential congestion on network

o Presentation still tied to business logic

Page 13: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 13 hcr:innovationcse@gg

3-Tier Architecture

Each layer can potentially run on a different machine

Presentation, logic, data layers disconnected

A Typical 3-tier Architecture

Architecture Principles

Client-server architecture

Each tier (Presentation, Logic, Data) should be independent and should not expose

dependencies related to the implementation

Unconnected tiers should not communicate

Page 14: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 14 hcr:innovationcse@gg

Change in platform affects only the layer running on that particular platform

Presentation Layer

Provides user interface

Handles the interaction with the user

Sometimes called the GUI or client view or front-end

Should not contain business logic or data access code

Logic Layer

The set of rules for processing information

Can accommodate many users

Sometimes called middleware/ back-end

Should not contain presentation or data access code

Data Layer

The physical storage layer for data persistence

Manages access to DB or file system

Sometimes called back-end

Should not contain presentation or business logic code

The 3-Tier Architecture for Web Apps

Presentation Layer

o Static or dynamically generated content rendered by the browser (front-end)

Logic Layer

o A dynamic content processing and generation level application server, e.g., Java EE,

ASP.NET, PHP, ColdFusion platform (middleware)

Data Layer

o A database, comprising both data sets and the database management system or

RDBMS software that manages and provides access to the data (back-end)

Advantages

Independence of Layers

Easier to maintain

Components are reusable

Faster development (division of work)

o Web designer does presentation

o Software engineer does logic

o DB admin does data model

Page 15: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 15 hcr:innovationcse@gg

JSP IMPLICIT OBJECTS

JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in

each page and developer can call them directly without being explicitly declared. JSP Implicit

Objects are also called pre-defined variables.

JSP supports nine Implicit Objects which are listed below:

Object Description

request This is the HttpServletRequest object associated with the request.

response This is the HttpServletResponse object associated with the response to the

client.

out This is the PrintWriter object used to send output to the client.

session This is the HttpSession object associated with the request.

application This is the ServletContext object associated with application context.

config This is the ServletConfig object associated with the page.

pageContext This encapsulates use of server-specific features like higher performance JspWriters.

page This is simply a synonym for this, and is used to call the methods defined by the translated servlet class.

Exception The Exception object allows the exception data to be accessed by designated JSP.

Application

These objects has an application scope.

These objects are available at the widest context level, that allows to share the same

information between the JSP page's servlet and any Web components with in the same

application.

Config

These object has a page scope and is an instance of javax.servlet.ServletConfig class.

Config object allows to pass the initialization data to a JSP page's servlet.

Parameters of this objects can be set in the deployment descriptor (web.xml) inside the

element <jsp-file>.

The method getInitParameter() is used to access the initialization parameters.

Exception

This object has a page scope and is an instance of java.lang.Throwable class.

This object allows the exception data to be accessed only by designated JSP "error pages."

Out

This object allows us to access the servlet's output stream and has a page scope.

Out object is an instance of javax.servlet.jsp.JspWriter class.

It provides the output stream that enable access to the servlet's output stream.

Page 16: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 16 hcr:innovationcse@gg

Page

This object has a page scope and is an instance of the JSP page's servlet class that processes

the current request.

Page object represents the current page that is used to call the methods defined by the

translated servlet class.

First type cast the servlet before accessing any method of the servlet through the page.

Pagecontext

PageContext has a page scope.

Pagecontext is the context for the JSP page itself that provides a single API to manage the

various scoped attributes.

This API is extensively used if we are implementing JSP custom tag handlers.

PageContext also provides access to several page attributes like including some static or

dynamic resource.

Request

Request object has a request scope that is used to access the HTTP request data, and also

provides a context to associate the request-specific data.

Request object implements javax.servlet.ServletRequest interface.

It uses the getParameter() method to access the request parameter.

The container passes this object to the _jspService() method.

Response

This object has a page scope that allows direct access to the HTTPServletResponse class

object

Response object is an instance of the classes that implements the

javax.servlet.ServletResponse class.

Container generates to this object and passes to the _jspService() method as a parameter.

Session

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.

JSP SCRIPTING ELEMENTS

Let you insert code into the servlet that will be generated from the JSP page.

Three form types

1. Expressions of the form <%= expression %> , which are evaluated and inserted into the

servlet’s output

2. Scriptlets of the form <% code %> , which are inserted into the servlet’s _jspService method

(called by service)

3. Declarations of the form <%! code %> , which are inserted into the body of the servlet

class, outside of any existing methods

Template Text

Static HTML in the JSP, that is simply “passed through” to the client by the servlet created to

handle the page

Exceptions are <% (use <\%) and <! -- JSP Comment (use <% -- JSP Comment)

Page 17: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 17 hcr:innovationcse@gg

JSP Expressions

<%= Java Expression %>

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

Predefined Variables

o request, the HttpServletRequest

o response, the HttpServletResponse

o session, the HttpSession

o out, the PrintWriter

Your hostname: <%= request.getRemoteHost() %>

XML Syntax for Expressions

<jsp:expression>

Java Expression

</jsp:expression>

Using Expressions as Attribute Values

<jsp:setProperty name="user"

property="id"

value=’<%= "UserID" + Math.random() %>’ />

XML Action Attributes

o jsp:setProperty

o jsp:include

o jsp:forward

o jsp:param

Example: Expressions.jsp

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

<HTML>

<HEAD>

<TITLE>JSP Expressions</TITLE>

</HEAD>

<BODY>

<H2>JSP Expressions</H2>

<UL>

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

<LI>Your hostname: <%= request.getRemoteHost() %>

<LI>Your session ID: <%= session.getId() %>

<LI>The <CODE>testParam</CODE> form parameter:

<%= request.getParameter("testParam") %>

</UL>

</BODY>

</HTML>

Page 18: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 18 hcr:innovationcse@gg

JSP Scriptlets

insert arbitrary code into the servlet’s _jspService method

<% Java Code %>

<%

String queryData = request.getQueryString();

out.println("Attached GET data: " + queryData);

%>

<% response.setContentType("text/plain"); %>

XML Equivalent

<jsp:scriptlet>

Code

</jsp:scriptlet>

Example: BGColor.jsp

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

<HTML>

<HEAD>

<TITLE>Color Testing</TITLE>

</HEAD>

<%

String bgColor = request.getParameter("bgColor");

boolean hasExplicitColor;

if (bgColor != null) {

hasExplicitColor = true;

} else {

hasExplicitColor = false;

bgColor = "WHITE";

}

%>

<BODY BGCOLOR="<%= bgColor %>">

<H2 ALIGN="CENTER">Color Testing</H2>

<%

if (hasExplicitColor) {

out.println("You supplied an explicit background color of "

+ bgColor + ".");

} else {

out.println("Using default background color of WHITE. ");

}

%>

</BODY>

</HTML>

http://localhost/JSP/BGColor.jsp

http://localhost/JSP/BGColor.jsp?bgColor=C0C0C0

Page 19: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 19 hcr:innovationcse@gg

JSP Declarations

Lets you define methods or fields that get inserted into the main body of the servlet class

(outside of the _jspService method)

<%! Java Code %>

XML equivalent

<jsp:declaration>

Code

</jsp:declaration>

Example: AccessCounts.jsp

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

<HTML>

<HEAD>

<TITLE>JSP Declarations</TITLE>

</HEAD>

<BODY>

<H1>JSP Declarations</H1>

<%! private int accessCount = 0; %>

<H2>Accesses to page since server reboot:

<%= ++accessCount %></H2>

</BODY>

</HTML>

Output

Page 20: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 20 hcr:innovationcse@gg

JSP STANDARD ACTIONS

JSP actions use constructs in XML syntax to control the behavior of the servlet engine.

<jsp:action_name attribute="value" />

Syntax Purpose

jsp:include Includes a file at the time the page is requested

<jsp:include page="relative URL" flush="true" />

jsp:useBean Finds or instantiates a JavaBean

<jsp:useBean id="name" class="package.class" />

jsp:setProperty Sets the property of a JavaBean

<jsp:setProperty name="myName" property="someProperty" .../>

jsp:getProperty Inserts the property of a JavaBean into the output

<jsp:getProperty name="myName" property="someProperty" .../>

jsp:forward Forwards the requester to a new page

<jsp:forward page="Relative URL" />

jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag for

the Java plugin

jsp:element Defines XML elements dynamically.

jsp:attribute Defines dynamically defined XML element's attribute.

jsp:body Defines dynamically defined XML element's body.

jsp:text Use to write template text in JSP pages and documents

<jsp:text>Template data</jsp:text>.

Example

Date.jsp

<p>

Today's date: <%= (new java.util.Date()).toLocaleString()%>

</p>

/* File: TestBean.java */

package action;

public class TestBean {

private String message = "No message specified";

public String getMessage() {

return(message);

}

public void setMessage(String message) {

this.message = message;

}

}

Page 21: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 21 hcr:innovationcse@gg

Main.JSP

<html>

<head>

<title>The include Action Example</title>

</head>

<body>

<center>

<h2>The include action Example</h2>

<jsp:include page="date.jsp" flush="true" />

</center>

<center>

<h2>Using JavaBeans in JSP</h2>

<jsp:useBean id="test" class="action.TestBean" />

<jsp:setProperty name="test" property="message" value="Hello

JSP..." />

<p>Got message....</p>

<jsp:getProperty name="test" property="message" />

</center>

<center>

<h2>The include action Example</h2>

<jsp:forward page="date.jsp" />

</center>

<jsp:plugin type="applet" codebase="dirname"

code="MyApplet.class"

width="60" height="80">

<jsp:param name="fontcolor" value="red" />

<jsp:param name="background" value="black" />

<jsp:fallback>

Unable to initialize Java Plugin

</jsp:fallback>

</jsp:plugin>

<jsp:element name="xmlElement">

<jsp:attribute name="xmlElementAttr">

Value for the attribute

</jsp:attribute>

<jsp:body>

Body for XML element

</jsp:body>

</jsp:element>

</body>

</html>

Output

TBD

Page 22: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 22 hcr:innovationcse@gg

DIRECTIVES AND CUSTOM TAG LIBRARIES OF SERVLETS

JSP Directives

JSP directives provide directions and instructions to the container, telling it how to handle

certain aspects of JSP processing

A JSP directive affects the overall structure of the servlet class.

It usually has the following form:

<%@ directive attribute="value" %>

Directives can have a number of attributes which you can list down as key-value pairs and

separated by commas

<%@ directive attribute1="value1"

attribute2="value2"

attributeN="valueN" %>

The blanks between the @ symbol and the directive name, and between the last attribute

and the closing %>, are optional.

There are three types of directive tag

Directive Description

<%@ page ... %> Defines page-dependent attributes, such as scripting language,

error page, and buffering requirements

<%@ include ... %> Includes a file during the translation phase

<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page

The page Directive

The page directive is used to provide instructions to the container that pertain to the

current JSP page. You may code page directives anywhere in your JSP page.

By convention, page directives are coded at the top of the JSP page.

Following is the basic syntax of page directive:

<%@ page attribute="value" %>

XML equivalent of the above syntax as follows:

<jsp:directive.page attribute="value" />

The page directive lets you define one or more of the following case-sensitive attributes

Attributes for page Directive

Attribute Description

Import

Specifies a list of packages or classes for use in the JSP as the Java import

statement does for Java classes

import="package.class" or

import="package.class1,...,package.classN".

This lets you specify what packages should be imported.

For example:

<%@ page import="java.util.*" %>

The import attribute is the only one that is allowed to appear multiple times

Buffer Specifies a buffering model for the output stream.

Page 23: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 23 hcr:innovationcse@gg

buffer="sizekb|none".

This specifies the buffer size for the JspWriter out.

The default is server-specific, but must be at least 8kb

autoFlush

Controls the behavior of the servlet output buffer

autoflush="true|false".

A value of true, the default, indicates that the buffer should be flushed

when it is full.

A value of false, rarely used, indicates that an exception should be

thrown when the buffer overflows.

A value of false is illegal when also using buffer="none"

contentType

Defines the character encoding scheme

contentType="MIME-Type" or

contentType="MIME-Type; charset=Character-Set"

This specifies the MIME type of the output. The default is text/html. For

example, the directive

<%@ page contentType="text/plain" %>

has the same effect as the scriptlet

<% response.setContentType("text/plain"); %>

errorPage

Defines the URL of another JSP that reports on Java unchecked runtime exceptions

errorPage="url".

This specifies a JSP page that should process any Throwables thrown but not

caught in the current page

isErrorPage

isErrorPage="true|false".

This indicates whether or not the current page can act as the error page

for another JSP page.

The default is false

Extends

Specifies a superclass that the generated servlet must extend

extends="package.class".

This indicates the superclass of servlet that will be generated.

Use this with extreme caution, since the server may be using a custom

superclass already

Info Defines a string that can be accessed with the servlet's getServletInfo() method

info="message".

isThreadSafe

Defines the threading model for the generated servlet

isThreadSafe="true|false".

A value of true (the default) indicates normal servlet processing

A value of false indicates that the servlet should implement

SingleThreadModel

language Defines the programming language used in the JSP page

language="java".

Session

Specifies whether or not the JSP page participates in HTTP sessions

session="true|false".

A value of true (the default) indicates that the predefined variable

session (of type HttpSession) should be bound to the existing session if

Page 24: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 24 hcr:innovationcse@gg

one exists, otherwise a new session should be created and bound to it.

A value of false indicates that no sessions will be used, and attempts to

access the variable session will result in errors at the time the JSP page

is translated into a servlet.

isELIgnored Specifies whether or not EL expression within the JSP page will beignored

isScriptingEna

bled Determines if scripting elements are allowed for use.

The include Directive

The include directive is used to includes a file during the translation phase.

This directive tells the container to merge the content of other external files with the

current JSP during the translation phase.

You may code include directives anywhere in your JSP page.

The general usage form of this directive is as follows

<%@ include file="relative url" >

<jsp:directive.include file="relative url" />

The filename in the include directive is actually a relative URL.

If you just specify a filename with no associated path, the JSP compiler assumes that the

file is in the same directory as your JSP

Example

<%@ include file="/navbar.html" %>

The taglib Directive

The JavaServer Pages API allows you to define custom JSP tags that look like HTML or

XML tags and a tag library is a set of user-defined tags that implement custom behavior.

The taglib directive declares that your JSP page uses a set of custom tags, identifies the

location of the library, and provides a means for identifying the custom tags in your JSP

page.

The taglib directive follows the following syntax:

<%@ taglib uri="uri" prefix="prefixOfTag" >

<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />

Where the uri attribute value resolves to a location the container understands and the prefix

attribute informs a container what bits of markup are custom actions.

Page 25: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 25 hcr:innovationcse@gg

Custom tag libraries

JSP is the technology that helps separate the front end presentation from the middle and

backend tiers.

The custom tag library is a powerful feature of JSP v1.1 that aids in that separation.

This technology is valuable to anyone who is building production-quality web applications,

and it is very applicable in today's market.

Custom tag libraries allow the Java programmer to write code that provides data access

and other services, and they make those features available to the JSP author in a simple

to use XML-like fashion.

An action in a web application -- for example, gaining database access -- can be

customized by using a custom tag in a JSP page.

The application typically will use JDO by using a Custom JSP tag library to abstract the

JDO API (similar to the way the JSP Standard Tag Library abstracts the JDBC API)

The JSP author doesn't have to understand the underlying detail to complete the action.

In short, a tag library is a collection of custom actions presented as tags.

Custom tags have many features that make them attractive to use from any JSP.

Custom tags can

be customized via attributes passed from the calling page, either statically or determined

at runtime;

have access to all the objects available to JSP pages including request, response, in and

out;

modify the response generated by the calling page;

communicate with each other; you can create and initialize a JavaBeans component,

create a variable that refers to that bean in one tag, and then use the bean in another

tag;

be nested within one another, allowing for complex interactions within a JSP page; and

encapsulate both simple and complex behaviors in an easy to use syntax and greatly

simplify the readability of JSP pages.

Page 26: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 26 hcr:innovationcse@gg

The Composition of a Tag Library

There are two types of components for a tag library:

o the tag library descriptor file

o the tag handlers.

With these a JSP is able to use tags contained in the library within its page.

The TLD File

A tag library descriptor (TLD) file is an XML document that describes the library.

A TLD contains information about the library as a whole and about each tag contained in

the library.

TLDs are used by a JSP container to validate the tags.

There is typically some header information followed by elements used to define the tag

library.

Element Description

<taglib> The tag library itself

<tlibversion> The tag library’s version

<jspversion> The JSP specification version the tag library depends on

<shortname>

A simple default name with a mnemonic value. For example, <shortname>

may be used as the preferred prefix value in taglib directives and/or to create

prefixes for IDs.

<uri> An optional URI that uniquely identifies the tag library.

<info> Descriptive information about the tag library

Example: DemoTag.TLD

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag

Library 1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<jspversion>1.1</jspversion>

<shortname>DemoTagLib</shortname>

<info>Demo Tag library</info>

<!-A Demo tag -->

<tag>

<name>hello</name>

<tagclass>SRM.examples.demo </tagclass>

<bodycontent>empty</bodycontent>

<info>

This is a demo tag.

</info>

<!-- Optional attributes -->

<!- personalized name -->

<attribute>

<name>name</name>

<required>false</required>

Page 27: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 27 hcr:innovationcse@gg

<rtexpvalue>false</rtexpvalue>

</attribute>

</tag>

</taglib>

The Tag Handler

The tag is defined in a handler class.

TagSupport is the base class used for simple tags.

It can be found in the javax.servlet.tagext package.

What your tag is implementing will depend on what methods could potentially be called

and what needs to be implemented.

TagSupport and TagBodySupport supply default implementations of the methods listed

below.

Depending upon the tag handler, we may need to implement some or all of the methods

doStartTag, doEndTag, release, doInitBody, doAfterBody, set/getAttribute1...N

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

public class Hello extends TagSupport {

private String name=null;

/**

* Getter/Setter for the attribute name as defined

* in the tld file for this tag

*/

public void setName(String value){

name = value;

}

public String getName(){

return(name);

}

/**

* doStartTag is called by the JSP container when the tag is

* encountered

*/

public int doStartTag() {

try {

JspWriter out = pageContext.getOut();

out.println("<table border="\1\">");

if (name != null)

out.println("<tr><td> Hello " + name + " </td></tr>");

else

out.println("<tr><td> Hello World </td></tr>");

} catch (Exception ex) {

throw new Error("todo: handle exception");

}

// Must return SKIP_BODY because we are not supporting a body

// for this tag.

return SKIP_BODY;

}

/**

Page 28: UNIT IV SERVER SIDE PROGRAMMING - WordPress.com · Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. Servlets, look

CS518 Internet Programming And Tools Unit IV

MTech CSE (PT, 2011-14) SRM, Ramapuram 28 hcr:innovationcse@gg

* doEndTag is called by the JSP container when the tag is closed

*/

public int doEndTag(){

try {

JspWriter out = pageContext.getOut();

out.println("</table>");

} catch (Exception ex){

throw new Error("todo: handle exception");

}

}

}

Once the TLD and tag handlers are created, you can begin accessing the tags in your JSP.

You declare that a JSP page will use tags defined in a tag library by including a taglib directive in

the page before any custom tag is used.

The prefix attribute is a shortcut to referencing the library throughout the page.

DemoTLib.JSP

<%@ taglib uri="/DemoTLib.tld" prefix="sample" %>

<html>

<head>

<title>Your Standard Hello World Demo</title>

</head>

<body bgcolor="#ffffff">

<hr />

<sample:hello name="Hello"/>

<hr />

</body>

</html>

Output

<html>

<head>

<title>Your Standard Hello World Demo</title>

</head>

<body bgcolor="#ffffff">

<hr />

<table border="1">

<tr><td> Hello</td></tr>

</table>

<hr />

</body>

</html>

Comments & Feedback

Thanks to my family members who supported me while I spent hours and hours to prepare this.

Your feedback is welcome at [email protected]