将日期字符串转换为 JSP 中的日期对象

Convert date string to Date object in JSP

我有一个表单,其中包含与某个对象相关的某些属性。 在这个对象中,我有一个日期对象,在我的表单中,我像字符串一样恢复它。 是否可以用字符串填充日期对象?

JSP 表格声明:

<form:form method="POST" action="/netmg/controller/device/search/" modelAttribute="device"> 

JSP 字符串值为:

<tr>
                <td class="label"><spring:message code="device.endDate" /></td>
                <td class="value">
                    <form:input path="endDate" cssClass="datepickerMe" />
                    <form:errors path="endDate" cssClass="errormsg" />
                </td> 
            </tr>

然后我在我的控制器中像这样恢复它:

/**
 *
 * @param device
 * @param bindingResult
 * @param uiModel
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String findDevicesByCriteria(@Valid @ModelAttribute Device device, BindingResult bindingResult, Model uiModel) {
    if (isCriteriaEmpty(device)) {
        uiModel.addAttribute("criteriaEmptyWarning", "error_search_criteria_empty");
        return ViewConstants.DEVICE_SEARCH_VIEW;
    }
    List<IDevice> deviceList = identityService.searchDevices(device.getSerialNumber(), device.getOwner(), device.getIpAdress(), device.getInstallDate(), device.getEndDate());
    if (deviceList.size() == 0) {
        uiModel.addAttribute(WebConstants.NO_RESULT, true);
    }
    uiModel.addAttribute(WebConstants.DEVICE_LIST, deviceList);
    return ViewConstants.DEVICE_SEARCH_VIEW;
}

您有什么想法可以填充日期对象属性吗?

如果值为日期,您可以使用 JSTL 中的 "formatDate" 函数。
您必须以这种方式添加标签库。

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>


最后为值添加格式,类似于此...

<fmt:formatDate value="${ojbect.date}" pattern="dd/MM/yyyy" />


我希望它对你有用。
问候。

在 POSTController 中,您可以将字符串(日期)解析为日期对象,如下所示:Parse String to Date 或者您可以将 JSP 输入设置为日期。

 <form:input type="datetime-local" path="endDate" cssClass="datepickerMe" />