【问题标题】:Spring taking String input from web page and converting into LocalDate conversion ErrorSpring从网页获取字符串输入并转换为LocalDate转换错误
【发布时间】:2018-08-25 18:17:45
【问题描述】:

我收到这个错误,你能找出我做错了什么吗?

无法将“java.lang.String”类型的值转换为所需类型 java.time.LocalDate' 嵌套异常是 java.lang.IllegalStateException:无法转换类型的值 'java.lang.String' 到所需类型'java.time.LocalDate':没有匹配 找到编辑器或转换策略。

package com.pc.controller;

import java.time.LocalDate;
import java.util.Map;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class Controllera {

@RequestMapping(value="/home.htm",method=RequestMethod.GET)
public String showForm() {
    System.out.println("Controllera.showForm()");
    return "welcome";
}

@RequestMapping(value="/home.htm",method=RequestMethod.POST)    
public String process(Map<String ,Object>map,@RequestParam("date") 
                     @DateTimeFormat(pattern="dd-MM-yyyy") LocalDate date) {
    System.out.println("Controllera.process()");
    System.out.println(date);
    map.put("date",date);
    return "success";
}
}

//end of controller


My web page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<form method="POST">
<input type="text" name="date" id="date"/><br>
<input type="submit"/>
</form >

【问题讨论】:

  • 我建议您将date 参数定义为字符串并在process(...) 处理程序中进行转换

标签: spring-mvc


【解决方案1】:

在 Html 中默认日期格式是 YYYY-MM-YY。

你有两个解决方案:

1 - 更改您的参数,例如 @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date

你的控制器方法也应该是:

@RequestMapping(value="/home.htm",method=RequestMethod.POST)    
public String process(Map<String ,Object> map, @RequestParam("date") 
                     @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {

// omitted for brevity.

 }
}

2 - 或者您可以在 JSP 中执行此操作,您需要检查 this

【讨论】:

  • 但我收到用户的 dd-MM-yyyy 模式
  • 对不起,我听不懂。解决方案解决了您的问题吗?
  • 而且 java.time api 也没有 customPropertyEditor。所以我想我必须使用 java.util.date 和 @InitBinder
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 2021-02-15
  • 1970-01-01
  • 2013-01-05
  • 1970-01-01
相关资源
最近更新 更多