中文乱码问题

  只需要在web.xml中配置编码过滤器即可

  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--设置编码格式-->
    <init-param>
      <param-name>Encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!--设置request作用域强制使用此编码格式-->
    <init-param>
      <param-name>forceRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <!--设置response作用域强制使用此编码格式-->
    <init-param>
      <param-name>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

或者直接设置request和response都强制使用此编码

    <init-param>
      <param-name>ForceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>

日期类型处理

1、方法一:在类的字段或Controller形参上@DataFormat(pattern="yyyy-MM-dd")

@Setter@Getter@NoArgsConstructor@AllArgsConstructor@ToString
public class Student {
    private String username;
    private String password;
    private List<String> id;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;
}

2、方法二:在Controller类中添加以下代码

@InitBinder
public void initBinderDateType(WebDataBinder binder){
      SimpleDateFormat sdf = new SimpleDateFormat();
      sdf.applyPattern("yyyy-MM-dd");
      binder.registerCustomEditor(java.util.Date.class,new CustomDateEditor(sdf,true));
}

3、方法三:使用@ControllerAdvice注解,该类必须处于能被Spring扫描到的包中。

@ControllerAdvice
public class DateFormatControllerAdvice {
    @InitBinder
    public void initBinderDateType(WebDataBinder binder){
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-dd");
        binder.registerCustomEditor(java.util.Date.class,new CustomDateEditor(sdf,true));
    }
}

 

posted on 2019-09-13 20:28  幸福的小耗子  阅读(401)  评论(0编辑  收藏  举报