gpt4 book ai didi

java - 在创建自定义 HttpServletResponse 方面需要帮助

转载 作者:搜寻专家 更新时间:2023-11-01 02:54:19 28 4
gpt4 key购买 nike

突然停滞在生成自定义 servlet 响应上。我想用预定义的替换 servlet 响应:

public class MyCustomResponse extends HttpServletResponseWrapper {
private String customOutput;
public MyCustomResponse(String customOutput, HttpServletResponse response) {
super(response);
// PrintWriter and Outputstream should stream this variable as output
this.customOutput = customOutput;
}

//
// Below I need to override something
//
}

过滤代码如下:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//
//
MyCustomResponse customResponse = new MyCustomResponse("Hello world!", (HttpServletResponse) response);
chain.doFilter(request, customResponse);
}

真可惜,但我真的坚持编写这个简单的任务:(

如有任何帮助,我们将不胜感激。

更新:

我想要的只是实现自定义响应包装器,一旦将其放入过滤器链中,它就会始终以一些预定义的文本进行响应。我知道如何从 doFilter() 方法中编写自定义数据,但我希望 MyCustomResponse 对此负责 - 只需实例化并放入链中。也欢迎任何有充分理由的回答“你不能那样做,因为......”。

最佳答案

如您的评论之一所述:

"I want my custom response to return a string in response to getWriter or getOutputStream method invocation"

为此,您必须通过覆盖它们来为 getWriter() 和 getOutputStream() 提供您自己的实现。

//---

private PrintWriter printWriter = null;
private ServletOutputStream outputStream = null;

public PrintWriter getWriter( ) throws IOException {

if (this.outputStream != null) {
throw new IllegalStateException(
"Cannot call getWriter( ) after getOutputStream( )");
}

if (this.printWriter == null) {
// initialize printWriter
}
return this.printWriter;
}

public ServletOutputStream getOutputStream( ) throws IOException {

if (this.printWriter != null) {
throw new IllegalStateException(
"Cannot call getOutputStream( ) after getWriter( )");
}

if (this.outputStream == null) {
// initialize outputStream
}
return this.outputStream;
}

//---

关于java - 在创建自定义 HttpServletResponse 方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4712920/

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