domingo, 11 de diciembre de 2011

PROYECTO CARRITO DE COMPRAS EN JAVA NETBEANS


Codigo Conexion con una base de datos en Mysql :
package logicaDatos;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Alexander Tujillo Moran
 */
public class ConexionDB {
    private Connection conexion;
    private Statement sentencia;
    private ResultSet resultado;
    private String driver="com.mysql.jdbc.Driver";
    private String url="jdbc:mysql://localhost:3306/libros";
   
    public ConexionDB() throws ClassNotFoundException{
        Class.forName(driver);
    }
   
    public void abrirConexion() throws SQLException{
        conexion=DriverManager.getConnection(url, "root", "upao");       
    }
   
    public ResultSet realizarConsulta(String consulta) throws SQLException{
        sentencia=conexion.createStatement();
        resultado=sentencia.executeQuery(consulta);
        return resultado;
    }
   
    public void cerrarConexion() throws SQLException{
        sentencia.close();
        conexion.close();
    }
}

Codigo del ServletDatos:

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import logica.CarritoCompras;
import logica.Libro;
import logicaDatos.ConexionDB;

/**
 *
 * @author Alexander Trujillo Moran
*/
public class ServletDatos 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");
        PrintWriter out = response.getWriter();
        String libro,titulo="";
        double precio=0;
        ConexionDB con=null;
        ResultSet rs=null;
        CarritoCompras carrito;
        HttpSession sesion=request.getSession(true);
        carrito=(CarritoCompras)sesion.getAttribute("carrito");
        if(carrito==null){
            carrito=new CarritoCompras();
            sesion.setAttribute("carrito", carrito);                   
        }
        libro=request.getParameter("libros");
        try{
        out.println("<html>");
        out.println("<head>");
        if(libro.compareTo("Seleccione")==0){         
           out.println("<title>Recomendaciones</title>"); 
           out.println("</head>");
           out.println("<body>");
           out.println("<h1>No hay Recomendaciones</h1>");
           out.println("<p>Ud. no selecciono ningun libro</p>");
           out.println("<a href=\"index.jsp\">Haga click aca para seguir comprando</a>");
           out.println("</body>");
           out.println("</html>");
        }else{
            con=new ConexionDB();
            con.abrirConexion();
            rs=con.realizarConsulta("select * from libro "
                    + "where LIB_NOMBRE like '"+libro+"%'");
            while(rs.next()){
              titulo=rs.getString(2);
              precio=rs.getDouble(3);
            }
            carrito.agregarLibro(new Libro(titulo,precio));
            out.println("<title>Sigue Comprando</title>"); 
            out.println("</head>");
            out.println("<body>");
            out.println("<h3>Bienvenido a Libreria Atlantida! Ud. seleciono "+titulo+"</h3>");           
            out.println("<a href=\"index.jsp\">Clickee aqui para seguir comprando</a></br>");
            out.println("<a href=\"ServletResumen\">Clickee aqui para ver resumen de compra</a>");
            out.println("</body>");
            out.println("</html>");
        }           
        }catch(ClassNotFoundException ex){
            System.out.println(ex);
        }catch(SQLException ex){
            System.out.println(ex);
        }finally {           
            out.close();
            try {
                con.cerrarConexion();
            } catch (SQLException ex) {
                System.out.println(ex);
            }
        }
    }

Codigo Jsp Index:

<%--
    Document   : index
    Created on : 29/10/2011, 08:08:22 AM
    Author     :Alexander Trujillo Moran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Carrito de Compras</title>
    </head>
    <body>
        <h1>SELECCIONES LIBRO DE SU PREFERENCIA</h1>
        <form action="ServletDatos">
            Libro:
            <select name="libros">
                <option value="Seleccione" selected="selected">Seleccione</option>
                <option value="Java">Java</option>
                <option value="C">C++</option>
                <option value="Ruby">Ruby</option>
                <option value="Python">Python</option>
            </select>
            <input type="submit" value="Enviar"/>
        </form>
       
    </body>
</html>





 Codigo Jsp Añadir Carrito

<%--
    Document   : AñadirCarrito
    Created on : 04/11/2011, 10:16:22 PM
    Author     : Alexander Trujillo Moran
--%>

<%@page import="java.util.ArrayList"%>
<%@page import="logica.*" %>
<%@page import="logicaDatos.*" %>
<%@page import="java.util.*" %>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Reporte de Libros</h1>
        <div>
            <a href="index.jsp">Inicio</a>
            <a href="Reporte">Reporte Producto</a>
        </div>
        <form method="post" action="ServletDatos">
            <div>
                <input type="hidden" name="accion" value="AnadirCarrito" />

                    <table border="1">
                    <tr>
                        <td>Libro</td>
                        <td><input type="text" name="txtLibro" value="<%= Libro.getTitulo()%>" readonly /></td>
                    </tr>
                    <tr>
                    </table>

            </div>
        </form>
    </body>
</html>

Codigo Libro.java:


package logica;

/**
 *
 * @author Alexander Trujillo Moran
 */
public class Libro {
    private String titulo;
    private double precio;
   
    public Libro(String titulo,double precio){
        this.titulo=titulo;
        this.precio=precio;
    }


    /**
     * @return the titulo
     */
    public String getTitulo() {
        return titulo;
    }

    /**
     * @param titulo the titulo to set
     */
    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    /**
     * @return the precio
     */
    public double getPrecio() {
        return precio;
    }

    /**
     * @param precio the precio to set
     */
    public void setPrecio(double precio) {
        this.precio = precio;
    }
   
}



Codigo CarritoCompras.java:


package logica;

import java.util.ArrayList;
import java.util.Date;

/**
 *
 * @author Alexander Trujillo Moran
 */
public class CarritoCompras {
    private Date fecha;
    private ArrayList<Libro> libros;
   
    public CarritoCompras(){
        fecha=new Date();
        libros=new ArrayList<Libro>();
    }
   
    public void agregarLibro(Libro libro){
        libros.add(libro);
    }
   
    public void eliminarLibro(Libro libro){
       
    }

    /**
     * @return the fecha
     */
    public Date getFecha() {
        return fecha;
    }

    /**
     * @param fecha the fecha to set
     */
    public void setFecha(Date fecha) {
        this.fecha = fecha;
    }
   
   
}



Resultado Final 
Para ejecutar perfectamente el proyecto deberan crear una base de datos en el Gestor de base de datos Mysql con una tabla llamada libro y queda perfectamente muchos saludos gracias...