Software">
Nothing Special   »   [go: up one dir, main page]

Java Web, Ejemplo MVC Club Deportivo Con B.D

Descargar como docx, pdf o txt
Descargar como docx, pdf o txt
Está en la página 1de 16

Java Web, MVC

Se debe separar la lógica de negocio de la presentación, una forma de separar las


funcionalidades es usando el patrón MVC

 Modelo: JavaBeans
 Vistas: Los archivos JSP (View)
 Controladores: Servlet

Crear nuevo proyecto web. ClubDeportivoMVC

Crear los paquetes:

1. Controller.. Clic derecho >New>Java Package, nombre controller


2. Model.. Clic derecho > New>Java Package, nombre model

Crear pagina principal index en la raíz del proyecto, es una vista con el formulario

Este formulario ya no enviara los datos a otra vista ejemplo procesar.jsp, sino que crearemos
un controlador (un Servlet que es una clase java), en la action del formulario escribir
procesar.do

3. Clic derecho en el paquete controlador > New > Servlet, nombre Procesar
4. Chequear la casilla Add information to deployment…
5. En URL cambiar por /procesar.do en minúscula

Modificar la clase Procesar, eliminar desde try … hasta …}, debido a que no se mostrara en el
controlador, para eso es la vista.
Recibimos los datos del processRequest

Hacer también la validación, en caso de no enviar los datos requeridos enviar a página
errorValidación, en caso contrario, enviar a página mostrar.jsp

Crear vista (pagina errorValidacion.jsp) para mostrar el error y dar opción de volver a index.

pagina: errorValidacion.jsp

para mostrar los datos, se debe crear el modelo Deportista

utilizar también una variable global, variable de sesión


Crear modelo Deportista
clic derecho en modelo> New > Java Class
Nombre: Deportista

Definir los atributos

Crear Constructor…
Crear Setter and Getter…

Ir a la página Procesar, crear una instancia de Deportista, deportista1, con los parámetros que
debe recibir, hacer el parseInt en los numéricos, importar clase Deportista

El deportista1 debe tener variables que permanezcan (variables de session),


Crear Página: mostrar.jsp

Rescatar los datos de la variable de sesión, con getAttribute….

Agregar las expresiones embebidas identificación, nombre, edad,….

Para mejorar la aplicación, validar si se ingresan datos String en edad.

En el controlador, controlar datos enteros (validar) con un Try – catch

Crear página errornumero.jsp

Terminado.

Adjunto la estructura de la aplicación y los códigos.


index.jsp
<%--
Document : index
Created on : 28-mar-2016, 12:51:31
Author : Alber Arango
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>Club Deportivo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div>Matricula Deportista </div>
<form action="procesar.do">
<table border="1">
<thead>
<tr>
<th colspan="2">Registro Deportista</th>
</tr>
</thead>
<tbody>
<tr>
<td>* Identificacion</td>
<td><input type="text" name="identificacion" size="12" /></td>
</tr>
<tr>
<td>* Nombre</td>
<td><input type="text" name="nombre" value="" /></td>
</tr>
<tr>
<td>Edad</td>
<td><input type="text" name="edad" size="2" /></td>
</tr>
<tr>
<td>Deporte</td>
<td><select name="deporte">
<option value="1">Futbol</option>
<option value="2">Basketboll</option>
</select></td>
</tr>
<tr>
<td>Sexo</td>
<td><input type="radio" name="sexo" value="hombre" />Niño<br>
<input type="radio" name="sexo" value="mujer" />Niña<br>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Registrar" />
<input type="reset" value="Limpiar" /></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

Errorvalidación.jsp
<%--
Document : errorValidacion
Created on : 28-mar-2016, 13:22:33
Author : Alber Arango
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META HTTP-EQUIV="refresh" CONTENT="2; URL=index.jsp">
<title>JSP Page</title>
</head>
<body>
<h1>La identificación y el nombre son requeridos</h1>
<a href="index.jsp">Volver...</a>
</body>
</html>

errorNumero.jsp

<%--
Document : errorNumero
Created on : 28-mar-2016, 16:37:58
Author : Alber Arango
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Error, debe ingresar edad en valor numerico</h1>
<a href="index.jsp">Volver...</a>
</body>
</html>
mostrar.jsp

<%--
Document : mostrar
Created on : 28-mar-2016, 15:36:07
Author : Alber Arango
--%>

<%@page import="model.Deportista"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%
Deportista deportista1 = (Deportista) request.getSession().getAttribute("sessionDep");
%>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Datos de la Matricula del Deportista</h1>

<table border="1">
<thead>
<tr>
<th colspan="2">Colilla de Matricula Deportista</th>
</tr>
</thead>
<tbody>
<tr>
<td>Identificacion</td>
<td><%=deportista1.getIdentificacion()%></td>
</tr>
<tr>
<td>Nombre</td>
<td><%=deportista1.getNombre()%></td>
</tr>
<tr>
<td>Edad</td>
<td><%= deportista1.getEdad()%></td>
</tr>
<tr>
<td>Sexo</td>
<td><%= deportista1.getSexo()%></td>
</tr>
<tr>
<td>Deporte</td>
<td><%= deportista1.getDeporte()%></td>
</tr>
<tr>
<td>Valor</td>
<td><%= deportista1.getValor()%></td>
</tr>
</tbody>
</table>
</body>
</html>

El controlador procesar.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Deportista;

/**
*
* @author Alber Arango
*/
public class Procesar extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

String identificacion = request.getParameter("identificacion");


String nombre= request.getParameter("nombre");
String edad = request.getParameter("edad");
String sexo= request.getParameter("sexo");
String deporte = request.getParameter("deporte");
if(identificacion.equals("") || nombre.equals("")){
request.getRequestDispatcher("errorValidacion.jsp").forward(request, response);
}

else{
int valor = 0;
if (deporte == "1") {
valor = 80000;
} else {
valor = 90000;
}
int eda=0;
try{
eda=Integer.parseInt(edad);
}
catch(NumberFormatException ex){
request.getRequestDispatcher("errorNumero.jsp").forward(request, response);
}

Deportista deportista1 = new Deportista(identificacion, nombre, eda, sexo, deporte, valor);


//Crear variable de sesion, nombre sessionDep, valor: lo que tienen el objeto deportista1
request.getSession().setAttribute("sessionDep", deportista1);

request.getRequestDispatcher("mostrar.jsp").forward(request, response);
}
}
}

El modelo Deportista.java
package model;

public class Deportista {

private String identificacion;


private String nombre;
private int edad;
private String sexo;
private String deporte;
private int valor;

public Deportista(String identificacion, String nombre, int edad, String sexo, String deporte, int valor) {
this.identificacion = identificacion;
this.nombre = nombre;
this.edad = edad;
this.sexo = sexo;
this.deporte = deporte;
this.valor = valor;
}

public String getIdentificacion() {


return identificacion;
}

public void setIdentificacion(String identificacion) {


this.identificacion = identificacion;
}

public String getNombre() {


return nombre;
}

public void setNombre(String nombre) {


this.nombre = nombre;
}

public int getEdad() {


return edad;
}

public void setEdad(int edad) {


this.edad = edad;
}

public String getSexo() {


return sexo;
}

public void setSexo(String sexo) {


this.sexo = sexo;
}

public String getDeporte() {


return deporte;
}

public void setDeporte(String deporte) {


this.deporte = deporte;
}

public int getValor() {


return valor;
}

public void setValor(int valor) {


this.valor = valor;
}

Guardar los datos en Base de Datos

1. Instalar una aplicación XAMPP, o Wampp, o APPSer….


Crear base de datos, en phpmyadmin
Nombre:
Tabla: Persona
Campos: identificación, nombre, edad, deporte, sexo, valor

Insert into persona (identificación, nombre, edad, deporte, sexo, valor)


Value
(‘545’,’Juan’,20,’Basquet’,80000)
Crear proyecto

Crear un index.jsp con el formulario, en action controlar.do

Hacer la conexión en NetBean con servicio de BD


Estando en NetBeam, ir a Services> Dababases, clic derecho, > Register MySQL Server
Ok

Clic derecho, conectar

Clic derecho en clubDeportivo> Conectar, ok


Se puede ver la Base de datos, las tablas, los campo.

Se pueden manipular los datos directamente,


Clic derecho en la conexión, Execute Command…

Ir al index.jsp, modificar el formulario en method controlador.do, method post

Crear paquetes controller, model

Ir al paquete controller, new, Servlet, Controlador, en url cambiar controlador.do

Dejar solo el método processRequest y la parte del try… borrar en el controlador


Inicializar las variable
Validar
Crear pagina jsp, con nombre error

Mandar a pagina error con parámetros según tipo de error


Ir a pagina error e imprimir el error
Recibir en un scriptlet,

Ir al paquete modelo, crear clase Deportista con los atributos del deportista

Crear constructor y getter y setter


Ir al controlador, crear un deportista dep1

Ir al paquete modelo, crear clase Conexión

Database URL
// Copiar de servicios, de la conexión, clic derecho, propiedades, copir de …
jdbc:mysql://localhost:3306/clubdeportivo?zeroDateTimeBehavior=convertToNull

También podría gustarte