gpt4 book ai didi

Java EE 过滤器和监听器

转载 作者:行者123 更新时间:2023-12-01 19:17:50 25 4
gpt4 key购买 nike

如果我实现一个Filter,在处理请求之前,它会向浏览器打印日期/时间,如下所示:

@WebServlet(name = "TimedServlet",
urlPatterns =
{
"/timed_servlet"
}, initParams =
{
@WebInitParam(name = "prod", value = "true")
})
class TimedServlet extends HttpServlet
{
@WebFilter(filterName = "Time_F",
urlPatterns =
{
"/timed_servlet"
})
private class Time_F implements Filter
{
private FilterConfig fc;

public void init(FilterConfig filterConfig) throws ServletException
{
fc = filterConfig;
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sd_f = new SimpleDateFormat();

response.getWriter().println(sd_f.format(cal));

chain.doFilter(request, response);
}

public void destroy()
{
fc = null;
}
}

protected void doRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");

try (PrintWriter out = response.getWriter())
{

out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ---</title>");
out.println("</head>");
out.println("<body>");
out.println("PROD");
out.println("</body>");
out.println("</html>");
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doRequest(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doRequest(request, response);
}

public String getServletInfo()
{
return "...";
}
}

浏览器中什么也没有显示,只显示 servlet 输出!

如果我想处理 ServletRequestListener 我如何访问响应对象,以便我可以向用户显示一些信息?

谢谢。

最佳答案

您需要调用 FilterChain#doFilter() 让请求转到 servlet/JSP。否则,您将直接阻止初始请求。

chain.doFilter(request, response);

关于你的第二个问题,没有 ServletRequestListener 不适合。

<小时/>

与具体问题无关,请记住 Filter不一定是在响应中写入内容的正确位置。这样,Servlet/JSP 就没有机会再根据业务需求和/或出现异常情况来控制/更改响应。您可能会面临 IllegalStateException 的风险。服务器日志中的 s。如果要在所有页面中打印日期,则必须在 JSP 端进行。要实现此目的,请将日期存储为请求属性:

String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
request.setAttribute("timestamp", timestamp);
chain.doFilter(request, response);

然后在JSP中显示如下

${timestamp}

(您也可以只存储 new Date() 并使用 JSTL <fmt:formatDate> 来格式化日期)

关于Java EE 过滤器和监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5804783/

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