SlideShare une entreprise Scribd logo
1  sur  23
Télécharger pour lire hors ligne
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&nbsp;
      <p>&nbsp;</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
<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
%>
   </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
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
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
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
public String toString() {
      return getTitle();
    }

    public String getType() {
      return "TECHNICAL";
    }

    public TechnicalBook() {
      super();
    }

    public TechnicalBook(String title) {
      super(title);
    }

}




                                           9
EJEMPLO 3

Desarrollar un script en JSP que permita enviar datos y guardarlos en archivo.




SOLUCIÓN

DatosBean.htm

    <html>
    <head>



                                                                                 10
<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
<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
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
<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
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
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>&nbsp;</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
</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>&nbsp;</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
<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>&nbsp;</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
<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
<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>&nbsp;</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
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>&nbsp;</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
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
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
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
}

    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

Contenu connexe

Tendances

Test du futur avec Spock
Test du futur avec SpockTest du futur avec Spock
Test du futur avec SpockCARA_Lyon
 
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드영욱 김
 
Rails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power StackRails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power StackDavid Copeland
 
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
The Ring programming language version 1.9 book - Part 52 of 210
The Ring programming language version 1.9 book - Part 52 of 210The Ring programming language version 1.9 book - Part 52 of 210
The Ring programming language version 1.9 book - Part 52 of 210Mahmoud Samir Fayed
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConqeTimeline, LLC
 
Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]automician
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
FYBSC IT Web Programming Unit III Core Javascript
FYBSC IT Web Programming Unit III  Core JavascriptFYBSC IT Web Programming Unit III  Core Javascript
FYBSC IT Web Programming Unit III Core JavascriptArti Parab Academics
 

Tendances (17)

Test du futur avec Spock
Test du futur avec SpockTest du futur avec Spock
Test du futur avec Spock
 
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
 
Rails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power StackRails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power Stack
 
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
The Ring programming language version 1.9 book - Part 52 of 210
The Ring programming language version 1.9 book - Part 52 of 210The Ring programming language version 1.9 book - Part 52 of 210
The Ring programming language version 1.9 book - Part 52 of 210
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConq
 
Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]
 
JavaScript
JavaScriptJavaScript
JavaScript
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
前端概述
前端概述前端概述
前端概述
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
FYBSC IT Web Programming Unit III Core Javascript
FYBSC IT Web Programming Unit III  Core JavascriptFYBSC IT Web Programming Unit III  Core Javascript
FYBSC IT Web Programming Unit III Core Javascript
 

En vedette

Question Four
Question Four Question Four
Question Four Tyrrell
 
Creative minds assignment 1 getting to know you
Creative minds assignment 1   getting to know youCreative minds assignment 1   getting to know you
Creative minds assignment 1 getting to know youAnni Rautio
 
AT - How did you use media technologies?
AT - How did you use media technologies?AT - How did you use media technologies?
AT - How did you use media technologies?nctcmedia12
 
‘Build First Plan Later’: The Voice of DIY Approaches in Today’s Design
‘Build First Plan Later’: The Voice of DIY Approaches in Today’s Design‘Build First Plan Later’: The Voice of DIY Approaches in Today’s Design
‘Build First Plan Later’: The Voice of DIY Approaches in Today’s DesignRavihansa Rajapakse
 
Свеча зажигания NGK
Свеча зажигания NGKСвеча зажигания NGK
Свеча зажигания NGKAl Maks
 
Gheorghe magheru school students
Gheorghe magheru school  studentsGheorghe magheru school  students
Gheorghe magheru school studentsGrigore Gheorghita
 
My evaluation question twoo
My evaluation   question twooMy evaluation   question twoo
My evaluation question twooTyrrell
 
Facemark web-banners price-list
Facemark web-banners price-listFacemark web-banners price-list
Facemark web-banners price-listRafig Valiyev
 
Target audience analyse PR
Target audience analyse PRTarget audience analyse PR
Target audience analyse PRnctcmedia12
 
Layout and drafting
Layout and draftingLayout and drafting
Layout and draftingnctcmedia12
 
Напольный газовый котел Protherm Волк 16 KSO
Напольный газовый котел Protherm Волк 16 KSOНапольный газовый котел Protherm Волк 16 KSO
Напольный газовый котел Protherm Волк 16 KSOAl Maks
 
Теплица Новатор Премиум
Теплица Новатор ПремиумТеплица Новатор Премиум
Теплица Новатор ПремиумAl Maks
 

En vedette (20)

Question Four
Question Four Question Four
Question Four
 
Creative minds assignment 1 getting to know you
Creative minds assignment 1   getting to know youCreative minds assignment 1   getting to know you
Creative minds assignment 1 getting to know you
 
AT - How did you use media technologies?
AT - How did you use media technologies?AT - How did you use media technologies?
AT - How did you use media technologies?
 
Feng shui bathroom
Feng shui bathroomFeng shui bathroom
Feng shui bathroom
 
‘Build First Plan Later’: The Voice of DIY Approaches in Today’s Design
‘Build First Plan Later’: The Voice of DIY Approaches in Today’s Design‘Build First Plan Later’: The Voice of DIY Approaches in Today’s Design
‘Build First Plan Later’: The Voice of DIY Approaches in Today’s Design
 
Свеча зажигания NGK
Свеча зажигания NGKСвеча зажигания NGK
Свеча зажигания NGK
 
Multiculture and communication
Multiculture and communicationMulticulture and communication
Multiculture and communication
 
Gheorghe magheru school students
Gheorghe magheru school  studentsGheorghe magheru school  students
Gheorghe magheru school students
 
Power point comunicacion
Power point comunicacionPower point comunicacion
Power point comunicacion
 
презентация Microsoft office power point
презентация Microsoft office power pointпрезентация Microsoft office power point
презентация Microsoft office power point
 
20120429取彗小組
20120429取彗小組20120429取彗小組
20120429取彗小組
 
Risk assessment
Risk assessmentRisk assessment
Risk assessment
 
My evaluation question twoo
My evaluation   question twooMy evaluation   question twoo
My evaluation question twoo
 
Facemark web-banners price-list
Facemark web-banners price-listFacemark web-banners price-list
Facemark web-banners price-list
 
Bundle presentation
Bundle presentationBundle presentation
Bundle presentation
 
Target audience analyse PR
Target audience analyse PRTarget audience analyse PR
Target audience analyse PR
 
Edgar allan poe
Edgar allan poeEdgar allan poe
Edgar allan poe
 
Layout and drafting
Layout and draftingLayout and drafting
Layout and drafting
 
Напольный газовый котел Protherm Волк 16 KSO
Напольный газовый котел Protherm Волк 16 KSOНапольный газовый котел Protherm Волк 16 KSO
Напольный газовый котел Protherm Волк 16 KSO
 
Теплица Новатор Премиум
Теплица Новатор ПремиумТеплица Новатор Премиум
Теплица Новатор Премиум
 

Similaire à Practica n° 7

Experience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsExperience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsCédric Hüsler
 
Bca sem 6 php practicals 1to12
Bca sem 6 php practicals 1to12Bca sem 6 php practicals 1to12
Bca sem 6 php practicals 1to12Hitesh Patel
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Creating web api and consuming part 2
Creating web api and consuming part 2Creating web api and consuming part 2
Creating web api and consuming part 2Dipendra Shekhawat
 
20190118_NetadashiMeetup#8_React2019
20190118_NetadashiMeetup#8_React201920190118_NetadashiMeetup#8_React2019
20190118_NetadashiMeetup#8_React2019Makoto Mori
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4Heather Rock
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkara JUG
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4DEVCON
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and ImprovedTimothy Fisher
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 

Similaire à Practica n° 7 (20)

Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
 
Experience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsExperience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - Highlights
 
Bca sem 6 php practicals 1to12
Bca sem 6 php practicals 1to12Bca sem 6 php practicals 1to12
Bca sem 6 php practicals 1to12
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Creating web api and consuming part 2
Creating web api and consuming part 2Creating web api and consuming part 2
Creating web api and consuming part 2
 
20190118_NetadashiMeetup#8_React2019
20190118_NetadashiMeetup#8_React201920190118_NetadashiMeetup#8_React2019
20190118_NetadashiMeetup#8_React2019
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
1cst
1cst1cst
1cst
 
Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
JavaServer Pages
JavaServer PagesJavaServer Pages
JavaServer Pages
 
Java Script
Java ScriptJava Script
Java Script
 
JSP
JSPJSP
JSP
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFaces
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and Improved
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
2190 pertemuan24(polling)
2190 pertemuan24(polling)2190 pertemuan24(polling)
2190 pertemuan24(polling)
 

Dernier

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Dernier (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Practica n° 7

  • 1. 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&nbsp; <p>&nbsp;</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>&nbsp;</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>&nbsp;</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>&nbsp;</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>&nbsp;</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>&nbsp;</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