繁体   English   中英

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

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

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

application.yml

write-dates-as-timestamps = true

结果

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM