我的 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/