为什么HttpServletRequestWrapper类不是抽象的

时间:2014-03-13 00:01:28

标签: java servlets

这个课程不应该是抽象的吗?如果我直接使用它,无论如何都会给我默认对象,因此我必须继承它并覆盖我关注的方法。我使用它的方式如下:

public class HttpRequestWrapper extends HttpServletRequestWrapper {
    private static final Logger logger = LoggerFactory
            .getLogger(HttpRequestWrapper.class);
    private final byte[] body;
    private static Gson gson = new Gson();

    public HttpRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // Read the request body and save it as a byte array
        InputStream is = super.getInputStream();
        body = IOUtils.toByteArray(is);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStreamImpl(new ByteArrayInputStream(body));
    }

    @Override
    public BufferedReader getReader() throws IOException {
        String encBody = getCharacterEncoding();
        if (encBody != null && encBody != enc) {
            enc = encBody;
        }
        return new BufferedReader(new InputStreamReader(getInputStream(), enc));
    }
        xxxxxxxx more code xxxxxx
 }

我不明白直接创建 HttpServletRequestWrapper 对象的优势因此为什么不抽象?我错过了一些重要的见解吗?包装器周围的包装器(我正在做的事情)是多余的吗?

更新1:我可以使用其他任何库来实现相同的目标吗?

1 个答案:

答案 0 :(得分:0)

这个类使用了Decorator设计模式,它用于包装有效的HttpServletRequest,它使您可以覆盖此类接口的行为。它意味着用期望的行为来装饰类,这就是这个类不能抽象的原因。

请记住,当请求命中服务器时,容器会创建HttpServletRequest的对象实现,此时您无法移动对象内的任何内容,例如方法的实现,这就是您使用具体类HttpServletRequestWrapper进行包装的原因。 / p>

此类通常与过滤器一起使用,以添加一些开箱即用的功能,而无需在servlet中移动代码,请考虑使用拦截过滤器设计模式。包装原始请求并使用doFilter方法将其发送到servlet