Vous êtes sur la page 1sur 22

1

Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

UNA APLICACIÓN CON CAPAS EN JAVA WEB

La capa de
procesos que
interactúan con la
BDD y el servlet

Se proceden a colocar
todos los métodos
que se van a ejecutar
, como listados ,
generación de
2
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

Las Tablas que intervienen


Paginas que el proyecto creadas en ORACLE :
Servlet la capa Las entidades o
interactúan con donde recepcionaPASAJEROS Clases que
RUTA VIAJES
el cliente BOLNRO CHAR(6)
RUTCOD CHAR(4) NROVIA CHAR(6)y envía intervienen en su
NROVIA CHAR(6)proyecto
RUTNOM VARC RUTCOD CHAR(4)
NOMPAS VARCHAR2(30)
HAR2(25) VIAFECH DATE
ASIENTO INTEGER
Las pantallas: VIAHRS DATE
PAGO NUMBER(8,1)
COSTO
NUMBER(6,1)
a) Debe mostrar una lista de rutas:
PagRuta.jsp
3
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

Descripción al seleccionar una ruta va llamar al servlet (SerVia donde se va pasar el código de ruta y nombre
que es necesario para listar todos los viajes destinados a esa ruta)

PagViaje.jsp
4
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

Al seleccionar un viaje va mostrar todos los pasajeros que se encuentran en ese viaje va llamar al
servlet(Serpasa) enviando como dato el numero de viaje y el costo ambos datos tienen que ser almacenados
en una sesión para que sean empleados en la pagina de adición de pasajeros observe que
request.getAttribute recupera el dato enviado por el servlet pero cuando pasa o llama a otra pagina pierde
su valor por lo tanto al emplear HttpSession ses=request.getSession() , se crea una sesión los valores
almacenados pueden ser llamados en cualquier parte o paginas del proyecto.
Pagpasa.jsp
5
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

b) Al hacer clic en adicionar pasajeros , va mostrar la siguiente pantalla para poder ingresar nuevos pasajeros,
observe que el numero de viaje y el costo tienen que ser recuperados en esta pagina , como esta en una
sesión entonces se puede recuperar.
Los datos viaje y costo además tienen que ser colocados en un campo oculto <input type=”Hidden”
name=”tvia”> para puedan ser enviados al servlet para grabación (SerGraba) una vez grabado se genera el
numero de boleto y dirige la pagina hacia Pagpasa(lista de pasajeros) para que el listado sea actualizado.
PagAdicion.jsp
6
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

Para el calculo del pago al seleccionar cualquier opción automáticamente va mostrar su pago , por lo tanto
tiene que emplear códigos en javascript , porque la operación es a nivel de cliente en el browser.

Entre a NetBeans y crear los siguientes paquetes: SYS.DAO, SYS.BEAN, SYS.SERVLET


7
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

System.out.print(ex.getMessage());
Descripción del código: }
En Conexión.java ( SYS.DAO) return cn;
package SYS.DAO; }
//PASANDO UNA INSTRUNCCION SQL QU DEVUELVA
import java.sql.*; LA TABLA
public static ResultSet Runqry(String
public class Conexion { sql)throws SQLException{
ResultSet rs=null;
public static Connection getConexion(){ PreparedStatement
//oracle st=getConexion().prepareStatement(sql);
rs=st.executeQuery();
String Driver="oracle.jdbc.driver.OracleDriver";
String URL="jdbc:oracle:thin:@localhost:1521:XE"; return rs;
String user="sistemas";
String password="sistemas"; }
//ejecutar una aplicacion para grabar o
//eleiminar
Connection cn=null; public static int Ejecutar(String sql)
try{ throws SQLException{
Class.forName(Driver); int res=0;
cn = DriverManager.getConnection(URL,user,password); Statement st =
getConexion().createStatement();
}catch(Exception ex){ res = st.executeUpdate(sql);
return res;
}

Las entidades :
8
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

Ruta.java Viaje.java

package SYS.DAO; package SYS.DAO;


public class Ruta {
private String codr=null; public class Viaje {
private String vianro=null;
private String nomr=null;
private String fecha=null;
public Ruta(String a, String b){ private String hora=null;
codr=a; nomr=b; private double costo=0;
} public Viaje(String a, String b,String c, double d){
vianro=a;
public String getCodr() { fecha=b;
return codr; hora=c;
} costo=d;
}
public void setCodr(String codr) {
this.codr = codr; public String getVianro() {
return vianro;
} }
public String getNomr() { public void setVianro(String vianro) {
return nomr; this.vianro = vianro;
} }

public void setNomr(String nomr) { public String getFecha() {


this.nomr = nomr; return fecha;
} }

public void setFecha(String fecha) {


}
this.fecha = fecha;
}

public String getHora() {


return hora;
}
}
9
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

La entidad Pasajeros: this.nompas = nompas;


package SYS.DAO; }

public class Pasajero { public String getTipo() {


private String boleto; return tipo;
private String via; }
private String nompas;
private int asiento; public void setTipo(String tipo) {
private String tipo; this.tipo = tipo;
private double pago; }

public String getBoleto() { public double getPago() {


return boleto; return pago;
} }

public void setBoleto(String boleto) { public void setPago(double pago) {


this.boleto = boleto; this.pago = pago;
} }

public String getVia() { public int getAsiento() {


return via; return asiento;
} }

public void setVia(String via) { public void setAsiento(int asiento) {


this.via = via; this.asiento = asiento;
} }

public String getNompas() { }


return nompas;
}

public void setNompas(String nompas) {

en el paquete SYS.BEANS Proceso.java


package SYS.BEANS;
10
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

import SYS.DAO.*;
import java.sql.*;
import java.util.*;
public class Proceso {
//lista de rutas
public List<Ruta> LisRut(){
List<Ruta> lista=new ArrayList();
String sql="Select rutcod, rutnom from ruta";
try{
ResultSet rs=Conexion.Runqry(sql);
while(rs.next()){
Ruta obj=new Ruta(rs.getString(1),rs.getString(2));
lista.add(obj);
}

}catch(Exception e){
e.printStackTrace();
}
return lista;

}
//lista de viajes pasando el codigo de ruta

public List<Viaje> Lisvia(String codr){


List<Viaje> lista=new ArrayList();
String sql="Select Vianro, Viafch, viahrs, cosvia from viaje where rutcod='"+codr+"'";
try{
ResultSet rs=Conexion.Runqry(sql);
while(rs.next()){
Viaje obj=new Viaje(rs.getString(1),
rs.getString(2).substring(0,10),
rs.getString(3).substring(11), rs.getDouble(4));
lista.add(obj);
}
11
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

}catch(Exception e){
e.printStackTrace();
}

return lista;

}
//lista de pasajeros respecto a un viaje
public List<Pasajero> LisPasa(String via){
List<Pasajero> lista=new ArrayList();
String sql="select bolnro, nom_pas,nro_Asi, tipo,pago from pasajeros where vianro='"+via+"'";
try{
ResultSet rs=Conexion.Runqry(sql);
while(rs.next()){
Pasajero obj=new Pasajero();
obj.setBoleto(rs.getString(1));
obj.setNompas(rs.getString(2));
obj.setAsiento(rs.getInt(3));
obj.setTipo(rs.getString(4));
obj.setPago(rs.getDouble(5));
lista.add(obj);
}

}catch(Exception e){
e.printStackTrace();
}
return lista;
}
//busca si un asiento esta ocupado o no
public boolean Ocupado(int asiento, String via){
boolean existe=false;
for(Pasajero x:LisPasa(via)){
if(asiento==x.getAsiento()){
existe=true;
12
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

break;
}
}
return existe;

public void Graba(Pasajero obj){ //para adicionar nuevos pasajeros al viaje seleccionado
String sql="insert into pasajeros values(?,?,?,?,?,?)";
try{
PreparedStatement st=Conexion.getConexion().prepareStatement(sql);
st.setString(1, obj.getBoleto());
st.setString(2,obj.getVia());
st.setString(3, obj.getNompas());
st.setInt(4, obj.getAsiento());
st.setString(5, obj.getTipo());
st.setDouble(6, obj.getPago());
st.executeUpdate();

}catch(SQLException e){
e.printStackTrace();
}

}
public String GenBoleto(){
String cad="";
//NVL PERMITE SABER SI UN VALOR ES NULO , SI LA TABLA ESTA VACIA NO HAY MAXIMO , POR LO TANTO EL
VALOR ES CERO
String sql="select NVL(MAX(BOLNRO),'0')+1 FROM PASAJEROS";
try{
ResultSet rs=Conexion.Runqry(sql);
rs.next();
int nro=rs.getInt(1);
java.text.DecimalFormat sd=new java.text.DecimalFormat("000000"); //para rellenar con ceros
a la izquierda
13
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

cad=sd.format(nro);
}catch(Exception e){
e.printStackTrace();
}
return cad;

}
//los servlet
SerVia
package SYS.SERVLET;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import SYS.DAO.*;
import SYS.BEANS.*;
public class SerVia extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String codr=request.getParameter("codr");
String nomr=request.getParameter("nomr");
String ruta="/Pagviaje.jsp";
Proceso obj=new Proceso();
request.setAttribute("lista",obj.Lisvia(codr) );
request.setAttribute("nomr", nomr);
request.setAttribute("codr", codr); //va redirigir hacia la pagina
this.getServletContext().getRequestDispatcher(ruta).forward(request, response);
}
}

Servlet de Pasajeros SerPas.java


package SYS.SERVLET;
14
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

import java.io.IOException;
import java.io.PrintWriter; Nota.- El método a emplear en el
import javax.servlet.ServletException; servlet es el doGet la razón es porque
import javax.servlet.http.HttpServlet; los datos son enviados por dirección de
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; pagina (<a href…) , en el
//para trabajar con sesiones processRequest no serán tomados en
import javax.servlet.http.HttpSession;
import SYS.BEANS.*; cuenta estos datos.

public class SerPas extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String viaje=request.getParameter("via");
String costo=request.getParameter("costo");
Proceso obj=new Proceso();
request.setAttribute("lispas",obj.LisPasa(viaje));
//crear una sesion para almacenar los datos
//para que sean utilizados en cualquier pagina
HttpSession ses=request.getSession();
ses.setAttribute("via", viaje);
ses.setAttribute("costo",costo );
String ruta="/Pagpasa.jsp";
this.getServletContext().
getRequestDispatcher(ruta).forward(request, response);
}

public String getServletInfo() {


return "Short description";
}// </editor-fold>

Servelt de grabacion serGraba.java


package SYS.SERVLET;
15
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

import SYS.BEANS.*;
import SYS.DAO.*;
public class SerGraba extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Proceso obj=new Proceso();
String nomp=request.getParameter("tnom");
String viaje=request.getParameter("tvia");
int asiento=Integer.parseInt(request.getParameter("cba"));
String tipo=request.getParameter("op");
String boleto=obj.GenBoleto();
double pago=Double.parseDouble(request.getParameter("tpago"));

Pasajero p=new Pasajero();


p.setBoleto(boleto);
p.setNompas(nomp);
p.setAsiento(asiento);
p.setVia(viaje);
p.setPago(pago);
p.setTipo(tipo);
obj.Graba(p);

String ruta="/Pagpasa.jsp";
//para enviar un listado actualizado
request.setAttribute("lispas", obj.LisPasa(viaje));
this.getServletContext().getRequestDispatcher(ruta).forward(request, response);
out.close();
16
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

}
}

En webpage las paginas que interactúan con el cliente:


La pagina de Cabecera.jsp que será incluida en todas las paginas que se va realizar , la
razón es de no estar diseñando lo mismo en cada página , por lo tanto será incluida en las
paginas.

Cabecera.jsp
<body background="turismo/FONDOTRI.GIF">
<table width="780" border="0" cellpadding="0" cellspacing="1">

<tr><td><img src="turismo/centro_cinta.png" height="10" width="700">


<tr><td><table>
<tr><td> <img src="turismo/promo_cuzco.jpg" height="200" width="300">
<td><img src="turismo/imagen2.gif" height="200" width="300">
<td><img src="turismo/promo_puno.jpg" height="200" width="300">
<tr>
<td bgcolor="#000000" align="center"><img src="images/spacer.gif" width="1" height="1"></td>
<tr align="center" bgcolor="#666666">
<td colspan="4" height="20"><font face="Verdana, Arial, Helvetica, sans-serif" size="1"
color="#F0F0F0">Administraci&oacute;n
Proyecto Agencia de Viajes 2009 LP2-UTP. Todos los derechos reservados. <a
href="mailto:moreno_1231@yahoo.es";><font
color="#E6E6E6">Cont&aacute;ctenos</font></a></font></td>
</tr>
</table>

Pagina donde se listan todas las rutas:


17
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

pagRuta.jsp
<%@page import="SYS.DAO.*,SYS.BEANS.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Rutas</title>
</head>
<body>
<%@include file="/Cabecera.jsp" %>
<center>
<table border="1">
<tr><th>Viajes<th>Nombre <th>Imagen
<%
Proceso obj=new Proceso();
for(Ruta x:obj.LisRut()){
%>
<tr><td><a href="SerVia?codr=<%=x.getCodr()%>&nomr=<%=x.getNomr()%>">Viajes</a>
<td><%=x.getNomr() %>
<td><img src="turismo/<%=x.getNomr()%>.jpg"
height="100" width="100">

<%}
%>
</table>
</center>
</body>
</html>

La pagina de Listas de viajes : PagViaje.jsp


18
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

<%@page import="SYS.DAO.*,SYS.BEANS.*,java.util.*" %>


<html>

<body>
<%@include file="/Cabecera.jsp" %>
<center>
<h1>Lista de Viajes</h1>
<%//recuperar valores enviados por servlet
String nom=(String)request.getAttribute("nomr");
List<Viaje> lisvia=
(ArrayList)request.getAttribute("lista");
%>
<img src="turismo/<%=nom %>.jpg" height="200"
width="200">
<table border="1">
<tr><td>Pasajeros <td>Fecha<td>Hora <td>Costo
<%for(Viaje x:lisvia){
%>
<tr><td><a href="SerPas?via=<%=x.getVianro()%>
&costo=<%=x.getCosto() %>"> <%=x.getVianro()%> </a>
<td><%=x.getFecha() %>
<td><%=x.getHora() %>
<td><%=x.getCosto() %>
<%}%>

</table>
</center>
</body>
</html>

Pagina de Listas de pasajeros: Pagpasa.jsp


19
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

<%@page import="SYS.DAO.*,SYS.BEANS.*,java.util.*" %>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Pasajeros</title>
</head>
<body>
<%@include file="/Cabecera.jsp" %>
<center>
<a href="PagAdicion.jsp">Adiciona Pasajeros</a>
<table border="1">
<tr><th>Boleto <td>Nombre <td>Asiento<td>Pago
<%
List<Pasajero> lista=
(ArrayList)request.getAttribute("lispas");
for(Pasajero x:lista){
%>
<tr><td><%=x.getBoleto() %>
<td><%=x.getNompas() %>
<td><%=x.getAsiento() %>
<td><%=x.getPago() %>

<%}
%>

</table>
</center>
</body>
</html>

La pagina de Ingreso de datos nuevos pasajeros: PagAdicion.jsp


20
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

El diseño realizarlo con macromedia, que es mas sencillo.

<%@page import="SYS.DAO.*,SYS.BEANS.*,java.util.*" %>


<head>
<title>Ingreso</title>
<style type="text/css">
<!--
.Estilo1 {
color: #0000FF;
font-weight: bold;
font-size: 24px;
}
-->
</style>
</head>
<body>
<%@include file="/Cabecera.jsp" %>
<% //recuperando valores de la session
HttpSession ses=request.getSession();
String viaje=(String)ses.getAttribute("via");
double costo=
Double.parseDouble((String)ses.getAttribute("costo"));
Proceso obj=new Proceso();
%>
<form id="form1" name="form1" method="post" action="SerGraba">
<table width="587" border="1">
<tr>
<td colspan="2" bgcolor="#FFFFFF"><div align="center"><span class="Estilo1">REGISTRO DE PASAJEROS
</span></div></td>
</tr>
<tr>
<td width="205">Nombre</td>
<td width="366"><label>
<input name="tnom" type="text" id="tnom" />
</label></td>
</tr>
<tr>
<td>Asiento</td>
21
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

<td><label>
<select name="cba" id="cba">
<%
for(int a=1; a<=40; a++){
if(!obj.Ocupado(a, viaje))//si no esta ocupado
out.print("<option>"+a);
}
%>

</select>
</label></td>
</tr>
<tr>
<td>Tipo</td>
<td><label>
<input name="op" type="radio" value="A" onclick="calculo(1)" />
Adulto
<input name="op" type="radio" value="N" onclick="calculo(2)" />
Ni&ntilde;o
<input name="op" type="radio" value="E" onclick="calculo(3)"/>
Estudiante</label></td>
</tr>
<tr>
<td>Pago</td>
<td><label>
<input name="tpago" type="text" id="tpago" />
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="Submit" value="Enviar" />
</label></td>
<td><input name="tvia" type="hidden" id="tvia" value="<%=viaje%>" />
<input name="tcos" type="hidden" id="tcos" value="<%=costo %>" />
<label>
<input type="reset" name="Submit2" value="Restablecer" />
</label></td>
</tr>
22
Facultad de Ingeniería Industrial y de Sistemas Ing. Alberto Moreno C.

</table>
</form>
</body>
<script language="javascript">
function calculo(n){
//recuperando el valor del campo oculto
cos=parseFloat(form1.tcos.value)
switch(n){
case 1:pago=cos; break;//adulto
case 2:pago=cos*0.5 ; break;
case 3:pago=cos*0.7
}
form1.tpago.value=pago
}
</script>
</html>

Vous aimerez peut-être aussi