Search code examples
javajspservletssemantic-ui

how to insert multiple checkbox values into database?


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

    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);
    }

Solution

  • 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(","))