SpringMVC Chinese garbled date and type of treatment

Chinese garbage problem

  Only you need to configure the encoding filter in web.xml

  < Filter > 
    < filter-name > characterEncodingFilter </ filter-name > 
    < filter-class > org.springframework.web.filter.CharacterEncodingFilter </ filter-class > 
    <-! Set coding format -> 
    < the init-param > 
      < param-name > encoding </ param-name > 
      < param-value > UTF-. 8 </ param-value > 
    </ the init-param > 
    <-! set request scope enforce this encoding format ->
    <param-the init > 
      < param-name > forceRequestEncoding </ param-name > 
      < param-value > to true </ param-value > 
    </ the init-param > 
    <-! disposed response scope enforce this encoding format -> 
    < the init-param > 
      < param-name > forceResponseEncoding </ param-name > 
      < param-value > to true </ param-value > 
    </ the init-param > 
  </ filter >
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

Or directly request and response force the use of this encoding

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

Date Type processing

1, Method a: Controller class parameter field or on @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. Method Two: Add the following code class 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. Method 3: Use @ControllerAdvice annotations, Spring class must be scanned in the package.

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

 

Guess you like

Origin www.cnblogs.com/xfdhh/p/11517575.html