Search code examples
javajspservletsjakarta-eejava-ee-6

servlet accept null values from checkboxes


enter image description herehere I have a jsp page which allow the user to apply his name, his age and his mastered programming language

<form action="./getPost" method="POST" >

     <label> name </label>      <input type="text" name="name" > <br><br>
     <label> age </label> &nbsp <input type="text" name="age" > <br><br>


    <label> programming langage </label> <br>
    <input type="checkbox" name="fav" value="java"> java <br>
    <input type="checkbox" name="fav" value="php"> php <br>
    <input type="checkbox" name="fav" value="python"> python <br><br>

    <input type="submit" value="submit post">

    </form>

this is how the servlet get the data

        String name = request.getParameter("name");
        String age = request.getParameter("age");
        String[] lang = request.getParameterValues("fav");

            InsertPost.add(new Post(name, age, lang));

when I fill in all the fields of the form and click on the button it inserts the data into the database. then I tested to submit it without selecting any checkbox which caused an error (java.lang.NullPointerException). the issue is that I want to leave this optional means not required if the user wants to pick or not. so how can I make the servlet handles null values ​​from checkboxes


Solution

  • How to solve this issue:

    Option 1: (sending empty string instead of null) Assuming that your table has a not-null constraint on field fav.

    String name = request.getParameter("name");
    String age = request.getParameter("age");
    List<String> lang = request.getParameterValues("fav");
    if(lang==null) {
        lang = new String[] {""};
    }
    InsertPost.add(new Post(name, age, lang));
    //not recommended as it will add 1-byte of empty string even if there is no fav language
    

    Note:

    You should put the InsertPost.add(...) call in a try-catch block to handle exception during inserting data to DB and then show it on UI as a part of best practices. Also, put a check if the name and age are null and handle it.

    Option 2: (sending null and removing null constraint from the table on fav field)

    //how you are doing it previously will work.
    InsertPost.add(new Post(name, age, lang));
    

    Cause of error


    Your database is not expecting null value on filed favorite languages