Você está na página 1de 36

Web Technologies

www.lectnote.blogspot.com

MODULE 4: JAVASERVER PAGES JSPs - Creating simple JSP Pages templating Request time expression Request & Response objects Reading parameter values Using Javabeans in JSPs - Reading & setting Properties of JavaBeans Connecting forms & bean properties Serialized beans declaring variables & methods in pages scriptlets conditionals, loops & execution handling in JSPs with scriptlets Accessing beans via scriptlets. INTRODUCTION JSP is a Java based technology that is run on a server to facilitate the processing of Web based request. Creating applications for the internet Internet or Internal network

1. enters URL Web 5. displaysbrowser HTML


2. sends request to web server
4. responds with HTML page

Web Server

3.web server fetches stored HTML page

1.Enter the URL of a web page in your browser. This tells the browser to contact specific machine on the internet. 2.Browser then sends the request to specified machine on the internet. Machine runs a software called a web server. This receives the request and examines it. Eg: for web sever:=Apache, Oracle HTTP server ,etc.

Web Technologies

www.lectnote.blogspot.com

3.Depending on the request received the web server retrieves from its storage a web page encoded in HTML. 4. The page thus acquired is passed back to the requesting web browser as a response. 5. The browser after receiving the response Web page, displays it to the user. The web page contain graphical elements such as GIF files, as well as hyperlinks to the URLs.

Limitations of the basic Web server model The basic function of Web server restricts it to serve a finite no of static Web pages. The content of each page remains the same. There is no easy way to show the change in information. A new set of pages needs to be created. Creating new static pages for every minute change of information is tedious. A lot of time and effort could be saved if there is some way of server to automatically generate portions of HTML page. This should happen dynamically when the request is processed. CGI provides this. Dynamic HTML generation via CGI CGI provides way to execute program on the server side; it may be on the same machine running the web server, or another machine. The output is an HTML page which is then send back to web browser for display. 1. The browser is instructed to access a URL. This tells the browser to contact a machine on the internet. 2. The browser then sends request to specified machine on the internet. In addition to this, the URL also specifies a specific CGI program location. The portion of the URL that specifies the location is beginjsp/ch1test.cgi. The web server examines the incoming request URL and forwards the incoming request to the specified CGI program. 3. The CGI program is executed on the server side. 4. The CGI programs output is captured by the web server. 5. This CGI programs output is passed back to the requesting web browser using the HTTP protocol. 6. The client web browser finally displays the output from the CGI program as an HTML page.

Web Technologies

www.lectnote.blogspot.com

3.runs prgrm

4.takes output as response CGI program

To or from other systems, Databases, etc

The CGI program can be programmed using any programming language. The output is not limited to finite set of static pages. CGI program can access additional resources in generating an output. Shortcomings of CGI i) The overhead of starting an OS process for each incoming request. ii) The overhead of loading and running a program for each incoming request. iii) The need for tedious and repetitive coding to handle the network protocol & request decoding. The first 2 operations consumes a large no of CPU cycles and memory. If too many requests arrive in short period of time, the server machine will be overloaded, as it has to perform the 2 operations. It is not possible to share code used in networking and decoding.

Web Technologies

www.lectnote.blogspot.com

Java programming language can be used to create CGI program. This is not suitable for handling CGI request because Java is inherently an interpreted language. So a very large program called the Java Virtual Machine (JVM) must be started. The cycle of starting s/m process, then a JVM within the process, and then running a Java CGI code within the JVM just for processing a single request is very expensive. The whole process needs to be repeated for each incoming request. It takes time to process the request & generate the output. Improving Java based CGI: servlets It can be improved if the overhead is eliminated. This is possible by processing all the incoming requests by initially starting a single OS process with a single JVM image. Because Java platform can load new classes during run time dynamically, this capability can be used to load new java code (classes) to handle incoming requests. ie, i) The overhead of starting an OS for each request is eliminated. ii) Overhead of loading a JVM for each request is eliminated. iii) Java classes are loaded by JVM to process incoming request. JAVASERVER PAGES JSP is a Java based technology that is run on a server to facilitate the processing of Web based request. JSP is actually the combination of HTML and java, the java program is embedded within HTML. It actually developed in 1999 by Sun Microsystems. The aim was to develop dynamic content by overcoming the disadvantages of CGI. In order to execute server side JSP it uses JSP container class. The users request is send to web server for processing. The web server process the request using JSP container which helps in processing. The HTML is given to JSP container classes which convert into java programs or servlets (purely written in java). These servlets actually interact with database or other data sources and processes the users request.

JSP content

Given to JSP container classs

converts into

Java servlets

Data base

Structure of JSP 4

Web Technologies

www.lectnote.blogspot.com

JSP page contains Template data Action Scripting elements Directive elements

Template : It actually provides the static HTML pages. It is the static text.This is passed directly through the JSP container unprocessed

Action: It is a special tag (XML based tag that is involved in the processing of the request). Eg: <jsp: use Bean>,<jsp: set Property> etc

Scripting elements: Scripting elements are embedded code in the java programming language within a JSP. There are three different types of scripting elements. Declarations: These are java code that is used to declare variables and methods. <%! java Declaration %> Eg: <%! int count=10; %> <%! int count=0; double value=10.0; %> Expressions: Expressions are java expressions that yield a resulting value. Syntax: <% = java expression %> Eg: <%= count+1 %> semicolon****]] [[****java expression does not end with a

Scriptlets : A scriptlet is a piece of java code that is sandwiched between the characters <% and %>.By itself, a scriptlet doesn't contribute any HTML. A scriptlet contains Java code that is executed every time the JSP is invoked. Eg: <HTML>

Web Technologies

www.lectnote.blogspot.com

<BODY> <% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. System.out.println ("Evaluating date now"); java.util.Date date=new java.util.Date(); %> Hello! The time is now <%= date %> </BODY> </HTML>

Directives: It is used to give special instruction to the JSP container about what to do during the translation of the page. Syntax: <% @ directive name attribute name = attribute value %> JSP support 3 different directive names Page Include Taglib Page directive It provides global information for a page.

Attribute are:-

a)

import : Used to specify the library classes that will be used with the JSP page. Eg :-<%@ page import=java.util.Color%>

b)

errorPage & isErrorPage: <%@ page isErrorpage =true%> isErrorpage : It tells the JSP container that this page is used by other JSP pages to handle errors. errorPage : it is a URL to a JSP that will be executed when an error occurs. 6

Web Technologies

www.lectnote.blogspot.com contentType: tells the container that what formats the output of the JSP represents. <%@page contentType= text/html%>

c)

d)

session, language, buffer ,isThreadSafe, autoFlash,extends etc are other attributes.

Include directive: Used to insert text and code to JSP at translation time ie at the time of code generation. Attribute is file <% @include file =news.jsp %>

Taglib directive: It tells the JSP container which tag library a specific JSP requires. It is used to assign prefix that is used within the JSP page (to identify tags from specific tag library). There are mainly two attributes used:Uri: identifies the tag library Prefix: used to distinguish different tags. [Defines a mechanism for extending the current set of JSP tags: by the used of tag library] Eg:- <% @ taglib prefix =c uri=http://java.sun.com/jsp/jstl/core %>

REQUEST TIME EXPRESSION(EL Expressions) The expression which can be evaluated at the request time itself is called Request Time Expression. The basic syntax is ${expression}

EL expressions may appear in two distinct locations in a JSP page. In-line with template data Within attributes values of tags

EL Implicit Objects Implicit objects are built in objects that can be used within any EL expression. There are 11 implicit 7

Web Technologies

www.lectnote.blogspot.com

objects(param,paramValues,header,headerValues,cookies,pageContext,pageScope,requestScope ..) param : It is a map containing all the incoming request parameters. In EL values of a map can be accessed via the [] notation or the dot(.) notation. Eg: ${ param. address} paramValues: it is a map providing access to all multivalued incoming request parameters. Eg: ${ paramValues.itemPurchased }/***************Refer JSP WROX****************/

Example of Request Time Expression for Arithmetic Operation <html><title>Arithmetic Operations</title> <body> <b>2+2 is ${2+2} and 4*4 is ${4*4}</b> </body></html> //output 2+2 is 4 and 4*4 is 16 //process.htm <html><title>Personal Information</title><body> <form action="process.jsp" method=post> <TABLE width=300 border=1> <TR> <TD >Name</TD><TD ><INPUT name=fname></TD></TR> <TR> <TD >Address</TD> <TD><TEXTAREA name=address cols=16></TEXTAREA></TD></TR> <TR> <TD >Gender</TD> <TD ><INPUT type=radio name=gender value="Male">Male <INPUT type=radio name=gender value="Female">Female </TD></TR> <TR><TD>Qualification</TD><TD ><SELECT > <OPTION value=BTech selected>BTech</OPTION> <OPTION value=MTech>MTech</OPTION> <OPTION value=MBBS>MBBS</OPTION> </SELECT></TD></TR> <TR><TD align=middle><INPUT id=submit1 type=submit value=Submit name=submit1></TD></TR> 8

Web Technologies

www.lectnote.blogspot.com

</TABLE></form> </body> </html> //Output-process.html Name


Vivek Chopra Delhi

Address

Gender Qualification

Male
BTech

Female

Submit

//process.jsp <html> <title>Personal Information</title> <body> <TABLE border=1> <TR> <TD >Name</TD> <TD >${param.fname}</TD></TR> <TR> <TD>Address</TD> <TD >${param.address}</TD></TR> <TR> <TD >Gender</TD> <TD >${param.gender}</TD></TR> <TR><TD >Qualification</TD><TD >${param.qual}</TD></TR> </TABLE></body></html> //output process.jsp

Name Address Gender Qualification

Vivek Chopra Delhi Male B.Tech

EVALUATING EXPRESSION AT RUN TIME 9

Web Technologies

www.lectnote.blogspot.com

In JSP we can evaluate expression at run time using <%=expression %>. The following example for finding Square root of a set of given numbers combines JSP tag, HTML tag and Java Statements //sqt.jsp <html> <title>Square Root</title> <body> <TABLE border=1> <TR> <TD > Number</TD> <TD >Square Root</TD></TR> <% for (int n=0;n<=5;n++) { %> <TR><TD ><%=n%></TD><TD ><%=Math.sqrt(n)%></TD></TR> <% } %> </TABLE></body></html> //output Number 0 1 2 3 4 5 Square Root 0.0 1.0 1.4142135623730951 1.7320508075688772 2.0 2.23606797749979

REQUEST AND RESPONSE OBJECT Implicit Objects: Implicit objects in JSP are objects that are immediately usable within a JSP page, without an explicit creation or declaration.

10

Web Technologies

www.lectnote.blogspot.com

request: It represents the request currently being processed. The Implicit object request is used to access request parameters. We can do this by calling request objects getParameter() method, with the parameter name you are looking for. It will return a string with value matching the named parameter. response : This represents the response being sent back to the browser. It is equivalent to the implicit object out. Two useful methods are response. sendRedirect (target URL); and response. sendError(404) //company.html <html> <title>Company Information</title> <body> <BODY> <form action="company.jsp" method=post> <TABLE border=1><TR><TD >Company Name</TD> <TD ><INPUT name=company></TD></TR> <TR><TD >Street</FONT></TD><TD ><INPUT name=street></TD></TR> <TR><TD>City</TD><TD ><INPUT name=city></TD></TR> <TR><TD >State</TD> <TD <INPUT name=state></TD></TR> <TR><TD ></TD> <TD ><INPUT type=submit value=Submit ></TD></TR></TABLE> </form></body></html> //company.jsp <html><title>company Information</title> <body> <TABLE border=1> <TR><TD >Name</TD> <TD > <%=request.getParameter("company")%></TD></TR> <TR><TD >Street</TD> <TD ><%=request.getParameter("street")%></TD></TR> 11

Web Technologies

www.lectnote.blogspot.com

<TR><TD >City</TD> <TD><%=request.getParameter("city")%></TD></TR> <TR><TD >State</TD> <TD><%=request.getParameter("state")%></TD></TR> </TABLE></body></html> //output company.html Company Name Street City State Wipro as asd asdf
Submit

company. jsp Name Wipro Street as City asd

State asdf

Example: //login.htm <HTML><TITLE>Login</TITLE> <BODY> <form action="logincheck.jsp" method=post> <TABLE border=1> <TR><TD >User Name</TD> <TD> <INPUT name=uname></TD></TR> <TR><TD>Password</TD> <TD><INPUT type=password name=pwd></TD></TR> <TR><TD > <INPUT type=submit value=Submit name=submit1></TD></TR> 12

Web Technologies

www.lectnote.blogspot.com

</TABLE> </form> </BODY> </HTML> //logincheck.jsp <%if (request.getParameter("pwd").equals("winner")) { %> <h2>Welcome , <%=request.getParameter("uname")%></h2> <% } else { response.sendError(403); } %> //output(html) User Name Welcome Password
Submit

********

//output : Welcome, Computer READING REQUEST PARAMETER VALUES

We can process the request parameter in two ways.One using param collection ie ${param.fieldname} and another using request.getParameter(fieldname)

//order.htm <HTML> 13

Web Technologies

www.lectnote.blogspot.com

<TITLE>ORDER </TITLE> <BODY><FORM action="entry.jsp" method=POST id=form1 name=form1> <b>ORDER INFORMATION</b> <TABLE border=1> <TR><TD>Name</TD> <TD><INPUT type=text name=Name></TD></TR> <TR><TD>Address</TD><TD><TEXTAREA name=Address></TEXTAREA></TD></TR> <TR><TD>Order Type</TD><TD><INPUT type=radio value="Home Delivery" name=Otype>Home Delivery <INPUT type=radio value="Direct Delivery" name=Otype>Direct Delivery</P></TD></TR> <TR> <TD>Pizza Type</TD><TD> <INPUT type=checkbox value="pepper" name=ptype>Pepper <INPUT type=checkbox value="Sweet Corn" name=ptype>Sweet Corn</FONT></TD></TR> <TR> <TD>Pizza Size</TD><TD><SELECT style="WIDTH: 90px" name=psize> <OPTION value=Small selected>Small</OPTION> <OPTION value=Medidm>Medium</OPTION> <OPTION value=Large>Large</OPTION> </SELECT></TD></TR> <TR> <TD ><INPUT id=submit1 type=submit value=Submit name=submit1></TD></TR></TABLE> </FORM> </BODY></HTML>

14

Web Technologies

www.lectnote.blogspot.com

//entry.jsp

<html> <body> <p align=center><b> You have Entered:</b></p> <TABLE style="WIDTH: 270px; HEIGHT: 226px" cellSpacing=0 cellPadding=0 align=center border=1> <TR><TD>Name</TD><TD> size=4${param.Name} </TD></TR> <TR><TD>Address</TD><TD>${param.Address}</TD></TR> <TR><TD>Order Type</TD><TD>${param.Otype}</TD></TR> <TR><TD>Pizza Type</TD><TD><FONT size=4>${paramValues.ptype[0]} ${paramValues.ptype[1]}</TD></TR> <TR><TD>Pizza Size</TD><TD>${param.psize}</TD></TR> </TABLE></body></html> //process.htm

ORDER INFORMATION

Name

ASD

Name Address Order type Pizza type Pizza size

ASD asd Home Delivery Pepper small

asd

Address

15

Web Technologies

www.lectnote.blogspot.com

Order Type Pizza Type Pizza Size


Submit

Home Delivery Pepper


Small

Direct Delivery

Sweet Corn

Using Java Beans in JSP Java Bean is a reusable component. We can use java beans in different programming applications or environments. Certain actions used are: 1. <jsp:useBean> Locates or instantiates a Bean with a specific name and scope. Used to create an object of the java bean.

Description The <jsp:useBean> element locates or instantiates a JavaBeans component. <jsp:useBean> first attempts to locate an instance of the Bean. If the Bean does not exist, <jsp:useBean> instantiates it from a class . To locate or instantiate the Bean, <jsp:useBean> takes the following steps, in this order: 1. Attempts to locate a Bean with the scope and name you specify. 2. Defines an object reference variable with the name you specify. 16

Web Technologies

www.lectnote.blogspot.com

3. If it finds the Bean, stores a reference to it in the variable. If you specified type, gives the Bean that type. 4. If it does not find the Bean, instantiates it from the class you specify, storing a reference to it in the new variable 5. If <jsp:useBean> has instantiated (rather than located) the Bean, and if it has body tags or elements (between <jsp:useBean> and </jsp:useBean>), executes the body tags. The body of a <jsp:useBean> element often contains a <jsp:setProperty> element that sets property values in the Bean. As described in Step 5, the body tags are only processed if <jsp:useBean> instantiates the Bean. If the Bean already exists and <jsp:useBean> locates it, the body tags have no effect. The attributes are Syntax <jsp:useBean id="beanInstanceName" scope="page | request | session | application" class="package. class" | type="package. class" /> Examples: <jsp:useBean id="myaddbook" scope="session" class="test.AddressBook" /> Attributes and Usage

Id - Name of java bean instance. class - Specifies the class name of the java bean. Scope - Life or scope of the java object.

id="beanInstanceName"

A variable that identifies the Bean in the scope you specify. You can use the variable name in expressions or scriptlets in the JSP file. The name is case sensitive and must conform to the naming conventions of the scripting language used in the JSP page. If you 17

Web Technologies

www.lectnote.blogspot.com

use the Java programming language, the conventions in the Java Language Specification. If the Bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.

scope="page | request | session | application"

The scope in which the Bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:
o

page - You 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 file.

request - You 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 file. You can use the request object to access the Bean, for example, request.getAttribute(beanInstanceName).

session - You 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 - You 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.

class="package.class" Instantiates a Bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor. The package and class name are case sensitive.

type="package.class"

18

Web Technologies

www.lectnote.blogspot.com

If the Bean already exists in the scope, gives the Bean a data type other than the class from which it was instantiated. If you use type without class or beanName, no Bean is instantiated. The package and class name are case sensitive. 2. <jsp:setProperty> Used to set properties of java beans.

Description 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>. Because <jsp:useBean> and <jsp:setProperty> work together, the Bean instance names they use must match (that is, the value of name in <jsp:setProperty> and the value of id in <jsp:useBean> must be the same). You can use <jsp:setProperty> to set property values in several ways:

By passing all of the values the user enters (stored as parameters in the request object) to matching properties in the Bean

By passing a specific value the user enters to a specific property in the Bean By setting a Bean property to a value you specify as either a String or an expression that is evaluated at runtime

The attributes are Name: The name of an instance of a Bean that has already been created or located with a <jsp:useBean> element. The value of name must match the value of id in <jsp:useBean>. The <jsp:useBean> element must appear before <jsp:seProperty> in the JSP file. Name of java bean object / instance. Value: Value of that property. 19

Web Technologies

www.lectnote.blogspot.com

Property: Name of the property that we want to set.

Syntax: <jsp:setProperty name="beanInstanceName" value=new value property="property name" /> Example: <jsp:setProperty name="cart" property="*" /> We can use * symbol instead of specifying property name for setting the values of all properties. This will cause the container to match each request parameter against the properties of the Java Bean and perform an assignment for each property with an identical name to a request parameter. 3. <jsp:getProperty> Used to get the property values. The attributes are Name: Name of java bean object / instance. Property: Name of the property that we want to set

Syntax: <jsp:getProperty name="beanInstanceName" property="property name" /> Example Program Use a java bean that acts as a counter. It has a single integer property. The variable 'count' holds the current number of times the bean property has been accessed. It also contains appropriate methods for getting and setting this property.

Counter.java package test public class Counter

private int count; public counter()

//declares a new property value..

20

Web Technologies

www.lectnote.blogspot.com //initializes the property value.

{ count=0; } public int getCount() { count++; return (this.count); } public void setCount(int c) { } } this.count=c;

//accessor method

//mutator method

BeanCounter.jsp <html> <body> <jsp:useBean id="counter" scope ="session" class="Counter"/> //Instantiate a javaBean <jsp:setProperty name="counter" value=10 property="count"/> //write the current value of property count //will call mutator method. (request the parameter count using setProperty Count from jsp:getproperty: <jsp:getProperty name="counter" property="count"/> //Count from jsp:getProperty: </body> </html>

Step1: create a folder myjsp inside the root folder of Apache called webapps Step2: create a Counter.java file in a package called test inside webapps\myjsp folder of Apache. Step 3: compile the Counter.java file and put the Counter.class file in the webapps\myjsp\WEB-INF\classes\test 21

Web Technologies

www.lectnote.blogspot.com

Step4: Create the JSP called BeanCounter.jsp that uses Counter bean and place it in webapps\myjsp\test folder Step 5: Run the BeanCounter.jsp using the URL:http://localhost:8080/myjsp/test/BeanCounter.jsp The output is Count from jsp:getproperty:11

ACCESSING JAVABEANS THROUGH SCRIPLETS The scriplet element can be used to add a whole block of code to a page, including variable declarations. The code block must be enclosed by a scriptlet start-identifier, <% and an end identifier, %>. //Example 2 //StringBean.java package tbean; /** A simple bean that has a single String property called message */ public class StringBean {private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } } //StringBean.jsp <HTML> <HEAD> <TITLE>Using JavaBeans with JSP</TITLE> 22

Web Technologies

www.lectnote.blogspot.com

</HEAD> <BODY> <h1>Using JavaBeans with JSP</h1> <jsp:useBean id="stringBean" class="tbean.StringBean" /> <OL> <LI>Initial value (getProperty): <I><jsp:getProperty name="stringBean" property="message" /></I> <LI>Initial value (JSP expression): <I><%= stringBean.getMessage() %></I> /*Using Scriptlets*/

<LI><jsp:setProperty name="stringBean" property="message"value="Welcome to JSP world" /> Value after setting property with setProperty: <I><jsp:getProperty name="stringBean" property="message" /></I> <LI><% stringBean.setMessage("Use javaBean in JSP"); %> /* Using Scriptlets*/

Value after setting property with scriptlet: <I><%= stringBean.getMessage() %></I> </OL> </BODY> </HTML> //output Using JavaBeans with JSP 1. Initial value (getProperty): No message specified 2. Initial value (JSP expression): No message specified 3. Value after setting property with setProperty: Welcome to JSP world 4. Value after setting property with scriptlet: Use javaBean in JSP /* Using Scriptlets*/

Connecting Forms and Beans Properties 23

Web Technologies

www.lectnote.blogspot.com

Example Program Create an HTML form as follows Name : Address : Phone :


SUBMIT

Thomas pala 239301

Addressbook.html <html> <body><form action=retrieve.jsp method = get> <table cellspacing = 1 cellpadding = 1 border =1 align = center> <tr> <td align = middle>Name : </td> <td align = middle><input type=text name=name></td> </tr> <tr> <td align = middle>Address : </td><td align = middle><input type=text name=address> </td></tr> <tr> <td align = middle>Phone : </td> name=phone> </td></tr> <tr><td colspan=2><input type=submit name=button value=SUBMIT> </td></tr> </table> </form> </body></html> AddressBook.java //Create the java bean with the properties name, address, phone. Write accessor and mutator methods. package test; public class AddressBook 24 <td align = middle><input type=text

Web Technologies

www.lectnote.blogspot.com

private String name; private String address; private String phone; public void AddressBook() {} public void setName (String nam) { } public void setAddress (String add) { } public void setPhone (String ph) { } public String getName () { } public String getAddress () { } public String getPhone () { } return (this.phone); return (this.address); return (this.name); this.phone=ph; this.address=add; this.name=nam;

} Retrieve.jsp <html> <body> <jsp:useBean id=myaddbook scope=session class=test.AddressBook/> <jsp:setProperty name=myaddbook property=*/> <table cellspacing = 1 cellpadding = 1 border =1 align = center> <tr><td colspan=2 align=center>Personal Information</td> 25

Web Technologies

www.lectnote.blogspot.com

<tr><td align = middle>Name : </td> <td align = center > </tr> <tr> <td align = middle>Name : </td> <td align = center ><% =myaddbook.getAddress() %></td> </tr> <tr> <td align = middle>Name : </td> <td align = center ><% =myaddbook.getPhone() %></td> </tr> </table> </body> </html> <% =myaddbook.getName() %></td>

The output is Put .html file and .jsp file in webapps/examples folder Put the package (including .java file and .class) in webapps/examples/WEB-INF/classes folder

Personal Information Name : Address : Phone : Thomas pala 239301

EXCEPTION HANDLING 26

Web Technologies

www.lectnote.blogspot.com

An exception is an event that occurs during the execution of a program and it disrupts the normal working of the instructions in the program .Java uses a class known as Exception class. Interpreter creates an object of this class when an exception occurs. Types of errors System Error Application Error Syntax Error Logical Error

You can catch exceptions in a JSP page like you would do in other Java classes. Simply put the code which can throw an exception/s between a try..catch block.

<% try { // Code which can throw can exception } catch(Exception e) { // Exception handler code here } %>

There is yet another useful way of catching exceptions in JSP pages. You can specify error page in the 'page' directive. Then if any exception is thrown, the control will be transferred to that error page where you can display a useful message to the user about what happened. Throws Whenever an error occurs in a function,an exception object is created and throws an exception. Exception handling is done within the calling method.

27

Web Technologies

www.lectnote.blogspot.com

Eg:

public void sum () throws Exception { } Catch(Exception e){. } try{ object.sum();

Here when an exception occurs then the exception object is created and thrown to the corresponding method. Throw: It is used to create our own exceptions. Public void sum ( int a , int b) { if(a == 0 && b==0) Exception e = new Exception() Throw e; } Example: Username Password
Submit

<html> 28

Web Technologies

www.lectnote.blogspot.com

<body> <table width="346" border="1"> <tr> <td width="164">Username</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>Password</td> <td><input type="text" name="password" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit" /></td> </tr> </table> </body></html> User.java public class user { private string username, password; public void setusername (String s) { } Public void setpassword (String p) { } 29 this. password=p; this. username=s;

Web Technologies

www.lectnote.blogspot.com

public string getusername () { } public String getpassword () { r eturn (this. password); } public void validate () {if (! (this. username==java)&&(this. password=jsp)) {Exception e = new Exception (Couldnt validate); Throw e; }} a.jsp <html> <body> <jsp: useBean id=myuser class =user/> <jsp: setProperty Name=myuser property=*/> try {myuser.validate (); 30 return (this. username);

Web Technologies

www.lectnote.blogspot.com

out.println (welcome+ myuser. getUserName ()); } catch (Exception e) { out.println (An exception occurred+e.toString ()); } </body> </html>

Error pages in JSP For different jsp pages there are different possible types of errors. errors centrally we make use of error pages. 2 steps to create a java error page 1. Create an error page A sample jsp page named error.jsp < % @ page isErrorpage = true %> Jsp container will create an implicit exception object for it. 2. Create jsp page < % @ page errorpage=error.jsp %> In the below example we are going to handle the run- time exception. To make a program on this we are using three pages. 31 Inorder to handle these

Web Technologies

www.lectnote.blogspot.com

An Html Form: It is used to display a form to the user where he will enter the first and second number. Controller class: This class is a jsp page which receives the values entered by the user and prints it on the user screen. If any exceptions exception occurs then it will forward it other page which will handle the exception. Exceptional Handler: This jsp page is actually an error page to which the control will be passed by the controller when the exception is thrown.

Code of the program is given below: <html> <head> <style> body, input { font-family: Tahoma; font-size:8pt; } </style> </head> <body> <table align="center" border=1> <form action="formHandler.jsp" method="post"> <tr><td>Enter your first Number: </td> <td><input type="text" name="fno" /></td></tr> <tr><td>Enter your Second Number: </td> <td><input type="text" name="sno" /></td></tr> <tr ><td colspan="2"><input type="submit" value="Submit" /></td></tr> </form> </table> </body> </html>

32

Web Technologies

www.lectnote.blogspot.com

<%@ page errorPage="exceptionHandler.jsp" %> <html> <head> <style> body, p { font-family:Tahoma; font-size:10pt; } </style> </head> <body> <% int fno; int sno; fno = Integer.parseInt(request.getParameter("fno")); sno = Integer.parseInt(request.getParameter("sno"));

int div=fno/sno; %> <p>Division is : <%= div %></p> <p><a href="form.html">Back</a>.</p> </body> </html>

33

Web Technologies

www.lectnote.blogspot.com

<%@ page isErrorPage="true" import="java.io.*" %> <html> <head> <title>Exceptional Even Occurred!</title> <style> body, p { font-family:Tahoma; font-size:10pt;padding-left:30; } pre { font-size:8pt; } </style> </head><body> <%-- Exception Handler --%> <font color="red"> <%= exception.toString() %><br> </font><% out.println("<!--"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); out.print(sw); sw.close(); pw.close(); out.println("-->"); %> </body> </html> Output of the program:

34

Web Technologies

www.lectnote.blogspot.com

35

Web Technologies

www.lectnote.blogspot.com

36

Você também pode gostar