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

标签 java spring

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

相关文章:

java - Libgdx - 大约 2 人游戏。我希望每个玩家都可以用一根手指触摸自己的区域

java - 如何根据名称获取类别?

java - 在 JSP EL 表达式中获取 Spring Security Principal

java - 抽屉导航上的 NullPointerException

java - 如何在Java项目中为类文件配置模板

java - 直接将图像添加到JPanel

java - SpringBoot Heroku org.maven.plugins :maven-compiler-plugin:3. 8.1:编译失败

java.math.BigDecimal 无法转换为 [Ljava.lang.Object;

java - 从 Angular 应用程序接收 Spring Controller 上的 URL 参数

Java Spring Controller 断点和 JUnit