【问题标题】:NullPointerException if checkbox is not cheked如果未选中复选框,则为 NullPointerException
【发布时间】:2014-04-28 16:45:41
【问题描述】:

我在 html 中有一个这样的复选框:

 <input type="checkbox" name="subscribe" value="subscribe">Subscribe For Answers</input>

在我的 servlet 中,我通过这样做来获得它的价值:

String checked=new String();
checked=request.getParameter("subscribe");

if(!checked.isEmpty()){
            if(checked.compareTo("subscribe")==0)
            {
                ps.setInt(4, 1);
            }
}
else  {
            ps.setInt(4,0);
}

但如果未选中复选框,则会出现空指针异常。请帮助纠正它。

【问题讨论】:

    标签: java jsp jakarta-ee servlets


    【解决方案1】:

    如果未选中该复选框,则请求将不包含任何subscribe 参数,因此checked 将是null。你想要这样的东西:

    String checked = request.getParameter("subscribe");
    if (checked != null && !checked.isEmpty()) {
        ...
    } else {
        ...
    }
    

    顺便说一句,如果提供了参数值,但不是“订阅”,你真的不想调用ps.setInt(4, ...) 吗?目前,您有三种选择:

    • 未提供:设置为 0
    • 提供并等于“订阅”:设置为 1
    • 否则:不要设置

    (也不清楚你为什么使用String.compare而不是String.equals...)

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-17
      • 2019-02-22
      • 2023-03-16
      相关资源
      最近更新 更多