如何在javax.servlet.Filter的doFilter中重定向

时间:2019-04-23 23:23:23

标签: java spring jsf redirect servlet-filters

我使用Spring和JSF进行了第一个学校项目,并且应该重写javax.servlet.Filter的{​​{1}}方法进行访问控制,并在用户无权访问特定URL时进行重定向。我正在使用NetBeans。

WEB-INF / web.xml

doFilter

AuthFilter.java

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

...
<filter>
    <filter-name>AuthFilter</filter-name>
    <filter-class>filters.AuthFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>AuthFilter</filter-name>
    <url-pattern>/faces/views/filtered/auth/*</url-pattern>
</filter-mapping>
...

如果我尝试选项1,它将在package filters; /** * This class checks if an authenticated user is trying to access its url, else redirect */ public class AuthFilter implements javax.servlet.Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpSession session = httpRequest.getSession(); Authenticated authenticated = (Authenticated) session.getAttribute("authenticated"); if (authenticated == null) { //option 1, use ExternalContext ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); try { externalContext.redirect( externalContext.getRequestContextPath() + externalContext.getRequestServletPath() + "/views/filtered/nonauth/login.xhtml"); } catch (Exception e) { e.printStackTrace(); } //option 2 HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendRedirect("../filtered/nonauth/login.xhtml"); } else { chain.doFilter(request, response); } } @Override public void destroy() { } } 上引发空指针异常(BalusC的this answer解释了原因)

OTOH,选项2似乎与位置有关,这意味着它从某些URL起作用,而从其他URL进入无限重定向循环。

我的问题是,将用户重定向到FacesContext页的正确方法是什么,而与他提出未经授权的请求的“位置”无关?

谢谢

0 个答案:

没有答案