美文网首页
3、springmvc 自定义Formatter

3、springmvc 自定义Formatter

作者: flyjar | 来源:发表于2022-04-04 07:55 被阅读0次

    1、新建Formatter/**

    • @author pite
      */
      @Component
      public class DataFormatter implements Formatter<LocalDateTime> {
      private final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

      /**

      • 将String解析成LocalDateTime
        */
        @Override
        public LocalDateTime parse(String s, Locale locale) throws ParseException {
        return LocalDateTime.parse(s,DATE_TIME_FORMATTER);
        }

      /**

      • 这个到底是干什么用的,我现在还没有弄明白

      • @param s

      • @param locale

      • @return
        */
        @Override
        public String print(LocalDateTime s, Locale locale) {

        return DATE_TIME_FORMATTER.format(s);
        }
        }

    2、在Controller中使用

    重点:Controller方法中参数,要填写被格式化之后类型。

    @RequestParam是必须要有的,如果没有则不会调用自定义的Formatter

      @GetMapping("notToken")
        @Transactional(rollbackFor = Exception.class)
        public LocalDateTime notToken(@RequestParam LocalDateTime localDateTime) throws Exception {
            return localDateTime;
        }
    
    

    相关文章

      网友评论

          本文标题:3、springmvc 自定义Formatter

          本文链接:https://www.haomeiwen.com/subject/rmbfsrtx.html