How to insert a data from one table to another table selecting it for a combobox?

丶灬走出姿态 提交于 2020-01-26 04:26:11

问题


  • I tried inserting data for selecting product class idcat class category with a combo but nothing any ideas please

  • -CLASSES

    public class Categoria {

    private int idcat;
    private String name;
    private String descrip;
    

    }

    public class Producto {

    private int producto;
    private int idcategoria;
    private String nombre;
    private String descrip;
    

    }

    -DAO CLASS CategoriaDAO

    public Collection listarIdCat() throws DAOExcepcion{

        Collection<Categoria> c=new ArrayList<Categoria>();
        String query="SELECT id_categoria from categoria ";
        Connection con=null;
        PreparedStatement stmt=null;
        ResultSet rs=null;
    
        try {
            con=ConexionBD.obtenerConexionDirecta();
            stmt=con.prepareStatement(query);
            rs=stmt.executeQuery();
            while(rs.next()) {
                Categoria vo=new Categoria();
                vo.setIdcat(rs.getInt("id_categoria"));
                c.add(vo);
    
            }
    
        } catch (SQLException e) {
            System.err.println(e.getMessage());
            throw new DAOExcepcion(e.getMessage());
        }finally{
    
            this.cerrarStatement(stmt);
    
            this.cerrarResultSet(rs);
            this.cerrarConexion(con);
        }
        return c;
    }
    
  • DAO CLASS ProductoDAO

public void insertar(Producto vo) throws DAOExcepcion {

>     
>             String query = "INSERT INTO producto(id_categoria,nombre,descripcion) VALUES ((SELECT id_categoria
> FROM categoria WHERE id_categoria=?),?,?,?)";
>             Connection con = null;
>             PreparedStatement stmt = null;
>     
>             try {
>                 con = ConexionBD.obtenerConexionDirecta();
>                 stmt = con.prepareStatement(query);
>                 stmt.setInt(1, vo.getIdcat());
>                 stmt.setString(2, vo.getNombre());
>                 stmt.setString(3, vo.getDescrip());
>                 int i = stmt.executeUpdate();
>                 if (i != 1) {
>                     throw new SQLException("No se pudo insertar");
>                 }
>             } catch (SQLException e) {
>                 System.err.println(e.getMessage());
>                 throw new DAOExcepcion(e.getMessage());
>             } finally {
>                 this.cerrarStatement(stmt);
>                 this.cerrarConexion(con);
>             }
>     
>         }
  • NEGOCIO CLASS CategoriaNegocio

    public class CategoriaNegocio {

    public Collection<Categoria> listarIdCat()throws DAOExcepcion{
    
        CategoriaDAO dao=new CategoriaDAO();
    
        Collection<Categoria> lista=dao.listarIdCat();
    
        return lista;
    
    }
    

    }

  • NEGOCIO CLASS ProductoNegocio

    public void insertarProducto(int idCat, String nom, String descrip,
                double prec, int stock, String image) throws DAOExcepcion {
    
            Producto p = new Producto();
            p.setIdcat(idCat);
            p.setNombre(nom);
            p.setDescrip(descrip);
            ProductoDAO dao = new ProductoDAO();
            try {
                dao.insertar(p);
            } catch (DAOExcepcion e) {
                throw e;
            }
    
        }
    
  • SERVLET InsertarProdServlet

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

      CategoriaNegocio negocio = new CategoriaNegocio();

      try {

          Collection<Categoria> lista = negocio.listarIdCat();

          request.setAttribute("IDCATEGORIA", lista);

      } catch (DAOExcepcion e) {

          System.out.println(e.getMessage());
      }
      RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/insertar.jsp");
      rd.forward(request, response);

  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      String id=request.getParameter("tid_cat");
      int idcat=Integer.parseInt(id.trim());

      String nom=request.getParameter("tnomprod");
      String des=request.getParameter("tdesprod");



      ProductoNegocio negocio=new ProductoNegocio();

      try {
          negocio.insertarProducto(idcat, nom, des);
          request.setAttribute("MENSAJE", "Se inserto correctamente");
          RequestDispatcher rd=request.getRequestDispatcher("/insertar.jsp");
          rd.forward(request,response);


      } catch (DAOExcepcion e) {

          request.setAttribute("MENSAJE_ERROR", "Hubo problemas");
          RequestDispatcher rd=request.getRequestDispatcher("/error.jsp");
          rd.forward(request,response);
      }


  }

JSP insertar

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="InsertarProdServlet" method="post">

<table><caption>Inserte Producto</caption>
<tr>
<td align="center"><select name="tid_cat" size="1" >  
<c:forEach items="${IDCATEGORIA}" var="c" >  
<option value="${c.idcategoria}" >${c.idcategoria}</option>  
</c:forEach>  
</select></td><td>
</td>
</tr>
<tr>
<td>NOMBRE</td><td><input type="text" name="tnomprod"> </td></tr><tr>
<td>DESCRIPCION</td><td><input type="text" name="tdesprod" > </td></tr><tr>
<td><input type="submit" value="INSERTAR">   </td></tr><tr>
</tr>
</table>
</form>
${MENSAJE}
</body>
</html>

回答1:


You have to access to your application through the Servlet like http://localhost/YouWebAppName/InsertarProdServlet, this will invoke a GET request (thus executing the doGet function) and will set the request attributes. Then it will forward to your insertar.jsp page and when clicking on the submit, it will invoke a POST request (thus executing the doPost function).

As a side note, next time don't post that code wall, or nobody will read your questions, just post a SSCCE of your code showing where might be the problem. En mi opinión, cuando vi tu pregunta ni me dieron ganas de leerla por solo ver tanto código que no forma parte del problema concreto (IMO, when I saw your question I didn't want to read it just to see all the code that's not part of the real problem).



来源:https://stackoverflow.com/questions/14984371/how-to-insert-a-data-from-one-table-to-another-table-selecting-it-for-a-combobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!