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

时间:2019-02-13 06:13:39

标签: java spring rest exception response

我有一个用@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"
}

2 个答案:

答案 0 :(得分:2)

application.yml

write-dates-as-timestamps = true

result

答案 1 :(得分:0)

您可以创建自己的接口实现,以更改响应  -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类。

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