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

时间:2015-01-28 11:07:03

标签: java jsp date java-ee

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

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

您是否有任何想法填写日期对象属性?

2 个答案:

答案 0 :(得分:0)

如果值是日期,您可以使用&#34; formatDate&#34;来自JSTL的功能。
您必须以这种方式添加taglib。

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


最后添加一个值的格式,类似于此...

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


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

答案 1 :(得分:0)

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

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