# 开发常见问题

# 流只能读一次的原因

使用 Spring Boot 框架来做 web 开发的核心是 DispatcherServlet,也就是使用 Servlet 来进行网络请求的处理,会从 HttpServletRequest 中获取请求参数等信息。通过HttpServletRequest获取流的代码片:

try {
    ServletInputStream stream = request.getInputStream();
} catch (IOException e) {
    e.printStackTrace();
}
1
2
3
4
5

可知会返回一个 ServletInputStream,类继承关系为:

public abstract class ServletInputStream extends InputStream {...}

public abstract class InputStream implements Closeable {...}

public interface Closeable extends AutoCloseable {...}
1
2
3
4
5

查看 InputStream 的源码可知,读取流的时候会根据 position 来获取当前位置,并且随着读取来进行位置的移动。如果想要重新读取,可以调用 inputstream.reset 方法,但是能否 reset 取决于 markSupported 方法,返回 true 可以 reset,反之不行。查看 ServletInputStream 可知,这个类并没有复写 markSupported 和 reset 方法,查看父类 InputStream:

public boolean markSupported() {
    return false;
}
public synchronized void reset() throws IOException {
    throw new IOException("mark/reset not supported");
}
1
2
3
4
5
6

可知 ServletInputStream 不支持 reset,故这个流只能读取一次。

# JsonProperty 失效

@JsonProperty 无法用于 Content-Type:application/x-www-form-urlencoded,因为它就不是 JSON,所以不能工作。

几种解决方式 (opens new window)

# 讨论区

由于评论过多会影响页面最下方的导航,故将评论区做默认折叠处理。

点击查看评论区内容,渴望您的宝贵建议~
Last Updated: 6/2/2023, 4:13:05 PM