java - 为什么类型转换会发生这种情况?

标签 java spring-mvc

我是 springMVC 的新手,今天我写了一个 DateConverter 像这样

public class DateConverter implements Converter<String,Date>{

    private String formatStr = "";

    public DateConverter(String fomatStr) {
        this.formatStr = formatStr;
    }

    public Date convert(String source) {
        SimpleDateFormat sdf = null;
        Date date = null;
        try {
            sdf = new SimpleDateFormat(formatStr);
            date = sdf.parse(source);
        } catch (ParseException e) {
                e.printStackTrace();
            }
        return date;

    }
}

然后我写一个像这样的 Controller

@RequestMapping(value="/converterTest") 
public void testConverter(Date date){
    System.out.println(date);
}

将其配置到 applicationContext,当我使用测试转换器时,我确信 DateConverter 已正确初始化

http://localhost:8080/petStore/converterTest?date=2011-02-22

the browser says:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect ().

有人可以帮我吗?提前致谢

最佳答案

您的转换器中有拼写错误。您拼错了构造函数参数,因此赋值无效。而不是:

public DateConverter(String fomatStr) {
    this.formatStr = formatStr;
}

尝试:

public DateConverter(String formatStr) {
    this.formatStr = formatStr;
}

可能还有其他问题,但至少您需要解决该问题。我假设您使用 yyyy-MM-dd 作为日期格式?

关于java - 为什么类型转换会发生这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17914390/

相关文章:

java - 如何在 Spring 框架中将多个输入存储到数组中

java - 由于某种原因,Apache POI Cellstyle 在第 41 行之后不适用

java - 在比较 boolean 值之前先完成 asynctask 的执行

java - 当屏幕改变方向时会调用什么?当我改变方向时我的应用程序正在重新启动

java - 正则表达式为什么当这里有两个组时负前瞻不起作用

java - Spring Security验证用户进入admin

java - Gradle中如何生成资源文件

java - 注入(inject)持久依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException

java - 更新端点的响应对象

spring-mvc - Spring Boot + React.js Axios : 403 Forbidden for HTTP POST calls