You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拆分HTML表单请求参数?Java时间转换遇500错误求助

问题分析与解决方案

一、500错误的原因及修复

你的代码在页面首次加载时,request.getParameter("time")会返回null(此时还未提交表单),直接调用split(":")会触发NullPointerException,导致500错误。

修复方法:先判断参数是否为空再处理:

<%
String time = request.getParameter("time");
String[] split = null;
if (time != null && !time.isEmpty()) {
    split = time.split(":");
}
%>

二、HTML时间数据的Java转换方案

HTML type="time" 控件提交的格式是标准的HH:mm(24小时制,比如14:30),推荐使用Java 8及以上的DateTimeFormatter(线程安全,比SimpleDateFormat更可靠)来解析:

// 放在JSP脚本段中的示例代码
if (time != null && !time.isEmpty()) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
    LocalTime localTime = LocalTime.parse(time, formatter);
    // 后续可基于localTime做业务处理,比如格式转换、时间计算等
}

如果必须使用SimpleDateFormat,同样要先做非空判断:

if (time != null && !time.isEmpty()) {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    Date date = sdf.parse(time);
    // 后续处理date对象
}

三、请求参数拆分的注意事项

  • 拆分前必须校验参数是否为null或空字符串,避免抛出异常
  • 若时间格式固定为HH:mm,split(":")会将其拆分为小时和分钟两个元素,可直接通过索引获取:
if (split != null) {
    String hour = split[0];
    String minute = split[1];
    // 使用小时、分钟数据
}

内容的提问来源于stack exchange,提问作者Divano Cromato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:54:10