gpt4 book ai didi

java - 使用@RequestBody 并转发到另一个端点会抛出异常 Stream closed

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:40 27 4
gpt4 key购买 nike

我的 Java spring REST API Controller 如下所示:

public void signup(@RequestBody RequestBody requestBody) throws IOException, ServletException {

我得到这个异常:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Stream closed; nested exception is java.io.IOException: Stream closed

发生这种情况是因为我想将请求主体转换为 RequestBody 类(它打开请求输入流并完成它),并将其转发/重定向到另一个端点。

实际控制人为:

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
public void signup(@RequestBody CustomUserDetails user, HttpServletRequest request, HttpServletResponse response) {

String userName = user.getUsername();
logger.debug("User signup attempt with username: " + userName);

try{
if(customUserDetailsService.exists(userName))
{
logger.debug("Duplicate username " + userName);
userName + " already exists");
String newUrl = "login";
RequestDispatcher view = request.getRequestDispatcher(newUrl);
view.forward(request, response);
} else {
customUserDetailsService.save(user);
authenticateUserAndSetSession(user, response);
}
} catch(Exception ex) {

}
}

我该如何处理?

最佳答案

您可以在 ExceptionHandler 中转发到登录页面,如下所示:

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public void signup(@RequestBody CustomUserDetails user, HttpServletResponse response) {

String userName = user.getUsername();
logger.debug("User signup attempt with username: " + userName);

//try{
if (customUserDetailsService.exists(userName)) {
logger.debug("Duplicate username " + userName);
throw new SignupException(userName + " already exists");
} else {
customUserDetailsService.save(user);
authenticateUserAndSetSession(user, response);
}
/*} catch(Exception ex) {

}*/
}

在同一个Controller中定义一个ExceptionHandler:

@ExceptionHandler(SignupException.class)
public String duplicateName() {
return "login";
}

SignupException 可能是这样的:

public class SignupException extends RuntimeException {
public SignupException(String message) {
super(message);
}

public SignupException() {
}
}

关于java - 使用@RequestBody 并转发到另一个端点会抛出异常 Stream closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862778/

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