【问题标题】:Convert date string to Date object in JSP在JSP中将日期字符串转换为日期对象
【发布时间】:2015-01-28 11:07:03
【问题描述】:

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

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

你有什么想法来填充日期对象属性吗?

【问题讨论】:

    标签: java jsp date jakarta-ee


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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


      最后为 value 添加一个格式,类似于这个......

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


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

      【讨论】:

      • @amarcarrilla 谢谢你的回复,我只需要替换我的表单:input by ?
      猜你喜欢
      • 2020-05-21
      • 2020-11-30
      • 2016-05-24
      • 1970-01-01
      • 2011-03-07
      • 2012-01-28
      • 1970-01-01
      • 2011-10-25
      相关资源
      最近更新 更多