如何将响应正文时间戳格式更改为 unix 时间戳?

How can i change my response body timestamp format to unix timestamp?

我有一个异常 class,它用 @ResponseStatus 注释,所以当我抛出这个异常时,会返回一个特定的响应。它工作正常,但我的时间戳有问题:"timestamp":“2019-02-12T13:33:26.540 + 0000”我想在 unix 秒“1550038291”中设置时间戳。我该如何更改,以便在响应中使用毫秒数?

@ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Invalid authorization")
public class AuthorizationException extends RuntimeException {}
{
  "timestamp": "2019-02-12T13:33:26.540+0000",
  "status": 401,
  "error": "Unauthorized",
  "message": "Invalid authorization",
  "path": "/my-endpoint"
}

您可以创建自己的此接口实现以更改响应 - AuthenticationFailureHandler

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler
{
  @Override
  public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException ex) throws IOException, ServletException
  {
    response.setStatus(HttpStatus.UNAUTHORIZED.value());

    Map<String, Object> data = new HashMap<>();
    data.put("timestamp", Calendar.getInstance().getTimeInMillis()); // you can format your date here 
    data.put("status",HttpStatus.UNAUTHORIZED.value());
    data.put("message", "You are not authorized.");
    data.put("path", request.getRequestURL().toString());

    OutputStream out = response.getOutputStream();
    com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, data);
    out.flush();
  }
}

您需要配置此 CustomAuthenticationFailureHandler.java class。

@Configuration
@EnableWebSecurity
@ComponentScan("your.base.package")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
 @Override
protected void configure(final HttpSecurity http) throws Exception {
    http.exceptionHandling().accessDeniedHandler(accessDeniedHandler())
    ;
}

@Bean
public AccessDeniedHandler accessDeniedHandler() {
    return new CustomAuthenticationFailureHandler();
}
}

application.yml

write-dates-as-timestamps= true

result