Contenu connexe Similaire à Practica n° 7 Similaire à Practica n° 7 (20) Practica n° 71. ACTIVIDADES
Ejecutar y analizar la solución de cada uno de los ejemplos.
EJEMPLO 1
Desarrollar un script en JSP .
SOLUCIÓN
arrayexample3.jsp
<html>
<head>
<title>Chapter 5 Examples</title>
</head>
<body>
Simple Catalog Browsing Example
<p> </p>
<form method="POST" action="arrayexample3handler.jsp">
<table border="0" cellpadding="0" cellspacing="0" width="439">
<tr>
<td width="157"><b>Browse Catalog</b></td>
<td width="128"></td>
<td width="148"></td>
</tr>
<tr>
<td width="157" bgcolor="#C0C0C0">
<font color="#FFFFFF">Product</font>
</td>
<td width="128" bgcolor="#C0C0C0">
<font color="#FFFFFF">ListPrice</font>
</td>
<td width="148" bgcolor="#C0C0C0">
<font color="#FFFFFF">Select</font>
</td>
</tr>
<tr>
<td width="157">Wrox Press Beginning JSP</td>
<td width="128">$49.99</td>
<td width="148">
<input type="checkbox" name="productid" value="1" />
</td>
</tr>
<tr>
<td width="157">Wrox Press Professional JSP</td>
<td width="128">$59.99</td>
<td width="148">
<input type="checkbox" name="productid" value="2" />
</td>
</tr>
3
2. <tr>
<td width="157">Wrox Press Beginning Java</td>
<td width="128">$39.99</td>
<td width="148">
<input type="checkbox" name="productid" value="3" />
</td>
</tr>
</table>
<p>
<input type="submit"
value="Add To Shopping Cart" name="AddToShoppingCartBtn" />
</p>
</form>
</body>
</html>
arrayexample3handler.jsp
<%@ page info="Array Example 3"%>
<%@ page import="com.wrox.begjsp.arrayexample3.ProductManager"%>
<%@ page import="com.wrox.begjsp.arrayexample3.Product"%>
<html>
<head>
<title>Chapter 5 Examples</title>
</head>
<body>
<b>Array Example 3 ( Response ) </b><br /><br />
<jsp:useBean id="pm"
class="com.wrox.begjsp.arrayexample3.ProductManager"
scope="session">
</jsp:useBean>
<%
String[] selProducts = request.getParameterValues("productid");
int selProductsCount = 0;
if (selProducts == null) {
out.println("You did not select any products");
} else {
selProductsCount = selProducts.length;
out.println("Your Shopping Cart now has :" +"<BR>");
for(int i=0;i<selProductsCount;i++) {
int ProductId = Integer.parseInt(selProducts[i]);
Product prod = pm.getProductDetails(ProductId);
out.println(prod.getProductName());
out.println(prod.getProductPrice());
out.println("<BR>");
}
}
4
3. %>
</body>
</html>
Product.java
package com.wrox.begjsp.arrayexample3;
public class Product {
private int productId;
private String productName;
private double productPrice;
public Product(int prodid, String prodname, double prodprice) {
productId = prodid;
productName = prodname;
productPrice = prodprice;
}
public int getProductId(){
return productId;
}
public void setProductId(int ProductId){
this.productId = ProductId;
}
public String getProductName(){
return productName;
}
public void setProductName(String ProductName){
this.productName = ProductName;
}
public double getProductPrice(){ return productPrice; }
public void setProductPrice(double productPrice){
this.productPrice = productPrice;
}
}
ProductManager.java
package com.wrox.begjsp.arrayexample3;
public class ProductManager {
private Product[] productList = new Product[3];
private int productCount;
public ProductManager() {
5
4. initializeProductList();
}
private void initializeProductList() {
productList[0] = new Product(1,"Wrox Press Beginning JSP",49.99);
productList[1] = new Product(2,"Wrox Press Professional JSP",59.99);
productList[2] = new Product(3,"Wrox Press Beginning Java",39.99);
}
public Product[] getProductList(){
return productList;
}
public int getProductCount(){
return productList.length;
}
public Product getProductDetails(int prodid) {
int ProductIndex = -1;
for(int i=0;i<this.getProductCount();i++) {
if (prodid == productList[i].getProductId()) {
ProductIndex = i;
break;
}
}
if (ProductIndex != -1) {
return productList[ProductIndex];
} else {
return null;
}
}
}
6
5. EJEMPLO 2
Desarrollar un script en JSP.
SOLUCIÓN
bookPage4.jsp
<%@ page import="com.wrox.library.*" %>
<html>
<head>
<title>Inheritance</title>
</head>
<body>
<%
Book techBook = new TechnicalBook("Car Mechanics");
Book childBook = new ChildrenBook("The Three Bears");
%>
TechnicalBook Type: <%= techBook.getType() %>
<br />
ChildrenBook Type: <%= childBook.getType() %>
<%
TechnicalBook techBook = new TechnicalBook("Car Mechanics");
ChildrenBook childBook = new ChildrenBook("The Three Bears");
%>
TechnicalBook toString(): <%= techBook.toString() %>
<br />
ChildrenBook toString(): <%= childBook.toString() %>
</body>
</html>
Book.java
package com.wrox.library;
public class Book {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Book() {
}
7
6. public Book(String title) {
this.title = title;
}
}
ChildrenBook.java
package com.wrox.library;
public class ChildrenBook extends Book {
private int minimumAge;
public int getMinimumAge() {
return minimumAge;
}
public void setMinimumAge(int a) {
minimumAge = a;
}
public String getType() {
return "CHILDREN";
}
public ChildrenBook() {
super();
}
public ChildrenBook(String title) {
super(title);
}
}
TechnicalBook.java
package com.wrox.library;
public class TechnicalBook extends Book {
private String skillLevel;
public String getSkillLevel() {
return skillLevel;
}
public void setSkillLevel(String s) {
skillLevel = s;
}
8
7. public String toString() {
return getTitle();
}
public String getType() {
return "TECHNICAL";
}
public TechnicalBook() {
super();
}
public TechnicalBook(String title) {
super(title);
}
}
9
8. EJEMPLO 3
Desarrollar un script en JSP que permita enviar datos y guardarlos en archivo.
SOLUCIÓN
DatosBean.htm
<html>
<head>
10
9. <title>Juan Perez JSP, Comentarios</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="generator" content="htm4l version 2.00">
<meta name="autor" content="Juan Perez">
<meta name="copyright" content="(c) 2004">
<meta name="creacion" content="07-jul-2004 18:28:31">
<meta name="modificacion" content="07-jul-2004 18:28:31">
</head>
<body>
<h2>JSP, encuesta</h2>
<center>
<form method="post" action="EncuestaBean.jsp" name="">
<br>
<table border=0 cols=5 width="80%" >
<tr><td align="left">
<font face="Arial,Helvetica" size="-1" color="#000099">
<b>Introduzca su nombre:</b>
<input type="text" name="usuario">
</td></tr>
<tr><td align="center">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr bgcolor="#999999"><td bgcolor="#003399">
<table width="100%" border="0" cellspacing="1" cellpadding="2">
<tr bgcolor="#FFFFFF"><td nowrap>
<table width="100%" border="0" cellspacing="1" cellpadding="1" align="center">
<tr><td nowrap valign="top">
<font face="Arial,Helvetica" size="-1" color="#000099">
<b>Indique su sexo:</b></font><br>
<font face="Verdana,Helvetica" size="-1" color="#000099">
<input type="radio" name="genero" value="Femenino" checked>Mujer<br>
<input type="radio" name="genero" value="Masculino">Hombre<br>
</font></td>
<td nowrap valign="top">
<font face="Arial,Helvetica" size="-1" color="#000099">
<b>Seleccione su vehículo de preferencia:</b></font><br>
<table width="100%" border="0" cellspacing="1" cellpadding="2">
<tr bgcolor="#FFFFFF"><td nowrap>
<font face="Verdana,Helvetica" size="-1" color="#000099">
Moto:</font></td><td>
<font face="Verdana,Helvetica" size="-1" color="#000099">
<select name="moto">
<option value="Ninguna">Ninguna</option>
<option value="Yamaha">Yamaha</option>
<option value="Honda">Honda</option>
<option value="Derby">Derby</option>
<option value="Aprilia">Aprilia</option>
<option value="Ducati">Ducati</option>
<option value="Bultaco">Bultaco</option>
<option value="BMW">BMW</option>
<option value="Kawasaki">Kawasaki</option>
<option value="Suzuki">Suzuki</option><br>
</select></font></td></tr>
<tr bgcolor="#FFFFFF"><td nowrap>
<font face="Verdana,Helvetica" size="-1" color="#000099">
Automóvil:</font></td><td>
<font face="Verdana,Helvetica" size="-1" color="#000099">
<select name="coche">
<option value="Ninguno">Ninguno</option>
11
10. <option value="Mercedes">Mercedes</option>
<option value="Porsche">Porsche</option>
<option value="Ferrari">Ferrari</option>
<option value="RollsRoyce">RollsRoyce</option>
<option value="BMW">BMW</option>
<option value="Toyota">Toyota</option><br>
</select></font></td></tr>
</table>
</td></tr>
</table>
</td></tr>
</table>
</td></tr>
</table>
</td></tr>
</table>
<br><br>
<center>
<input type="submit" name="submit" value=" Aceptar ">
<input type="reset" name="reset" value=" Borrar ">
</center>
</form>
</center>
</body>
</html>
12
11. EncuestaBean.jsp
<html>
<head>
<title>Juan Perez JSP, Comentarios</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="generator" content="htm4l version 2.00">
<meta name="autor" content="Juan Perez">
<meta name="copyright" content="(c) 2004">
<meta name="creacion" content="07-jul-2004 18:28:31">
<meta name="modificacion" content="07-jul-2004 18:28:31">
</head>
<body>
<h3> Encuesta - revisión datos </h3>
<jsp:useBean id="vbean" scope="request" class="Beans.ClaseBean" />
<%-- Se utiliza las propiedades del JavaBean mapaeadas con
respecto a las entradas del formulario. Como los nombres son
coincidentes, se puede utilizar la máscara "*" --%>
<jsp:setProperty name="vbean" property="*" />
<% // Comprobamos que todos los datos han sido seleccionados
if(vbean.getUsuario() == null || vbean.getGenero() == null ||
vbean.getMoto() == null || vbean.getCoche() == null ) {
%>
<br>Hay opciones que no se han seleccionado y debe haber una<br>
selección en cada uno de ellos para completar la encuesta.<br>
Pulse aquí <a href="javascript:history.back()">volver</a> para realizar la selección.
<% } else {
String file = application.getRealPath("/datos");
%>
<jsp:setProperty name="vbean" property="fichero" value="<%= file %>" />
<% vbean.store(); %>
<font face="Verdana,Helvetica" size="-1" color="#000099">
Gracias <b><jsp:getProperty name="vbean" property="usuario" /></b>,
su selección ha sido recogida.<br> Los datos son:<br>
</font><br>
<table width="40%" border="0" cellspacing="1" cellpadding="0" align="center">
<tr><td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr bgcolor="#999999"><td bgcolor="#003399">
<table width="100%" border="0" cellspacing="1" cellpadding="2">
<tr bgcolor="#FFFFFF"><td nowrap>
<table width="100%" border="0" cellspacing="1" cellpadding="1" align="center">
<tr><td nowrap>
<font face="Verdana,Helvetica" size="-1" color="#000099">
Sexo:</font></td>
<td nowrap>
<font face="Verdana,Helvetica" size="-1" color="#990000">
<b><jsp:getProperty name="vbean" property="genero" /></b></font>
</td></tr>
<tr><td nowrap>
<font face="Verdana,Helvetica" size="-1" color="#000099">
Automóvil:</font></td>
<td nowrap>
<font face="Verdana,Helvetica" size="-1" color="#990000">
13
12. <b><jsp:getProperty name="vbean" property="coche" /></b></font>
</td></tr>
<tr><td nowrap>
<font face="Verdana,Helvetica" size="-1" color="#000099">
Moto:</font></td>
<td nowrap>
<font face="Verdana,Helvetica" size="-1" color="#990000">
<b><jsp:getProperty name="vbean" property="moto" /></b></font>
</td></tr>
</table>
</td></tr>
</table>
</td></tr>
</table>
</td></tr>
</table>
<% } %>
</body>
</html
ClaseBean.java
//
// ClaseBean.java
// Copyright (c) 2004, Juan Perez
// Todos los derechos reservados.
//
// No se asume ninguna responsabilidad por el uso o alteracion de este
// software.
//
// Compilador: javac 1.3.0, Java 2 SDK
// Autor: Juan Perez
// Creacion: 19-Ago-2004 04:33:09
// Revision:
//
//--------------------------------------------------------------------------
// Esta informacion no es necesariamente definitiva y esta sujeta a cambios
// que pueden ser incorporados en cualquier momento, sin avisar.
//--------------------------------------------------------------------------
/**
* JavaBean utilizado para mostrar la separación d ela parte lógica, de la
* parte de presentación de resultados de la encuesta.
* La página HTML es la encargada de recoger la información del formulario
* proporcionada por el usuario, que pasa el control a la página JSP, que
* utiliza este Bean para el almacenamiento de los datos de cada una de
* las propiedades del Bean y de guardarlos en disco, con el fichero de
* nombre igual al del usuario.
*/
package Beans;
import java.io.*;
import java.util.Properties;
public class ClaseBean {
private String usuario;
private String genero;
private String coche;
private String moto;
14
13. private String fichero;
// Métodos set() y get() correspondientes a las propiedades
// del JavaBean, que se corresponden con los datos de entrada que
// están presentes en el formulario de la página html
public String getUsuario() {
return( usuario );
}
public void setUsuario( String _usuario ) {
usuario = _usuario;
}
public String getGenero() {
return( genero );
}
public void setGenero( String _genero ) {
genero = _genero;
}
public String getCoche() {
return( coche );
}
public void setCoche( String _coche ) {
coche = _coche;
}
public String getMoto() {
return( moto );
}
public void setMoto( String _moto ) {
moto = _moto;
}
public String getFichero() {
return( fichero );
}
public void setFichero( String _fichero ) {
fichero = _fichero;
}
// Método que se encarga del almacenamiento del objeto Propiedades
// en fichero de disco
public void store() throws IOException {
Properties p = new Properties();
p.put( "usuario",usuario );
p.put( "genero",genero );
p.put( "coche",coche );
p.put( "moto",moto );
FileOutputStream fos = new FileOutputStream( fichero+"/"+usuario );
p.store( fos,"Encuesta de Vehículos, realizada a -- "+usuario );
fos.flush();
fos.close();
}
}
//------------------------------------------- Final del fichero ClaseBean.java
15
14. EJEMPLO 4
Desarrollar un script en JSP.
SOLUCIÓN
Counter.jsp
<%@page contentType="text/html"%>
<html>
<head><title>Counter</title></head>
<body>
<jsp:useBean id="counter" scope="page"
class="com.wrox.counter.CounterBean"/>
<p>The current date is
<jsp:getProperty name="counter" property="todaysDate"/></p>
<p><jsp:getProperty name="counter" property="message"/></p>
</body>
</html>
getphonelist.jsp
<%@ page import="java.util.*" %>
<%@ page import="com.wrox.begjsp.Phone.EmployeePhone" %>
<%@ page import="com.wrox.begjsp.Phone.PhoneManager" %>
<html>
<head>
<title>Chapter 5 Examples</title>
</head>
<body>
<h3><b>EMPLOYEE PHONE LIST</b></h3>
<p> </p>
<jsp:useBean id="PhoneMgr"
class="com.wrox.begjsp.Phone.PhoneManager">
</jsp:useBean>
<table border="0" cellpadding="0" cellspacing="0" width="439">
<tr>
<td width="157"></td>
<td width="128"></td>
<td width="148"></td>
</tr>
<tr>
<td width="157" bgcolor="#C0C0C0">
<font color="#FFFFFF">EmployeeId</font>
Mgter. Juan Pablo Apaza Condori. 17
15. </td>
<td width="128" bgcolor="#C0C0C0">
<font color="#FFFFFF">EmployeeName</font>
</td>
<td width="148" bgcolor="#C0C0C0">
<font color="#FFFFFF">PhoneNo</font>
</td>
</tr>
<%
Enumeration phoneListEnum = PhoneMgr.getPhoneList();
while (phoneListEnum.hasMoreElements()) {
EmployeePhone empphone = (EmployeePhone)phoneListEnum.nextElement();
%>
<tr>
<td width="157"><%=empphone.getEmployeeId()%></td>
<td width="128"><%=empphone.getEmployeeName()%></td>
<td width="148"><%=empphone.getPhoneNumber()%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
getsortedphonelist.jsp
<%@ page import="java.util.*" %>
<%@ page import="com.wrox.begjsp.Phone.EmployeePhone" %>
<%@ page import="com.wrox.begjsp.Phone.PhoneManager" %>
<html>
<head>
<title>Chapter 5 Examples</title>
</head>
<body>
<h3><b>EMPLOYEE PHONE LIST</b></h3>
<p> </p>
<jsp:useBean id="PhoneMgr"
class="com.wrox.begjsp.Phone.PhoneManager" >
</jsp:useBean>
<table border="0" cellpadding="0" cellspacing="0" width="439">
<tr>
<td width="157"></td>
18
16. <td width="128"></td>
<td width="148"></td>
</tr>
<tr>
<td width="157" bgcolor="#C0C0C0">
<font color="#FFFFFF">EmployeeId</font>
</td>
<td width="128" bgcolor="#C0C0C0">
<font color="#FFFFFF">EmployeeName</font>
</td>
<td width="148" bgcolor="#C0C0C0">
<font color="#FFFFFF">PhoneNo</font>
</td>
</tr>
<%
PhoneMgr.sortPhoneList();
Enumeration phoneListEnum = PhoneMgr.getPhoneList();
while (phoneListEnum.hasMoreElements()) {
EmployeePhone empphone =
(EmployeePhone)phoneListEnum.nextElement();
%>
<tr>
<td width="157"><%=empphone.getEmployeeId()%></td>
<td width="128"><%=empphone.getEmployeeName()%></td>
<td width="148"><%=empphone.getPhoneNumber()%></td>
</tr>
<%
}
%>
</table>
<p> </p>
</form>
</body>
</html>
login.jsp
<html>
<body>
<form method="POST" action="loginhandler.jsp">
<div align="right">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td width="100%">Login Screen</td>
</tr>
</table>
<hr>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td width="100%" colspan="2"></td>
</tr>
<tr>
19
17. <td width="10%">UserName</td>
<td width="90%">
<input type="text" name="username" size="20">
</td>
</tr>
<tr>
<td width="10%">Password</td>
<td width="90%">
<input type="password" name="password" size="20">
</td>
</tr>
<tr>
<td width="10%"></td>
<td width="90%"></td>
</tr>
</table>
</div>
<p>
<input type="submit" value="Login" name="LoginBtn">
<input type="reset" value="Reset" name="B2">
</p>
</form>
</body>
</html>
loginhandler.jsp
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if ((username.equalsIgnoreCase("wrox")) &&
(password.equalsIgnoreCase("wrox"))) {
out.println("<H3>MAIN MENU</H3>");
out.println("<A href=getphonelist.jsp>Get Employee Phone No. List</a>"
+ "<BR>");
out.println("<A href=getsortedphonelist.jsp>"
+ "Get Sorted Phone No. List (Sorted by EmployeeName)</a>"
+ "<BR>");
out.println("<A href=search.jsp>Search for Phone No. List</a>"
+ "<BR>");
} else {
out.println("UserName/Password combination is incorrect !!!");
out.println("<a href=login.jsp>Try Again</a>");
}
%>
search.jsp
<html>
<head>
<title>Chapter 5 Examples</title>
</head>
20
18. <body>
<h3>Search Form</h3>
<br />
<form method="POST" action="searchresults.jsp">
<table border="0" cellpadding="0" cellspacing="0" width="439">
<tr>
<td width="433" colspan="2">
<b>
Look up for Employee
( Enter one of the following criteria)
</b>
</td>
</tr>
<tr>
<td width="157">Employee Id</td>
<td width="276"><input type="text" name="empid" size="21"></td>
</tr>
<tr>
<td width="157">Employee Name</td>
<td width="276"><input type="text" name="empname" size="21"></td>
</tr>
</table>
<p><input type="submit" value="Search ..." name="SearchBtn"></p>
</form>
</body>
</html>
searchresults.jsp
<%@ page import="java.util.*" %>
<%@ page import="com.wrox.begjsp.Phone.EmployeePhone" %>
<%@ page import="com.wrox.begjsp.Phone.PhoneManager" %>
<html>
<head>
<title>Chapter 5 Examples</title>
</head>
<body>
<h3><b>EMPLOYEE PHONE LIST - SEARCH RESULTS</b></h3>
<p> </p>
<jsp:useBean id="PhoneMgr" class="com.wrox.begjsp.Phone.PhoneManager" >
</jsp:useBean>
<table>
<%
Enumeration phoneListEnum = null;
String strempid = request.getParameter("empid");
if ((strempid != null) && (!strempid.equals(""))) {
21
19. phoneListEnum =
PhoneMgr.searchPhoneList(Integer.parseInt(strempid));
} else {
String empname = request.getParameter("empname");
phoneListEnum = PhoneMgr.searchPhoneList(empname);
}
while (phoneListEnum.hasMoreElements()) {
EmployeePhone empphone =
(EmployeePhone)phoneListEnum.nextElement();
%>
<tr>
<td width="157"><%=empphone.getEmployeeId()%></td>
<td width="128"><%=empphone.getEmployeeName()%></td>
<td width="148"><%=empphone.getPhoneNumber()%></td>
</tr>
<%
}
%>
</table>
<p> </p>
<p></p>
</body>
</html>
CounterBean.java
package com.wrox.counter;
import java.util.*;
import java.text.SimpleDateFormat;
public class CounterBean {
private Date curDate;
private SimpleDateFormat dateFormat;
private GregorianCalendar targetDate;
private String name;
public CounterBean() {
GregorianCalendar currentDate = new GregorianCalendar();
curDate = (Date) currentDate.getTime();
dateFormat = new SimpleDateFormat("EEE, dd MMMM yyyy");
targetDate = new GregorianCalendar();
targetDate.set(targetDate.YEAR, 3000);
targetDate.set(targetDate.MONTH, 0);
targetDate.set(targetDate.DATE, 1);
targetDate.set(targetDate.AM_PM, 0);
targetDate.set(targetDate.HOUR, 0);
targetDate.set(targetDate.MINUTE, 0);
targetDate.set(targetDate.SECOND, 0);
22
20. name = "the new millennium";
}
public String getTodaysDate() {
return dateFormat.format(curDate);
}
public void setTargetYear(int year) {
targetDate.set(targetDate.YEAR, year);
}
public void setTargetMonth(int month) {
targetDate.set(targetDate.MONTH, month);
}
public void setTargetDate(int date) {
targetDate.set(targetDate.DATE, date);
}
public void setTargetAmPm(int ampm) {
targetDate.set(targetDate.AM_PM, ampm);
}
public void setTargetHour(int hour) {
targetDate.set(targetDate.HOUR, hour);
}
public void setTargetMinute(int minute) {
targetDate.set(targetDate.MINUTE, minute);
}
public void setTargetSecond(int second) {
targetDate.set(targetDate.SECOND, second);
}
public void setTargetEvent(String eventName) {
name = eventName;
}
public String getTargetEvent() {
return name;
}
public String getMessage() {
Date millDate = (Date) targetDate.getTime();
int dateTest = millDate.compareTo(curDate);
switch(dateTest) {
case 1:
long millisecs = (millDate.getTime()) - (curDate.getTime());
long msInDay = (1000*60*60*24);
long daysToGo = (long) (millisecs/msInDay);
return("Only " + daysToGo + " days to go until " + name + "!!!");
case 0:
23
21. return("Welcome to the new Millenium!!!");
case -1:
return("Sorry, counter has expired");
default:
return("Counter error");
}
}
}
EmployeePhone.java
package com.wrox.begjsp.Phone;
public class EmployeePhone implements Comparable {
int employeeId;
String employeeName;
String phoneNumber;
public EmployeePhone(int empid, String empname, String phonenum) {
this.employeeId = empid;
this.employeeName = empname;
this.phoneNumber = phonenum;
}
public int hashCode(){
return 17*employeeId;
}
public boolean equals(Object obj) {
if (!(obj instanceof EmployeePhone)) return false;
EmployeePhone emp = (EmployeePhone)obj;
if (emp.getEmployeeId() == this.employeeId) {
return true;
} else {
return false;
}
}
public int compareTo(Object obj) {
EmployeePhone emp = (EmployeePhone)obj;
if ((this.employeeName.compareTo(emp.getEmployeeName())) > 0) {
return 1;
} else {
return -1;
}
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int empid) {
this.employeeId = empid;
}
24
22. public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String empname) {
this.employeeName = empname;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setEmployeeId(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
PhoneManager.java
package com.wrox.begjsp.Phone;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Collections;
public class PhoneManager {
private Vector phoneList = new Vector();
public PhoneManager() {
initializePhoneList();
}
private void initializePhoneList() {
EmployeePhone phone1 = new EmployeePhone(1,"Prashant","510-123-4567");
EmployeePhone phone2 = new EmployeePhone(2,"Archit","510-123-4580");
EmployeePhone phone3 = new EmployeePhone(3,"Ashish","510-123-3333");
phoneList.add(phone1);
phoneList.add(phone3);
phoneList.add(phone2);
}
public void sortPhoneList() {
Collections.sort(phoneList);
}
public Enumeration getPhoneList(){
return phoneList.elements();
25
23. }
public int getPhoneListCount(){
return phoneList.size();
}
public Enumeration searchPhoneList(String empnamelike) {
Vector resultList = new Vector();
Enumeration phonelistenum = phoneList.elements();
while (phonelistenum.hasMoreElements()) {
EmployeePhone empphone = (EmployeePhone)phonelistenum.nextElement();
String empname = empphone.getEmployeeName();
if (empname.indexOf(empnamelike) != -1) {
resultList.add(empphone);
}
}
return resultList.elements();
}
public Enumeration searchPhoneList(int empid) {
int PhoneIndex = -1;
Vector resultList = new Vector();
Enumeration phonelistenum = phoneList.elements();
while (phonelistenum.hasMoreElements()) {
EmployeePhone empphone = (EmployeePhone)phonelistenum.nextElement();
if (empphone.getEmployeeId() == empid) {
resultList.add(empphone);
break;
}
}
return resultList.elements();
}
}
26