如何重定向到过滤器中的引荐来源网址?

发布于 2024-11-08 00:49:35 字数 98 浏览 0 评论 0原文

如何在过滤器中执行重定向到调用该过滤器的 servlet 或 jsp。实际上,我想检查用户是否没有权限查看某些内容,然后,在尝试获取禁止资源时,用户将停留在他尝试获取该资源的页面上。

how can I perform a redirect in filter to the servlet or jsp from which this filter has been called. Actually, I want to check if the user have not permition to see some content, then, while trying to get a forbbiden resourse, the user will stay at the page from where he have tried to get that resource.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若相惜即相离 2024-11-15 00:49:35

doFilter()方法,需要对获取到的ServletResponse 参数 HttpServletResponse 然后调用sendRedirect()方法就可以了。请求发起的页面可以通过 referer 请求头获取(是的,有传说中的拼写错误),可以通过 HttpServletRequest#getHeader() 转换后它来自 ServletRequest 论证。

if (userHasPermission) {
    chain.doFilter(request, response);
} else {
    String referrer = ((HttpServletRequest) request).getHeader("referer");
    ((HttpServletResponse) response).sendRedirect(referrer);
}

请注意,引荐来源网址是客户端控制的值,因此可能会被欺骗甚至删除。您希望对获取的值添加条件检查,当不存在或无效时,重定向到主页或其他地方。

另请参阅:

In the doFilter() method, you need to cast the obtained ServletResponse argument to HttpServletResponse and then call the sendRedirect() method on it. The page where the request originated can be obtained by the referer request header (yes, with the legendaric misspelling) which can be obtained by HttpServletRequest#getHeader() after casting it from the ServletRequest argument.

if (userHasPermission) {
    chain.doFilter(request, response);
} else {
    String referrer = ((HttpServletRequest) request).getHeader("referer");
    ((HttpServletResponse) response).sendRedirect(referrer);
}

Please note that the referrer is a client-controlled value and thus this can be spoofed or even removed. You'd like to add conditional checks on the obtained value and when absent or invalid, redirect to the main page instead or somewhere else.

See also:

  • Our servlet-filters wiki page (you can get this page by putting your mouse above the tag below the question until a popbox shows and then click the info link on the popbox)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文