gpt4 book ai didi

java - 我如何在 Spring 发送自己的回复?

转载 作者:行者123 更新时间:2023-11-29 04:29:02 27 4
gpt4 key购买 nike

我在我的应用程序中使用 JWT 实现 Spring 安全性,每当进行未经授权的调用时,它都会返回以下响应

@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {

response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

响应 json 如下所示

{
"timestamp": 1497832267379,
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/path"
}

除此之外,我还可以发送我自己的自定义响应,例如:

{
"code":401,
"message":"The request is unauthorized"

}

感谢任何帮助

编辑

我将代码更新为以下格式:

 @Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {

//response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");

Status unauthorizedEntry = new Status();
unauthorizedEntry.setCode(401);
unauthorizedEntry.setMessage("Unauthorized Entry");
Map<String, Object> unauthorizedEntryResponse = new HashMap<>();
unauthorizedEntryResponse.put("status", unauthorizedEntry);
objectMapper.writeValue(response.getOutputStream(), unauthorizedEntry);
response.flushBuffer();
}

我的状态类如下:

public class Status {

int code;
String message;

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}

现在我收到 200 响应,但屏幕上没有显示任何内容。它是完全空白的。感谢您的帮助!

最佳答案

你可以尝试添加一个controller advice

@RestController
@ControllerAdvice
public class ExceptionHandlerController {

@ExceptionHandler(UsernameNotFoundException.class, DataAccessException.class)
@ResponseStatus(HttpStatus.SC_UNAUTHORIZED)
@ResponseBody ErrorInfo
UnauthorizeExceptionInfo(HttpServletRequest req, Exception ex) {
return new ErrorInfo(req.getRequestURL(), ex);
}
}

和ErrorInfo.class

@JsonIgnore
public final StringBuffer url;
public final String ex;

public ErrorInfo(StringBuffer stringBuffer, Exception ex) {
this.url = stringBuffer;
this.ex = ex.getLocalizedMessage();
}

当您抛出新的 UsernameNotFoundException 时, Controller 将处理响应。

而且我想如果密码/电子邮件不匹配,异常会从 CustomUserDetailsS​​ervice 中的 @Override public loadUserByUsername 中抛出。

此处有更多详细信息:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

关于java - 我如何在 Spring 发送自己的回复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44620783/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com