Home > front end >  how to insert multiple checkbox values into database?
how to insert multiple checkbox values into database?

Time:05-08

So, I have a form in that i have two check boxes and both can be checked but when i check both the data is not going into database only the first value is inserting.

I tried using getParameterValues, also gave it as an array in bean and also tried some jquery functions but not able to achieve this can some one please help ??

I know there are already many examples out here but none of them worked for me.

I'll add my code below.

This is the controller servlet


import java.io.IOException;
import java.sql.SQLException;
//import java.sql.Timestamp;
//import java.text.DateFormat;
import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.time.LocalDate;
//import java.time.format.DateTimeFormatter;
import java.util.List;
//import java.util.Locale;
//import java.util.TimeZone;

//import java.util.Calendar;
//import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.postgresql.util.PGTimestamp;

@WebServlet("/")
public class ControllerServlet<main_category> extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    private ProductDAO productDAO;

    public ControllerServlet()
    {
        this.productDAO = new ProductDAO();
    }

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {
        String action = request.getServletPath();

        try
        {
            switch (action)
            {
            case "/insert":
                try
                {
                    insertProduct(request, response);
                }
                catch (SQLException ex)
                {
                    throw new ServletException(ex);
                }
                catch (ParseException e)
                {
                    e.printStackTrace();
                }
                break;

            case "/ProductList":
                try
                {
                    listProduct(request, response);
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                catch (ServletException e)
                {
                    e.printStackTrace();
                }
                break;

            case "/delete":
                try
                {
                    deleteProduct(request, response);
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                break;

            case "/edit":
                try
                {
                    showCreateProduct(request, response);
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                catch (ServletException e)
                {
                    e.printStackTrace();
                }
                break;

            case "/update":
                try
                {
                    updateProduct(request, response);
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                catch (ServletException e)
                {
                    e.printStackTrace();
                }
                catch (ParseException e)
                {
                    e.printStackTrace();
                }
                break;
            default:
                try
                {
                    RequestDispatcher rd = request.getRequestDispatcher("URL.jsp");
                    
                    rd.forward(request, response);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                } 
                catch (ServletException e)
                {
                    e.printStackTrace();
                }
                break;
            }
        } 
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    public void insertProduct(HttpServletRequest request, HttpServletResponse response)throws SQLException, IOException, ClassNotFoundException, ServletException, ParseException
    {       
        String code = request.getParameter("code");        
        String name = request.getParameter("name"); 
        int price = Integer.parseInt(request.getParameter("price"));
        String home_main_category = request.getParameter("home_main_category");
        String home_sub_category = request.getParameter("home_sub_category");
        String p_avail = request.getParameter("p_avail");
        String p_act = request.getParameter("p_act");      // This is the checkbox
        String pro_exp_date = request.getParameter("pro_exp_date");
        String pro_manufacture_date = request.getParameter("pro_manufacture_date");
         
        Product newProduct = new Product(code,name,price,home_main_category,home_sub_category,p_avail,p_act,pro_exp_date,pro_manufacture_date);
        
        try 
        {
            productDAO.insertProduct(newProduct);
        }
        
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        
        RequestDispatcher rd = request.getRequestDispatcher("CreateProduct.jsp");
        
        rd.forward(request,response);
    }

    public void listProduct(HttpServletRequest request, HttpServletResponse response)throws SQLException, IOException, ServletException, ClassNotFoundException
    {
        List<Product> listProduct = productDAO.selectAllProducts();

        request.setAttribute("listProduct", listProduct);

        RequestDispatcher rd = request.getRequestDispatcher("ProductList.jsp");
        
//      System.out.println(" "   listProduct );

        rd.forward(request, response);
    }

    public void deleteProduct(HttpServletRequest request, HttpServletResponse response)throws SQLException, IOException, ClassNotFoundException, ServletException
    {
        int id = Integer.parseInt(request.getParameter("id"));

        productDAO.deleteProduct(id);

        RequestDispatcher rd = request.getRequestDispatcher("ProductList");

        rd.forward(request, response);
    }

    public void showCreateProduct(HttpServletRequest request, HttpServletResponse response)throws SQLException, IOException, ClassNotFoundException, ServletException
    {
        int id = Integer.parseInt(request.getParameter("id"));

        Product existingProduct = productDAO.selectProduct(id);

        RequestDispatcher rd = request.getRequestDispatcher("CreateProduct.jsp");

        request.setAttribute("product", existingProduct);

        rd.forward(request, response);
    }

    public void updateProduct(HttpServletRequest request, HttpServletResponse response)throws SQLException, IOException, ClassNotFoundException, ServletException, ParseException
    {
        int id = Integer.parseInt(request.getParameter("id"));
        String code = request.getParameter("code");
        String name = request.getParameter("name");
        int price = Integer.parseInt(request.getParameter("price"));
        String home_main_category = request.getParameter("home_main_category");
        String home_sub_category = request.getParameter("home_sub_category");
        String p_avail = request.getParameter("p_avail");
        String p_act = request.getParameter("p_act");                // This is the checkbox
        String pro_exp_date = request.getParameter("pro_exp_date");
        String pro_manufacture_date = request.getParameter("pro_manufacture_date");

        Product product = new Product(id, code, name, price, home_main_category, home_sub_category, p_avail, p_act, pro_exp_date, pro_manufacture_date);

        productDAO.updateProduct(product);

        RequestDispatcher rd = request.getRequestDispatcher("CreateProduct.jsp");

        rd.forward(request, response);
    }
}   

This is my DAO


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
//import java.util.Date;

public class ProductDAO
{   
    public void insertProduct(Product product) throws SQLException, ClassNotFoundException
    {
        Connection conn = DatabaseConnection.initializeDatabase();
        
        String query = "insert into productlist (code,name,price,home_main_category,home_sub_category,p_avail,p_act,pro_exp_date,pro_manufacture_date) values(?,?,?,?,?,?,?,?,?)";
        
        try
        {           
            PreparedStatement prestmt = conn.prepareStatement(query);
            
            prestmt.setString(1,product.code);
            prestmt.setString(2,product.name);
            prestmt.setInt(3,product.price);
            prestmt.setString(4,product.home_main_category);
            prestmt.setString(5,product.home_sub_category);
            prestmt.setString(6,product.p_avail);
            prestmt.setString(7,product.p_act);     // this is the checkbox
            prestmt.setString(8, product.pro_exp_date);
            prestmt.setString(9,product.pro_manufacture_date);
            
            System.out.println("Product is added to Database");
             
            prestmt.executeUpdate();
            
        } 
         
        catch (SQLException e) 
        {
            e.printStackTrace();
        }       
    }

    public List<Product> selectAllProducts() throws SQLException, ClassNotFoundException
    {
        List<Product> listProduct = new ArrayList<>();
        
        
        Connection conn = DatabaseConnection.initializeDatabase();
        
        String query = "select * from productlist";
        
        try
        {
            PreparedStatement prestmt = conn.prepareStatement(query);
             
            ResultSet rs = prestmt.executeQuery();
             
             while (rs.next())
             {   
                 int id = rs.getInt("id");                           
                 String code = rs.getString("code");
                 String name = rs.getString("name");
                 int price = rs.getInt("price");
                 String home_main_category = rs.getString("home_main_category");
                 String home_sub_category = rs.getString("home_sub_category");
                 String p_avail = rs.getString("p_avail");
                 String p_act = rs.getString("p_act");      // this is the checkbox
                 String pro_exp_date = rs.getString("pro_exp_date"); 
                 
                 String pro_manufacture_date = rs.getString("pro_manufacture_date");
                
       
                 listProduct.add(new Product(id,code,name,price,home_main_category,home_sub_category,p_avail,p_act,pro_exp_date,pro_manufacture_date));
             }  
         //    System.out.println(" "   listProduct );
             
                 System.out.println("Product List is Displayed");
        } 
         
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
        
        return listProduct;        
    }
     
    public boolean deleteProduct(int id) throws SQLException, ClassNotFoundException
    {   
        boolean rowDeleted = false;
        
        Connection conn = DatabaseConnection.initializeDatabase();
        
        String query = "delete from productlist where id = ?";
        
        try
        {           
            PreparedStatement prestmt = conn.prepareStatement(query);
        
            prestmt.setInt(1,id);
            
            rowDeleted = prestmt.executeUpdate() > 0;
        }
        
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        
        System.out.println("Product is Deleted Successfully");
        
        return rowDeleted;
    }
    
    public Product selectProduct(int id) throws ClassNotFoundException, SQLException
    {
        Product product = null;
        
        Connection conn = DatabaseConnection.initializeDatabase();
        
        String query =  "select * from productlist where id = ?";
    
        try
        {           
            PreparedStatement prestmt = conn.prepareStatement(query);
    
            prestmt.setInt(1,id);
        
            ResultSet rs = prestmt.executeQuery();
            
            while (rs.next())
             {  
                String code = rs.getString("code");
                String name = rs.getString("name");
                int price = rs.getInt("price");
                String home_main_category = rs.getString("home_main_category");
                String home_sub_category = rs.getString("home_sub_category");
                String p_avail = rs.getString("p_avail");
                String p_act = rs.getString("p_act");       // this is the checkbox
                String pro_exp_date = rs.getString("pro_exp_date");
                String pro_manufacture_date = rs.getString("pro_manufacture_date");
                
                product = new Product(id,code,name,price,home_main_category,home_sub_category,p_avail,p_act,pro_exp_date,pro_manufacture_date);
             }  
        }
    
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        
        System.out.println("Product Details are Being Edited");
        
        return product;
    }
    
    public boolean updateProduct(Product product) throws SQLException, ClassNotFoundException
    {
        boolean rowUpdated = false;
        
        Connection conn = DatabaseConnection.initializeDatabase();
        
        String query = "update productlist set code = ?, name = ?, price = ?, home_main_category = ?, home_sub_category = ?, p_avail = ?, p_act = ?, pro_exp_date = ?, pro_manufacture_date = ? where id = ? ";  
        
        try
        {
            PreparedStatement prestmt = conn.prepareStatement(query);
                                                                                                                                                
            prestmt.setString(1,product.code);
            prestmt.setString(2,product.name);
            prestmt.setInt(3,product.price);
            prestmt.setString(4,product.home_main_category);
            prestmt.setString(5,product.home_sub_category);
            prestmt.setString(6,product.p_avail);
            prestmt.setString(7,product.p_act);     // this is the checkbox
            prestmt.setString(8,product.pro_exp_date);
            prestmt.setString(9,product.pro_manufacture_date);
            prestmt.setInt(10,product.id);
            
            rowUpdated = prestmt.executeUpdate() > 0;
            
            System.out.println("Product Details are Updated in the Database");  
        }
        
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
        
        return rowUpdated;  
    }
}


This is what i added in my JSP i am using Semantic UI.


<div class = "error_placement_checkbox">
        <div align = "center"  id = "idcheckbox">
            <div align = "center" >
                <label> Product Availability </label>
                    <div >
                        <div >
                            <input type = "checkbox" name = "p_act" value = "In_Stock" >
                            <label> In Stock </label>
                        </div>
                    </div>
                    <div >
                        <div >
                            <input type = "checkbox" name = "p_act" value = "Out_Of_Stock" >
                                <label> Out Of Stock </label>
                        </div>
                    
                    </div>
            </div>
        </div>
        </div>

CodePudding user response:

I guess, the problem is with duplicated name in form - p_act:

 <input type = "checkbox" name = "p_act" value = "In_Stock" >
 <input type = "checkbox" name = "p_act" value = "Out_Of_Stock" >

I think you should do separate names for each position (like p_act1, p_act2) and concat them somehow. For example:

String p_act = Stream.of(request.getParameter("p_act1"), request.getParameter("p_act2"))
   .filter(Objects::nonNull)
   .collect(Collectors.joining(","))
  • Related