Jsp sasidhar

Post on 07-Aug-2015

129 views 0 download

Tags:

Transcript of Jsp sasidhar

JSPJava Server Pages

K.SASIDHAR

servlets• Server side Java programs• Solve scalability issue• serlvets are run on threads of execution not

separate processes• Solve portability issue• runs on every platform that supports Java• supported by all most popular web servers• Issues: • html tags are embedded in java programs within

out.print() statements

JSP -- Introduction • server-side technology

• separates dynamic content from static

content of a page

– Java scriptlets embedded into html-like page

• Separates the work of

– java programmers

– page authors

Introduction

• Java Server Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content

• Developed by Sun Micro Systems in 1999.

• Defines interaction between the server and JSP and describes the format and syntax of the page.

JSP page

• A page created by the web developer that includes JSP technology-specific and custom tags, in combination with other static (HTML or XML) tags.

• A JSP page has the extension .jsp or .jspx;

• This signals to the web server that the JSP engine will process elements on this page.

• Using the .xml deployment descriptor, additional extensions can be associated with the JSP engine.

Advantages of JSP • Provides a powerful and flexible mechanism to

produce dynamic web pages.

• It allows the creation of custom tag libraries to meet the specific needs of the project.

• It provides built-in support of HTTP session management.

• Can be integrated with : JDBC API, Thread API, EJB API etc..

JSP notations

• <% … %> jsp scriplet a fragment of code that

run when the user request the webpage.

• < %= > delimeter used for expressions

• <%@ > jsp directives

Anatomy of a jsp page <%@page contenttype = “text/html” language = “java%”><%@page import = “java.util.Date” session = “false”%>

Jsp elements

<html><head><title> simple jsp page demo</title></head><body> <h3> current time is : </h3>

Template data

<%= new Date()%> -- > jsp elements

</body></html> Template data

%@ is jsp directive

%= is jsp element

In a simple way

<HTML>

<BODY>

Hello!  The time is now <%= new java.util.Date() %>

</BODY>

</HTML>

Client and Server with JSP

Java Server Pages (JSP) in detail

Client’s Computer

Server

1.Browser requests HTML

7. Server sends HTML back to browser

servletservlet

class 5.The servlet runs and generates HTML

Java Engine

6. Java Engine sends HTML to server

2. Server sends requests to Java Engine

3. If needed, the Java Engine reads the .jsp file

4. The JSP is turned into a servlet, compiled, and loaded

Bean

JSP Life cycle

Translation Time• A JSP application is usually a collection of JSP

files, HTML files, graphics and other resources.• A JSP page is compiled when your user loads it

into a Web browser

1. When the user loads the page for the first time, the files that make up the application are all translated together, without any dynamic data, into one Java source file (a .java file)

2. The .java file is compiled to a .class file. In most implementations, the .java file is a Java servlet that complies with the Java Servlet API.

JSP Elements• Declarations <%! code %>

<jsp:declaration>

</jsp:declaration >

• Expressions <%= expression %>

<jsp:expression>

</jsp:expression>

• Scriplets <% code %>

<jsp:scriplet>

</jsp:scriplet >

Declaration• Declares a variable or method valid in the scripting language used in the JSP

page. – Syntax

<%! declaration; [ declaration; ]+ ... %>– Examples

<%! String destin; %>

<%! Public String getDestination()

{return destin;}%>

<%! Circle a = new Circle(2.0); %>

– You can declare any number of variables or methods within one declaration

element, as long as you end each declaration with a semicolon. – The declaration must be valid in the Java programming language.

Declaration Example<HTML>

<HEAD><TITLE>JSP Declarations</TITLE></HEAD>

<BODY><H1>JSP Declarations</H1>

<%! private int keepCount = 0; %>

<H2>

Page accessed:

<%= ++keepCount %>

times

</H2>

</BODY>

</HTML>

Predefined Variable – Implicit Objects• request – Object of HttpServletRequest (request parameters, HTTP

headers, cookies

• response – Object of HttpServletResponse

• out - Object of PrintWriter buffered version JspWriter

• session - Object of HttpSession associated with the request

• application - Object of ServletContext shared by all servlets in the engine

• config - Object of ServletConfig

• pageContext - Object of PageContext in JSP for a single point of access page – variable synonym for this object

Expression• Contains an expression valid in the scripting language used in the JSP page.

– Syntax

<%= expression %>

<%! String name = new String(“JSP World”); %><%! public String getName() { return name; } %>

<B><%= getName() %></B>Description:

An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.

– Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSPfile. Expressions are evaluated from left to right.

Expression Example<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() %></UL></BODY></HTML>

Scriptlet• Contains a code fragment valid in the page scripting language.

– Syntax<% code fragment %>

<%String var1 = request.getParameter("name");

out.println(var1);%> This code will be placed in the generated servlet method:

_jspService()

Scriplet Example<HTML>

<HEAD><TITLE>Weather</TITLE></HEAD>

<BODY>

<H2>Today's weather</H2>

<% if (Math.random() < 0.5) { %>

Today will be a <B>suny</B> day!

<% } else { %>

Today will be a <B>windy</B> day!

<% } %>

</BODY>

</HTML>

JSP Scriptlets Example

<%for (int i=100; i>=0; i--) { %> <%= i %> The numbers in

decending order are: <br><%}%>

Another example: JSP Tags + HTML Tags

<h2>Table of Square Roots</h2><table border=2> <tr> <td><b>Number</b></td> <td><b>Square Root</b></td> </tr> <% for (int n=0; n<=100; n++) { %> <tr> <td><%=n%></td> <td><%=Math.sqrt(n)%></td> </tr> <% } %></table>

JSP Page Directive• Directives are messages to the JSP container and do not produce

output into the current output stream– Syntax:<%@ directive attribute=“value” %><%@ directive attribute1=“value1”

attribute1 =“value2” … %> There are three types of directives:1. page2. include3. Taglib

XML form: <jsp:directive.directiveType attribute=“value” />

Purpose of the page Directive

• Give high-level information about the servlet that will result from the JSP page

• Can control– Which classes are imported

– What class the servlet extends

– What MIME type is generated

( Multipurpose Internet Mail extensions )

– How multithreading is handled

– If the servlet participates in sessions

– The size and behavior of the output buffer

– What page handles unexpected errors

Page Directive

• Defines attributes that apply to an entire JSP page. <%@ page [ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*}, ..." ] [ session="true|false" ] [ buffer="none|8kb|sizekb" ] [ autoFlush="true|false" ] [ isThreadSafe="true|false" ] [ info="text" ] [ errorPage="relativeURL" ] [ contentType="mimeType [ ;charset=characterSet

]" [ isErrorPage="true|false" ] %>

Include Directive

• Includes a static file in a JSP file, parsing the file's JSP elements. – Syntax

<%@ include file="relativeURL" %>

The <%@ include %> directive inserts a file of text or code in a JSP file at translation time, when the JSP file is compiled.

<%@ include %> process is static. A static include means that the text of the included file is added to the JSP file.

The included file can be:

1. JSP file,

2. HTML file,

3. text file.

Taglib Directive• Defines a tag library and prefix for the custom tags used in the JSP page.– Syntax

<%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %>

<%@ taglib uri="http://thathost/tags" prefix="public" %>

<public:loop>

</public:loop>

The <%@ taglib %> directive declares that the JSP file uses custom tags, names the tag library that defines them, and specifies their tag prefix.

<jsp:forward>(Used in server redirection)

• Forwards a client request to an HTML file, JSP file, or servlet for processing. – Syntax

<jsp:forward page="{relativeURL | <%= expression %>}" />

<jsp:forward page="{relativeURL | <%= expression %>}" >

<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+

</jsp:forward>

<%@ page errorPage="error.jsp" %>

<%!

public double calculate(double amount, double interest, int period) {

if(amount <= 0) {

throw new IllegalArgumentException("Amount should be greater than 0: " + amount);

}

if(interest <= 0) {

throw new IllegalArgumentException("Interest should be greater than 0: " + interest);

}

if(period <= 0) {

throw new IllegalArgumentException("Period should be greater than 0: " + period);

}

return amount*Math.pow(1 + interest/100, period);

}

%>

Loan Calculator compound.jsp

<html>

<head>

<title>Compound</title>

</head>

<body style="font-family:verdana;font-size:10pt;">

<%@ include file="header.html" %>

<%

double amount = Double.parseDouble(request.getParameter("amount"));

double interest = Double.parseDouble(request.getParameter("interest"));

int period = Integer.parseInt(request.getParameter("period"));

%>

<b>Pincipal using compound interest:</b>

<%= calculate(amount, interest, period) %>

<br/><br/>

<jsp:include page="footer.jsp"/>

</body>

</html>

Uses of JSP Constructs:Using JavaBeans • Scripting elements calling servlet

code directly• Scripting elements calling servlet

code indirectly (by means of utility classes)

• Beans• Custom tags• Servlet/JSP combo

(MVC architecture)

SimpleApplication

ComplexApplication

JavaBeans• The other standard actions relate to

manipulation of JavaBeans within a JSP page.

• JavaBeans is a component architecture.

• It dictates a set of rules that software developers must follow to create reusable components.

• A Bean is an instance of a class that was coded following these rules.

• JSP interacts with Beans through tags (naturally).

<jsp:useBean>• Locates or instantiates a bean with a specific name and

scope. <jsp:useBean id="beanInstanceName" scope="page|request|session|application" { class="package.class" | type="package.class" | class="package.class" type="package.class"

| beanName="{package.class | <%= expression

%>}“ } { /> | > other elements </jsp:useBean> }

Background: What Are Beans?

• Classes that follow certain conventions– Must have a zero-argument (empty) constructor– Should have no public instance variables (fields)– Persistent values should be accessed through

methods called getXxx and setXxx• If class has method getTitle that returns a String, class is

said to have a String property named title• Boolean properties use isXxx instead of getXxx

• For more on beans, see http://java.sun.com/beans/docs/

Basic Bean Use in JSP

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

• Purpose: Allow instantiation of classes without explicit Java syntax

• Notes– Simple interpretation: JSP action<jsp:useBean id="book1" class="cwp.Book" />can be thought of as equivalent to the scriptlet<% cwp.Book book1 = new cwp.Book(); %>

– But useBean has two additional features• Simplifies setting fields based on incoming request params• Makes it easier to share beans

Attributes and Usage• id="beanInstanceName"

A variable that identifies the bean in the scope you specify.

The name is case sensitive and must conform to the naming

conventions of the scripting language used in the JSP page

scope="page|request|session|application“

page   One can use the bean within the JSP page with the <jsp:useBean> element or any of the page's static include files, until the page sends a response back to the client or forwards a request to another resource

request   One can use the bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another resource. One can use the request object to access the bean, for example, request.getAttribute(beanInstanceName).

Attributes and Usage ……session   One can use the bean from any JSP page

in the same session as the JSP page that created the bean. The bean exists across the entire session, and any page that participates in the session can use it. The page in which you create the bean must have a page directive with session="true".

application   One can use the bean from any JSP page in the same application as the JSP page that created the bean. The bean exists across an entire JSP application, and any page in the application can use the bean.

Different Scope

ApplicationApplication

SessionSession

RequestRequest

PagePage

Least visibleLeast visible

Most visibleMost visible

Objects accessible only within pageswhere they were created.

Objects accessible from pages processing the request.

Objects accessible from pagesBelonging to the same session.

Objects accessible from pagesBelong to the same application.

<jsp:setProperty>• Sets a property value or values in a bean.

– Syntax<jsp:setProperty name="beanInstanceName"

{ property="*" | property="propertyName" [ param="parameterName" ] | property="propertyName" value="{string | <%= expression %>}"

} /> Ex: <jsp:setProperty name="mybean" property="*" /> <jsp:setProperty name="mybean" property="username"

/> <jsp:setProperty name="mybean" property="username"

value="Steve" />

Setting Bean Properties: Simple Example

• Format: <jsp: setProperty name="name" property="property" value="value" />

• Purpose– Allow setting of bean properties (i.e., calls to

setXxx) without explicit Java code

• Notes– <jsp:setProperty name="book1" property="title" value="Core Servlets and JSP" />

is equivalent to the following scriptlet<% book1.setTitle("Core Servlets and JSP"); %>

Jsp setproperty ….

The <jsp:setProperty> element sets the value of one or more properties in a bean,

using the bean's setter methods. You must declare the bean with<jsp:useBean> before

you set a property value with <jsp:setProperty>.

<jsp:getProperty>• Gets the value of a bean property so that you can display it in a result page. – Syntax

<jsp:getProperty name="beanInstanceName“ property="propertyName" />

– Example: <jsp:useBean id="calendar" scope="page" class="employee.Calendar" /> <h2> Calendar of <jsp:getProperty name="calendar" property="username" /> </h2>The <jsp:getProperty> element gets a bean property value using the property's getter methods and displays the property value in a JSP page. You must create or locate a bean with <jsp:useBean> before you use <jsp:getProperty>.

Jsp with Beanspublic class MessageBean {

private String message = "No Message";

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

}

JavaBeans with JSP Page<jsp:useBean id="firstBean" scope="session"

class="packBeans.MessageBean"/>

<jsp:setProperty name="firstBean"

property="message"

value="This is a message from a bean" />

<H1>Message:

<I><font color="#0000FF" size=+3>

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

</I></font>

</H1>

Handling Forms with JSPpackage packBeans;

public class NameBean {

private String name;

public NameBean() {

name = null;

}

public String getName() {

return name;

}

public void setName(String aName) {

name = aName;

}}

JSP Form<jsp:useBean id='nb' scope='session' class=‘packBeans.NameBean'/>

<jsp:setProperty name='nb' property="*"/>

<HTML>

<BODY>

<H1>Please enter your name to be registered to JSP Course?</H1>

<FORM method="get">

<INPUT type="text" name="name" size="25">

<INPUT type="submit" value="Submit">

</FORM>

<% if ( request.getParameter("name") != null ) } %>

<%=

"Click<a href=GetName.jsp> here</a> to confirm your registration"

%>

<% } %>

</BODY>

</HTML>

JSP Results

<jsp:useBean id='nb' scope="session“class=“packBeans.NameBean"/>

<HTML> <HEAD> <TITLE>Registered Name</TITLE> </HEAD> <BODY>

<jsp:getProperty name="nb" property="name"/>

</BODY></HTML>

Work with the Buffer• When the page is being processed, the data is

stored in the buffer instead of being directly sent to the client browser.

<<htmlhtml>>This is a test of the bufferThis is a test of the buffer<<brbr/>/><%<%out.flush();out.flush();for (int x=0; x < 100000000; x++);for (int x=0; x < 100000000; x++);out.print("This test is generated about 5 out.print("This test is generated about 5

seconds later.");seconds later.");out.flush();out.flush();%>%></</htmlhtml>>

Working with Session object• The session object has many useful methods

that can alter or obtain information about the current session.– setMaxInactiveInterval(second)

<<htmlhtml><><headhead>><<titletitle>>Session ValuesSession Values</</titletitle>></</headhead><><bodybody>><%<%session.setMaxInactiveInterval(10);session.setMaxInactiveInterval(10);String name = (String) String name = (String)

session.getAttribute("username");session.getAttribute("username");out.print("Welcome to my site " + name + out.print("Welcome to my site " + name +

"<br>");"<br>");%>%></</bodybody></></htmlhtml>>

Model View Controller

1. Model: This is business logic of applications,

responsible for performing the actual work conducted

by the application. This unit deals with the modeling of

real-world problem and doesn’t have any idea about

how it is being displayed to the user.

2. View: This is presentation logic of the application

responsible for rendering the information or data of the

application. It may have little or no programming logic

at all.

MVC3.Controller: This is the request processing logic of the

application,& mainly responsible for coupling between both the model and view together, so as to perform the operations.

• It is like a traffic controller directing request to the corresponding resources and forwarding appropriate response to the user.

• Finally the goal of MVC is the separation of content presentation (view), and content generation (Model) there by developing maintainable, flexible and extensible application.

• Java Programmers can concentrate on writing java code (model and controller) and web designers could concentrate on using dream weaver, Photoshop to build fabulous-looking web pages (for view)

MVC

Controller

Model

View

Data Base

5: forward to view

2: Invoke

3: retrieve/store data 4: Get result

1: request

6: response

User

Java Server Pages• Model 2 Architecture to serve dynamic content

– Model: Enterprise Beans with data in the DBMS• JavaBean: a class that encapsulates objects and can be displayed

graphically

– Controller: Servlets create beans, decide which JSP to return, do the bulk of the processing

– View: The JSPs generated in the presentation layer (the browser)

53

MVC Benefits

• Clarity of design– easier to implement and maintain

• Modularity– changes to one don't affect the others– can develop in parallel once you have the

interfaces• Multiple views

– games, spreadsheets, powerpoint, Eclipse, UML reverse engineering, ….

54

MVCDesign Pattern

Architecture