servlet 接受来自复选框的空值

servlet accept null values from checkboxes

这里我有一个jsp页面,允许用户申请他的名字、他的年龄和他掌握的编程语言

<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>

这就是 servlet 获取数据的方式

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

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

当我填写表单的所有字段并单击按钮时,它会将数据插入数据库。 然后我测试提交它而不选择任何导致错误的复选框(java.lang.NullPointerException)。 问题是,如果用户想要选择,我想保留这个可选的手段。 那么如何让 servlet 处理来自复选框的空值

如何解决这个问题:

选项 1: (发送空字符串而不是 null) 假设您的 table 对字段 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

注:

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.

选项 2: (发送 null 并从 fav 字段的 table 中删除 null 约束)

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

错误原因


您的数据库在提交 favorite languages

时不期望空值

//一个建议:对待null并替换为空字符串

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

希望对你有所帮助