Documentos de Académico
Documentos de Profesional
Documentos de Cultura
1. INTRODUCCION
2. MODELO DE SOLUCION
3. VARIABLES
4. TIPOS DE DATOS
5. CLASES NUMERICAS
6. OPERADORES ARITMETICOS
7. OPERADOR CAST Y CONVERSIONES
8. JERARQUIA DE OPERACIONES
9. APLICACIONES
10. CONCEPTOS BASICOS DE OOP
11. JAVA SERVER PAGE (1)
1. INTRODUCCION
2. INSTRUCCIONES DE CONTROL DE PROGRAMA
3. INSTRUCCIONES CONDICIONALES
4. CONDICIONES SIMPLES
5. OPERADORES RELACIONALES
6. INSTRUCCION IF
7. CONDICIONES COMPUESTAS
8. INSTRUCCION SWITCH
9. CONTROL SELECT
10. CONTROL CHECKBOX Y MANEJO DE
EXEPCIONES
11. CONTROL RADIOBUTTON
12. CICLO FOR
13. CICLO WHILE
14. CICLO DO...WHILE
15. CONCLUSIONES ACERCA DE CICLOS
1. INTRODUCCION
2. ARREGLOS TRADICIONALES
3. ARREGLOS TIPO LISTA
4. ARREGLOS TIPO TABLA
1. PROCEDIMIENTOS Y FUNCIONES
2. PARAMETROS
3. VARIABLES LOCALES Y GLOBALES
4. FUNCIONES
5. ARREGLOS COMO PARAMETROS
1. INTRODUCCION
2. ESTRUCTURAS O REGISTROS
3. ARCHIVOS (1)
4. ARCHIVOS (2)
5. CREACION ARCHIVOS
6. GRABACION Y LECTURA DISCO
7. BUSQUEDA EN ARCHIVO DIRECTO
8. FILTROS o CONDICIONES
9. BAJA o ELIMINACION
10. OPERACIONES CON CAMPOS
11. EDICION o MODIFICACION REGISTROS
12. GRAFICOS
1. INTRODUCCION
2. MODELOS DE ALMACENAMIENTO DE DATOS
3. TABLAS
4. TABLAS (CONTINUACION)
5. MICROSOFT ACCESS
6. JDBC SQL RESULTSET CONNECTION
7. SELECCION O DESPLIEGUE
8. INSERCCION O ADICION DE REGISTROS
9. BUSQUEDAS
10. FILTROS
11. OPERACIONES CON CAMPOS
12. BAJAS
13. EDICION DE REGISTROS
14. GRAFICOS O IMAGENES
UNIDAD 8: JAVA JSP INT A LAS BASES DE
DATOS (MYSQL)
1. INTRODUCCION
2. MODELOS DE ALMACENAMIENTO DE DATOS
3. TABLAS
4. TABLAS (CONTINUACION)
5. MYSQL (1)
6. OBJETO RESULTSET MYSQL (2)
7. SELECCION O DESPLIEGUE
8. INSERCCION O ADICION DE REGISTROS
9. BUSQUEDAS
10. FILTROS
11. OPERACIONES CON CAMPOS
12. BAJAS
13. EDICION DE REGISTROS
14. GRAFICOS O IMAGENES
UNIDAD I: JAVA JSP ELEMENTOS BASICOS
AREA = PI * RADIO2
Class Integer
public final class java.lang.Integer extends java.lang.Number
{
// Fields
public final static int **MAX_VALUE**;
public final static int **MIN_VALUE**;
// Constructors
public **Integer**(int value);
public **Integer**(String s);
// Methods
public double **doubleValue**();
public boolean **equals**(Object obj);
public float **floatValue**();
public static Integer **getInteger**(String nm);
public static Integer **getInteger**(String nm, int val);
public static Integer **getInteger**(String nm, Integer val);
public int **hashCode**();
public int **intValue**();
public long **longValue**();
public static int **parseInt**(String s);
public static int **parseInt**(String s, int radix);
public static String **toBinaryString**(int i);
public static String **toHexString**(int i);
public static String **toOctalString**(int i);
public String **toString**();
public static String **toString**(int i);
public static String **toString**(int i, int radix);
public static Integer **valueOf**(String s);
public static Integer **valueOf**(String s, int radix);
}
Esta clase convierte un dato de tipo int a un objeto.
Este objeto contiene un solo campo de tipo int.
Pero tambien el objeto contiene una serie de metodos para convertir
un valor int a una String y tambien para convertir una String a int.
Ademas de otros metodos de igual utilidad.
Class Double
public final class java.lang.Double extends
java.lang.Number
{
// Fields
public final static double **MAX_VALUE**;
public final static double **MIN_VALUE**;
public final static double **NaN**;
public final static double **NEGATIVE_INFINITY**;
public final static double **POSITIVE_INFINITY**;
// Constructors
public **Double**(double value);
public **Double**(String s);
// Methods
public static long **doubleToLongBits**(double value);
public double **doubleValue**();
public boolean **equals**(Object obj);
public float **floatValue**();
public int **hashCode**();
public int **intValue**();
public boolean **isInfinite**();
public static boolean **isInfinite**(double v);
public boolean **isNaN**();
public static boolean **isNaN**(double v);
public static double **longBitsToDouble**(long bits);
public long **longValue**();
public String **toString**();
public static String **toString**(double d);
public static Double **valueOf**(String s);
}
Class Float
public final class java.lang.Float extends java.lang.Number
{
// Fields
public final static float **MAX_VALUE**;
public final static float **MIN_VALUE**;
public final static float **NaN**;
public final static float **NEGATIVE_INFINITY**;
public final static float **POSITIVE_INFINITY**;
// Constructors
public **Float**(double value);
public **Float**(float value);
public **Float**(String s);
// Methods
public double **doubleValue**();
public boolean **equals**(Object obj);
public static int **floatToIntBits**(float value);
public float **floatValue**();
public int **hashCode**();
public static float **intBitsToFloat**(int bits);
public int **intValue**();
public boolean **isInfinite**();
public static boolean **isInfinite**(float v);
public boolean **isNaN**();
public static boolean **isNaN**(float v);
public long **longValue**();
public String **toString**();
public static String **toString**(float f);
public static Float **valueOf**(String s);
}
Class Long
public final class java.lang.Long extends java.lang.Number
{
// Fields
public final static long MAX_VALUE;
public final static long MIN_VALUE;
// Constructors
public Long(long value);
public Long(String s);
// Methods
public double doubleValue();
public boolean equals(Object obj);
public float floatValue();
public static Long getLong(String nm);
public static Long getLong(String nm, long val);
public static Long getLong(String nm, Long val);
public int hashCode(); public int intValue();
public long longValue();
public static long parseLong(String s);
public static long parseLong(String s, int radix);
public static String toBinaryString(long i);
public static String toHexString(long i);
public static String toOctalString(long i);
public String toString();
public static String toString(long i);
public static String toString(long i, int radix);
public static Long valueOf(String s);
public static Long valueOf(String s, int radix);
}
Operad
Operación
or
+ Suma
- Resta
* Multiplicacion
/ Division
Residuo o
%
Modulo
import java.lang.math ;
public static double pow(double a, double b);
Ejemplo:
Y = 3*Math.pow(x, 0.5);
* En este ejemplo no funcional se esta dando por supuesto que no
interesa el tipo de dato que requiere la función pow() para trabajar
correctamente.
Class Math
public final class java.lang.Math
extends java.lang.Object
{ Fields
public final static double E;
public final static double PI;
Methods
public static double abs(double a);
public static float abs(float a);
public static int abs(int a);
public static long abs(long a);
public static double acos(double a);
public static double asin(double a);
public static double atan(double a);
public static double atan2(double a, double b);
public static double ceil(double a);
public static double cos(double a);
public static double exp(double a);
public static double floor(double a);
public static double IEEEremainder(double f1, double f2);
public static double log(double a);
public static double max(double a, double b);
public static float max(float a, float b);
public static int max(int a, int b);
public static long max(long a, long b);
public static double min(double a, double b);
public static float min(float a, float b);
public static int min(int a, int b);
public static long min(long a, long b);
public static double pow(double a, double b);
public static double random();
public static double rint(double a);
public static long round(double a);
public static int round(float a);
public static double sin(double a);
public static double sqrt(double a);
public static double tan(double a);
}
Ejemplo:
// declaración
int alfa;
// Asignación
alfa = 20;
// Cambio de tipo
(float) alfa;
Ejemplo:
(int) 3.1416;
a) // Declaración
float alfa;
// Operación
alfa = (float)23/5;
// Pero en estos casos es preferible
alfa=23/5.0;
b)// Declaración
double potencia;
// Operación
potencia = Math.pow ( (double)5, (double)3);
1.
2.
3.
UNIDAD 1: JAVA JSP ELEMENTOS BASICOS
- 2+ 3* 4 = 20(incorrecto) = 14 (correcto)
b) si calif1=60 y calif2=80
entonces en programa se usa
promedio=calif1 + calif2/2
da como resultado promedio = 100
Orden de operaciones:
1. Paréntesis
2. Potencias y raíces
3. Multiplicaciones y divisiones
4. Sumas y restas
5. Dos o más de la misma jerarquía u orden,
entonces resolver de izquierda a derecha
corrida:
Notas:
1. Para insertar codigo java dentro de una pagina
html se deberan usar una serie de tags o
delimitadores ( en el ejemplo se esta usando <
% una serie de instrucciónes de java %> )
donde cada uno de ellos tiene un proposito
definido.
Otros delimitadores son:
Comentarios <%– comentario –%> Ignorados
cuando jsp es convertida a servlet y muy utiles
para documentar nuestros programas jsp.
Declaracion <%! Variables, metodos, etc %>
Recordar que todo buen programa, empieza
declarando variables.
2. Instruccion <%= instruccion %> Para poner una
y solo una instrucción de java, ademas recordar
que ya existen aparte ciertas instrucciones o
variables predefinidas tales como request,
response, out, session, application, config, and
pageContext( tambien disponibles en scriptlets).
Recordar ademas que cuando se use <%= una
sola instrucción %>, la instrucción no debe
terminar con punto y coma.
Scriptlet <% todo un programa completo %> Un
scriptlet es un grupo de instruciones de java,
como se deduce de esta definición, se usara
muchos scriptltes en nuestros jsp.
Aqui si, las instucciones deben terminar con
punto y coma
Un bloque de instruciones <% bloque java %>,
puede empezar (<%) en un scriptlet y terminar
en otro scriptlet, pero asegurarse de que todos
los scriptlets se abran y se cierren.
Include Directive <%@ include file=“url” %> Se
usa para incluir achivos en la pc que compila la
jsp, esto se realiza al tiempo que la jsp es
convertida en servlet, el url debe ser relativo.
Para este caso tambien es valido:
jsp:include action para incluir el archivo al
tiempo de request por parte de un usuario
remoto
jsp:forward Action <jsp:forward page=“URL
relativo”/> Manda llamar o enlazar otra pagina.
NOTA: HASTA AQUI SON LAS DIRECTIVAS O
DELIMITADORES MAS COMUNES EN PROGRAMAS
O APLICACIONES SENCILLAS
2.- En la parte de abajo se esta construyendo
una pagina html dinamica, usando la
instrucción( mejor dicho objeto OUT) out.println
de java, les recuerdo conseguir un buen tutorial
de HTML y estudiarlo a fondo.
3. Se esta usando tres objetos TEXT de html (ver
apendice html), de estos objetos se cargan su
propiedad NAME y VALUE en este ultimo caso
usando una variable normal de java jsp
4. Poner atención dentro del programa que cuando
creamos objetos HTML se declaran en
mayusculas y cuando creamos variables java se
declaran en minusculas, no es una regla pero si
es una buena practica de programación.
5. Se esta usando un objeto HTML submit del cual
se usan las propiedades NAME y VALUE, este
objeto tiene como proposito principal activar la
acción de la forma (llamarse a si mismo el
prog1.jsp) y ademas mandar los datos que
proporciono el usuario hacia el servidor.
6. La ultima parte de la pagina es FORM, todos los
objetos html deberan estar encerrados entre
esta forma o ventana, form tiene dos
propiedades la primera de ellas es una acción y
en este caso la acción es pedirle al servidor que
vuelva a ejecutarse el propio programa1 jsp, la
segunda parte es un metodo, es este caso es el
metodo POST tambien se puede poner el
metodo GET, en ambos casos este metodo
regresa los datos desde la pc del usuario hacia
el servidor, pero POST lo hace en forma invisible
y GET lo hace en forma publica (probar el
mismo programa con post y get y observar que
pasa cuando activan el boton de submit).
7. Al principio del programa se deberan declarar e
inicializar a 0 o ”” todas las variables del
programa.
8. Se esta usando una instrucción IF para revisar el
VALUE de SUBMIT, recordar que cuando el
usuario pide por primera vez el programa al
servidor , el VALUE del objeto SUBMIT es “null”,
ya que el usuario carga datos en los objetos
TEXT y realiza un click en SUBMIT, el value de
SUBMIT pasa a valer “evento1”.
9. Se esta usando el objeto
REQUEST.GETPARAMETER( VALUE OBJETO
HTML) para leer la propiedad VALUE de los
objetos HTML y de paso cargarlos en las
variables java apropiadas.
10. Recordar que todos los datos que entran o
salen de un objeto html seran de tipo string.
11. Por la razón del inciso 10 se esta usando
el metodo parseInt(string) para convertir la
string a int.
12. Ya cargadas las variables se debera
realizar la operación apropiada, recordar incluir
estas variables en la forma dinamica.
Propiedad Metod
Eventos
es os
“OnClick
“form” “click”
”
“OnFocu
“name” “focus”
s”
“value”
“enabled”
Control “CheckBox”.
Metod
Propiedades Eventos
os
“OnClick
“form” “click”
”
“OnFocu
“name” “focus”
s”
“value”
“enabled”
“checked”
“defaultcheck
ed”
Control “Radio”.
Propiedad Metod
Eventos
es os
“form” “OnClick “click”
”
“OnFocu
“name” “focus”
s”
“value”
“enabled”
“checked
”
Control “Password”.
Propiedad Metod
Eventos
es os
“form” “OnBlur” “blur”
“OnFocu
“name” “focus”
s”
“value”
“enabled”
Propiedad Metod
Eventos
es os
“form” “OnBlur” “blur”
“OnFocu
“name” “focus”
s”
“value”
“enabled”
Control “Select”.
Metod
Propiedades Eventos
os
“length” “OnBlur” “blur”
“OnFocus
“options” “focus”
”
“selectedInd “OnChang
ex” e”
Control “Hidden”.
“abstrac “strictfp”
“double” “int”
t” &&
“boolean “interface
“else” “super”
” ”
“break” “extends” “long” “switch”
“synchroniz
“byte” “final” “native”
ed”
“case” “finally” “new” “this”
“package
“catch” “float” “throw”
”
“char” “for” “private” “throws”
“protecte
“class” “goto” & “transient”
d”
“const”
“if” “public” “try”
%
“continu “implemen
“return” “void”
e” ts”
“default” “import” “short” “volatile”
“instanceof
“do” “static” “while”
”
JAVA.SUN.COM
UNIDAD 2: JAVA JSP INSTRUCCIONES DE
CONTROL DE PROGRAMA
Operad
Significado
or
== Igual que
> Mayor que
< Menor que
>= Mayor o igual que
⇐ Menor o igual que
No es igual que o es
!=
diferente que
Ejemplo:
Prog2 jsp
<%
// declarando
int sueldo=0;String res="";
if(request.getParameter("OK") != null)
{
sueldo = Integer.parseInt(request.getParameter("SUELDO"));
if (sueldo >= 3000)
{ res="RICO"; }
else {res="POBRE"; };
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog2.jsp METHOD=post>");
out.println("DAME SUELDO:<INPUT TYPE=TEXT NAME=SUELDO
value="+sueldo+"><BR>");
out.println("EVALUACION:<INPUT TYPE=TEXT NAME=RES
value="+res+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Recordar que es valido usar mas de una instrucción
dentro del grupo cierto o falso del if.
if ( carrera.compareTo(“informatica”) == 0 )
OPERAD
SIGNIFICADO
OR
&& “Y” LOGICO
“O”
LOGICO
“NO”
!
NEGACION
Ejemplo:
Notas:
Observar que cada condición simple lleva sus propios
parentesis.
Si la variable es de tipo string el dato va entre
comillas(”), pero si la variable es de tipo char el dato
va entre apostrofes(').
Para que el computador evalúe como CIERTA una
condición compuesta que contiene el operador lógico
”&&”, las dos condiciones simples deben ser ciertas.
switch(var OPCION)
{
case const1: instrucción(es);
break;
case const2: instrucción(es);
break;
case const3: instrucción(es);
break; ………………
default: instrucción(es);
};
prog3 jsp
<%
// declarando
char letra=' ';
if(request.getParameter("OK") != null)
{
//recordar que TEXTBOX contiene una string
letra=request.getParameter("LETRA").charAt(0);
switch(letra)
{case 'a':
out.println("aguila ");
break;
case 'b': case 'B':
out.println("baca ");
break;
case 'c':
out.println("caballo ");
break;
default:
out.println("no hay ");
};
// observar que se puede escribir direcatmente a la pagina dinamica
// esto es para los flojos
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog3.jsp METHOD=post>");
out.println("DAME UNA LETRA:<INPUT TYPE=TEXT NAME=LETRA
value="+letra+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Prog4.jsp
<%
// declarando
String municipio="";
if(request.getParameter("OK") != null)
{
municipio =request.getParameter("MUNICIPIO");
out.println(municipio+" =");
if (municipio.compareTo("ENSENADA")==0) out.println("TIBIO");
if (municipio.compareTo("TIJUANA")==0) out.println("HELADO");
if (municipio.compareTo("MEXICALI")==0) out.println("CALIENTE");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog4.jsp METHOD=post>");
out.println("<B>MUNICIPIOS</B>");
out.println("<SELECT NAME=MUNICIPIO>");
out.println("<OPTION>ENSENADA<OPTION>TECATE<OPTION>TIJUANA<OPTION>ME
XICALI");
out.println("</SELECT>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Ejemplos de uso:
<%
// observar declaracion y usando las otras directivas
if(request.getParameter("OK") != null)
{
m=request.getParameter("M");
n=request.getParameter("N");
f=request.getParameter("F");
try{
if (m.compareTo("on")==0) out.println("masculino checado<br>");
}catch(java.lang.NullPointerException e){};
try{
if (n.compareTo("on")==0) out.println("neutro checado<br>");
}catch(java.lang.NullPointerException e){};
try{
if (f.compareTo("on")==0) out.println("femenino checado<br>");
}catch(java.lang.NullPointerException e){};
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog5.jsp METHOD=post>");
out.println("<b>sexo:</b><br>");
out.println("<input type=checkbox name=M checked>masculino<br>");
out.println("<input type=checkbox name=F >femenino<br>");
out.println("<input type=checkbox name=N checked>neutro<br>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Notas:
<%
// es mejor esta declaracion no hay que inicializar
if(request.getParameter("OK") != null)
{
sexo=request.getParameter("SEXO");
carrera=request.getParameter("CARRERA");
out.println("carrera="+carrera+"<br>");
out.println("sexo="+sexo+"<br>");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog6.jsp METHOD=post>");
out.println("sexo:<br>");
out.println("<input type=radio name=SEXO value=masculino
checked>masculino<br>");
out.println("<input type=radio name=SEXO
value=femenino>femenino<br>");
out.println("<input type=radio name=SEXO value=neutro>neutro<br>");
out.println("carrera:<br>");
out.println("<input type=radio name=CARRERA value=sistemas
checked>sistemas<br>");
out.println("<input type=radio name=CARRERA
value=informatica>informatica<br>");
out.println("<input type=radio name=CARRERA
value=medicina>medicina<br>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
1. Observar que tenemos dos grupos de
radiobotones uno con NAME=SEXO y otro con
NAME=CARRERA sin embargo existen varios
radiobotones y cada radiobuton tiene su propio
valor o VALUE.
2. Recordar que en checkbox(tema anterior) la
propiedad NAME debe ser distinta para cada
uno de ellos, mientras que en radiobutton es la
misma para todo un grupo similar de ellos.
3. La razón principal para esta situación es que los
radiobotones son mutuamente excluyentes
entre si Y QUE SOLO UNO PUEDE ESTAR
ENCENDIDO A LA VEZ por eso los agrupamos
con la propiedad NAME para que html los pueda
considerar como dos o mas grupos diferentes.
4. Tambien tienen la propiedad checked para que
aparezcan seleccionados al cargar el programa
prog6 jsp
5. A diferencia del checkbox, html va a regresar
solamente el par NAME=VALUE de el
radiobuton que este seleccionado, esto lo
hace por cada grupo de radiobotones que
tengamos en la forma html
1. CONSTRUIR UN CUESTIONARIO DE 6
PREGUNTAS SOBRE LOS HÁBITOS DE ESTUDIO
DE UN ESTUDIANTE Y PASAR SUS RESPUESTAS
A UNA PAGINA NUEVA.
2. EVALUAR UNA FUNCION CUALESQUIERA, LA
PAGINA HTML TIENE NAME = X Y VALUE = 3,
-5, 10 .
UNIDAD 2: JAVA JSP INSTRUCCIONES DE
CONTROL DE PROGRAMA
EJEMPLO
<%
%>
Casos Particulares del ciclo for:
1. 1.- El ciclo comienza en uno y se incrementa de
uno en uno este es el caso mas general.
2. Pero el valor inicial puede se diferente de uno,
ejemplo;
for(x=5;x⇐15;x=x+1){ etc.};
3. Incluso el valor inicial puede ser negativo,
ejemplo;
for (x = -3 ;x⇐ 8; x=x+1) { etc.};
4. Los incrementos también pueden ser diferentes
al de uno en uno, ej.;
for (x=1; x⇐ 20; x=x+3){ etc. };
5. Incluso pueden ser decrementos, solo que en
este caso, recordar;
a. el valor inicial de la variable debe ser
mayor que el valor final.
b. cambiar el sentido de la condición.
ejemplo;
Su formato general es :
Su formato general es :
NOMBRES
Juan –
>nombres(0)
Pedro →
nombres(1)
Rosa –>
nombres(2)
Jose –>
nombres(3)
a) LISTAS
EDAD
1
8
3
4
2
2
1
5
B) TABLAS
CIA ACME
ING MENS VTAS
(MILES DE $)
SUC 1
20 30 40
A 0
SUC 5
60 70 80
B 0
SUC 9 10 11 12
D 0 0 0 0
En java Jsp se observa la diferencia principal entre un
arreglo tipo lista y un arreglo tipo tabla son las
cantidades de columnas que contienen.
Notas:
ej:
int edad[4]={15,16,17,18};
float sueldo[3]={40.85, 65.30, 33.33};
String *ciudad[]={“tecate”, “tijuana”, “mexicali”,
“rosarito”, “ensenada”};
Prog11 jsp
<%! int edad[][]=new int[2][3], ren=0, col=0; %>
<%
String temp1=request.getParameter("INSERTAR");
if(temp1==null)temp1=" ";
if(temp1.compareTo("insertar")==0){
if(col < 3){
edad[ren][col]=Integer.parseInt(request.getParameter("EDAD"));
col=col+1;};
if(col == 3){col=0;ren=ren+1;};
if(ren==2) {out.print("TABLA LLENA");};
};
if(request.getParameter("MESES") != null )
{
// operaciones
for(ren=0; ren<=1; ren++)
for(col=0;col<=2;col++)
edad[ren][col]=edad[ren][col]*12;
// DESPLEGANDO USANDO OBJETO TABLE DE HMTL FOR NORMAL
out.println("<table border=2><tr><th>EDAD EN MESES</th></tr>");
for(ren=0; ren<=1; ren++)
{ out.println("<tr>");
for(col=0;col<=2;col++)
{ out.println("<td>"+edad[ren][col]+"</td>"); };
out.println("</tr>"); };
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog11.jsp METHOD=post>");
out.println("DAME EDAD:"+ren+","+col+"<INPUT TYPE=TEXT
NAME=EDAD>");
out.println("<INPUT TYPE=SUBMIT NAME=INSERTAR VALUE=insertar
><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=MESES VALUE=meses><BR>");
out.println("</FORM>");
%>
Notas:
Observar el formato de declaración y como se
controlan los indices de captura reng, col.
Notas:
El for reng tiene su propio grupo de instrucciones
encerrados entre {}. Mientras que el for col solo
tiene una instrucción que ejecutar el print(celda ),
el ultimo print(</termina renglon) es del ciclo for
reng).
FOR R = 0 TO 3
FOR C = 0 TO 2
NEXT C
PROMRENG(R) = TOTRENG(R)/3
NEXT R
FOR C = 0 TO 2
FOR R = 0 TO 3
TOTCOL(C)=TOTCOL(C) + TABLA(R,C)
NEXT R
PROMCOL(C) = TOTCOL(C) / 4
NEXT C
TEMA 1: DECLARACIONES o
PROCEDIMIENTOS JAVA JSP
Su formato es:
Menu.
a) Pesos a dolares.
b) Area de un triangulo.
c) Emitir Boleta.
d) Fin de menu.
UNIDAD 4: JAVA JSP PROGRAMACION
ORIENTADA OBJETOS
<%!
void NomProc(lista de parametros)
{ cuerpo de instrucciones; };
%>
prog13.jsp
<%!
int base=0; double altura=0; double area=0;
void proc1(int a, double b){
area= a * b / 2.0 ;};
%>
<%
// no usar objetos request y out fuera de scriptlet
// porque no estan creados por java todavia
if(request.getParameter("OK") != null)
{
base = 10;
altura = 3.1416;
// llamando o invocando procedimiento uno y pasando parametros
// recordar que se pueden mandar datos o variables
proc1(base,3.1416);
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog13.jsp METHOD=post>");
out.println("DAME LA BASE:<INPUT TYPE=TEXT NAME=BASE
value="+base+"><BR>");
out.println("DAME LA ALTURA:<INPUT TYPE=TEXT NAME=ALTURA
value="+altura+"><BR>");
out.println("AREA:<INPUT TYPE=TEXT NAME=AREA value="+area+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
REGLAS PARA EL USO DE PARAMETROS
INSTRUCCION RETURN
<%!
double res=0;
double funcion1(int a, double b){
return a * b; };
%>
<%
// no usar objetos request y out fuera de scriptlet
// porque no estan creados por java todavia
if(request.getParameter("OK") != null)
{
// llamando o invocando funcion uno y pasando parametros
// recordar que se pueden mandar datos o variables
double alfa=funcion1(2,2.5) + 3 + funcion1(2, 3.3);
res= alfa;
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog14.jsp METHOD=post>");
out.println("RESULTADO:<INPUT TYPE=TEXT NAME=RESULTADO
value="+res+"><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
Ejemplo;
Prog15 jsp
<%!
int r;
for(r=0;r<=2;r++)
alfa[r]=alfa[r]+10;
};
%>
<%
if(request.getParameter("OK") != null)
int eta[]={3,4,5};
decl1(eta);
for(r=0;r<=2;r++)
out.println("eta="+eta[r]+"<br>");
};
out.println("</FORM>");
%>
Problema A:
Variables que puedan almacenar un conjunto de
valores y no necesariamente del mismo tipo.
Problema B:
Resolver el problema de almacenar en forma
permanente los datos que se generan dentro de un
programa ya sea por captura, proceso, etc;
Ejemplo;
class alumno{
void alumno(){};
static String nombre= new String();
static int edad;
void inicializar(){
alumno.nombre="pepe el toro";
alumno.edad=18; };
void desplegar(){
System.out.println(alumno.nombre);
System.out.println(alumno.edad);
};
} // termina la clase
Programa 16.jsp;
<%!
static class alumno{
static String nombre=" ";
static int edad=0;
void alumno(){};
static void inicializar(){
alumno.nombre="pepe el toro";
alumno.edad=18; };
};
%>
<%
if(request.getParameter("OK") != null)
{
alumno.inicializar();
out.println(alumno.nombre);
out.println(alumno.edad);
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog16.jsp METHOD=post>");
out.println("<INPUT TYPE=SUBMIT NAME=OK VALUE=evento1 ><BR>");
out.println("</FORM>");
%>
nomclase.nombredelcampo
Organización de archivos:
Tipo de archivos:
Almacenamiento en arhivos:
1. Modo Texto: en este caso los datos son
almacenados usando codigp ascii y por tanto
son plenamente visibles usando cualquier
editor.
2. Modo Binario: en este caso los datos son
almacenados en notación hexadecimal y por
tanto se ocupa un editor binario para
reconocerlos sin embargo un archivo binario es
mas compacto que un archivo texto.
UNIDAD 5: JAVA JSP REGISTROS Y
ARCHIVOS SECUENCIALES
Codigo de grabación:
Prog17.jsp
<%@ page import="java.io.*" %>
<%
// declarando
int clave=0;String nombre=""; float estatura=0;
// creando un objeto de tipo archivo
DataOutputStream archivo = null;
if(request.getParameter("INSERTAR") != null)
{
// capturando datos
clave=Integer.parseInt(request.getParameter("CLAVE"));
nombre=request.getParameter("NOMBRE");
estatura=Float.parseFloat(request.getParameter("ESTATURA"));
try {
// creando archivo en append
archivo = new DataOutputStream(new
FileOutputStream("c:\\archivo1.dat",true));
// grabando al archivo
archivo.writeInt(clave);
archivo.writeUTF(nombre);
archivo.writeFloat(estatura);
out.println(clave+": registro grabado");
}
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
// cerrando el archivo
archivo.close();
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog17.jsp METHOD=post>");
out.println("CLAVE :<INPUT TYPE=TEXT NAME=CLAVE><BR>");
out.println("NOMBRE :<INPUT TYPE=TEXT NAME=NOMBRE><BR>");
out.println("ESTATURA :<INPUT TYPE=TEXT NAME=ESTATURA><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=INSERTAR VALUE=GRABAR ><BR>");
out.println("</FORM>");
%>
Se usa una clase llamada FileOutputStream,
especializada en archivos con muchos metodos y
constructores para crear, manipular y procesar
archivos el constructor usado solo lleva dos
parametros, el primero todo la ruta o path a donde
quedara el archivo(cuidado con no poner la doble
diagonal \\) y el segundo parametro es la palabra
“true”, esto es para que el archivo se abra en modo
llamado “APPEND”, es decir que cada nuevo registro
se vaya escribiendo al final del archivo, si no se pone
este parametro(true), un nuevo registro se
sobreescribiria sobre el registro anterior.
Method Summary
“void
flush”()” Flushes this data output stream.
”
size”()” Returns the current value of the counter “written”,
“int” the number of bytes written to this data output stream so
far.
write”(byte[] b, int off, int len)“
“void
Writes “len” bytes from the specified byte array starting at
”
offset “off” to the underlying output stream.
“void write”(int b)” Writes the specified byte (the low eight bits of
” the argument “b”) to the underlying output stream.
“void writeBoolean”(boolean v)” Writes a “boolean” to the
” underlying output stream as a 1-byte value.
“void writeByte”(int v)“
Writes out a “byte” to the underlying output stream as a 1-
”
byte value.
“void WriteBytes (String s) Writes out the string to the underlying
” output stream as a sequence of bytes.
“void writeChar”(int v)” Writes a “char” to the underlying output
” stream as a 2-byte value, high byte first.
“void WriteChars (String s) writes a string to the underlying
” output stream as a sequence of characters.
writeDouble”(double v)“
Converts the double argument to a “long” using the
“void
“doubleToLongBits” method in class “Double”, and then
”
writes that “long” value to the underlying output stream as
an 8-byte quantity, high byte first.
writeFloat”(float v)” Converts the float argument to an “int”
“void using the “floatToIntBits” method in class “Float”, and then
” writes that “int” value to the underlying output stream as a
4-byte quantity, high byte first.
writeInt”(int v)“
“void
Writes an “int” to the underlying output stream as four
”
bytes, high byte first.
writeLong”(long v)“
“void
Writes a “long” to the underlying output stream as eight
”
bytes, high byte first.
writeShort”(int v)“
“void
Writes a “short” to the underlying output stream as two
”
bytes, high byte first.
writeUTF (String str) writes a string to the underlying output
“void
stream using UTF-8 encoding in a machine-independent
”
manner.
Prog18.jsp:
Method Summary
read”(byte[] b)“
“int” See the general contract of the “read” method of
“DataInput”.
read”(byte[] b, int off, int len)“
“int” See the general contract of the “read” method of
“DataInput”.
readBoolean”()“
“boolea
See the general contract of the “readBoolean” method of
n”
“DataInput”.
readByte”()“
“byte” See the general contract of the “readByte” method of
“DataInput”.
readChar”()“
“char” See the general contract of the “readChar” method of
“DataInput”.
readDouble”()“
“double
See the general contract of the “readDouble” method of
”
“DataInput”.
readFloat”()“
“float” See the general contract of the “readFloat” method of
“DataInput”.
readFully”(byte[] b)“
“void” See the general contract of the “readFully” method of
“DataInput”.
readFully”(byte[] b, int off, int len)“
“void” See the general contract of the “readFully” method of
“DataInput”.
“int” readInt”()“
See the general contract of the “readInt” method of
“DataInput”.
String
with: BufferedReader d
= new BufferedReader(new InputStreamReader(in)); |
| “long” | readLong”()“
See the general contract of the “readLong” method of
“DataInput”. |
readShort”()“
“short” See the general contract of the “readShort”
method of “DataInput”.
readUnsignedByte”()“
“int” See the general contract of the
“readUnsignedByte” method of “DataInput”.
readUnsignedShort”()“
“int” See the general contract of the
“readUnsignedShort” method of “DataInput”.
readUTF”()“
String See the general contract of the “readUTF”
method of “DataInput”.
readUTF”(“DataInput “in)“
Reads from the stream “in” a representation of
“static”
a Unicode character string encoded in Java
String
modified UTF-8 format; this string of
characters is then returned as a “String”.
skipBytes”(int n)“
“int” See the general contract of the “skipBytes”
method of “DataInput”.
Codigo prog19.Java:
<%@ page import="java.io.*" %>
<%
// declarando
int clave=0;int claveb=0;String nombre=""; float estatura=0;
// creando un objeto de tipo archivo
DataInputStream archivo = null;
if(request.getParameter("BUSCAR") != null)
{
// construyendo tabla html
out.println("<HTML><TABLE Border=10 CellPadding=5><TR>");
out.println("<th bgcolor=Green>CLAVE</th><th
bgcolor=White>NOMBRE</th><th bgcolor=Red>ESTATURA</th></TR>");
// capturando clave a buscar
claveb=Integer.parseInt(request.getParameter("CLAVEB"));
try {
// abriendo archivo
archivo = new DataInputStream(new
FileInputStream("c:\\archivo1.dat"));
while(true){
clave=archivo.readInt();
nombre=archivo.readUTF();
estatura=archivo.readFloat();
if (claveb==clave){
out.println("<TR>");
out.println("<TD>"+clave+"</TD>");
out.println("<TD>"+nombre+"</TD>");
out.println("<TD>"+estatura+"</TD>");
out.println("</TR>");
} } }
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
archivo.close();
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog19.jsp METHOD=post>");
out.println("CLAVE BUSCAR:<INPUT TYPE=TEXT NAME=CLAVEB><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=BUSCAR VALUE=buscar><BR>");
out.println("</FORM>");
%>
Procedimiento :
Prog21 jsp
<%@ page import="java.io.*" %>
<%
// declarando
int clave=0;int claveb=0;String nombre=""; float estatura=0;
// creando un objeto de tipo archivo
DataInputStream archivo = null;
DataOutputStream archivot = null;
if(request.getParameter("ELIMINAR") != null)
{
// capturando clave a eliminar
claveb=Integer.parseInt(request.getParameter("CLAVEB"));
try {
// abriendo archivos
archivo = new DataInputStream(new
FileInputStream("c:\\archivo1.dat"));
archivot = new DataOutputStream(new
FileOutputStream("c:\\temp.dat",true));
while(true){
clave=archivo.readInt();
nombre=archivo.readUTF();
estatura=archivo.readFloat();
if (claveb!=clave){
archivot.writeInt(clave);
archivot.writeUTF(nombre);
archivot.writeFloat(estatura);
}}}
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
// cerrando archivos
archivo.close();
archivot.close();
// eliminando original renombrando temporal
File file1 = new File("c:\\archivo1.dat");
File file2 = new File("c:\\temp.dat");
if (file1.exists()) {file1.delete();};
file2.renameTo(file1);
// avisando
out.println("REGISTRO ELIMINADO");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog21.jsp METHOD=post>");
out.println("CLAVE ELIMINAR:<INPUT TYPE=TEXT NAME=CLAVEB><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=ELIMINAR VALUE=Eliminar><BR>");
out.println("</FORM>");
%>
Prog22.jsp
<%@ page import="java.io.*" %>
<%
// declarando
int clave=0;String nombre=""; float estatura=0;
// creando dos objetos de tipo archivo uno para escritura y otro
para lectura
DataInputStream archivo = null;
DataOutputStream archivot = null;
if(request.getParameter("SUMAR") != null)
{
try {
// abriendo archivos
archivo = new DataInputStream(new
FileInputStream("c:\\archivo1.dat"));
archivot = new DataOutputStream(new
FileOutputStream("c:\\temp.dat",true));
while(true){
clave=archivo.readInt();
nombre=archivo.readUTF();
estatura=archivo.readFloat();
// sumando
estatura = estatura + 5;
// grabando a temporal
archivot.writeInt(clave);
archivot.writeUTF(nombre);
archivot.writeFloat(estatura);
}}
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
// cerrando archivos
archivo.close();
archivot.close();
// eliminando original renombrando temporal
File file1 = new File("c:\\archivo1.dat");
File file2 = new File("c:\\temp.dat");
if (file1.exists()) {file1.delete();};
file2.renameTo(file1);
// avisando
out.println("ESTATURAS SUMADAS ");
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog22.jsp METHOD=post>");
out.println("<INPUT TYPE=SUBMIT NAME=SUMAR VALUE=EST+5><BR>");
out.println("</FORM>");
%>
Prog23.jsp
prog24.jsp
<%@ page import="java.io.*" %>
<%
// declarando
int clave=0;int claveb=0;String nombre=""; float estatura=0;String
foto="";
// creando un objeto de tipo archivo
DataInputStream archivo = null;
if(request.getParameter("BUSCAR") != null)
{
// construyendo tabla html
out.println("<HTML><TABLE Border=10 CellPadding=5><TR>");
out.println("<th bgcolor=Green>CLAVE</th><th
bgcolor=White>NOMBRE</th><th
bgcolor=Red>ESTATURA</th><th>FOTOGRAFIA</TH></TR>");
// capturando clave a buscar
claveb=Integer.parseInt(request.getParameter("CLAVEB"));
try {
// abriendo archivo
archivo = new DataInputStream(new
FileInputStream("c:\\archivo1.dat"));
while(true){
clave=archivo.readInt();
nombre=archivo.readUTF();
estatura=archivo.readFloat();
foto=archivo.readUTF();
if (claveb==clave){
out.println("<TR>");
out.println("<TD>"+clave+"</TD>");
out.println("<TD>"+nombre+"</TD>");
out.println("<TD>"+estatura+"</TD>");
out.println("<TD><img
src=http:\\\\localhost\\progs\\"+foto+"></TD>");
out.println("</TR>");
} } }
catch(FileNotFoundException fnfe) {}
catch (IOException ioe) {};
archivo.close();
};
// construyendo forma dinamica
out.println("<FORM ACTION=prog24.jsp METHOD=post>");
out.println("CLAVE BUSCAR:<INPUT TYPE=TEXT NAME=CLAVEB><BR>");
out.println("<INPUT TYPE=SUBMIT NAME=BUSCAR VALUE=buscar><BR>");
out.println("</FORM>");
%>
nota: