【问题标题】:my servlet mapping spoil my filter我的 servlet 映射破坏了我的过滤器
【发布时间】:2014-10-23 04:09:41
【问题描述】:

在我的程序中,/Controller/* 形式的任何 url 都被我的 servlet 映射重定向到 Controller 类。

我尝试为身份验证添加过滤器,如果用户未登录且路径不是/Controller/RegForm,它将重定向到/Controller/RegForm

问题是因为我的 servlet 映射重定向到 /Controller,过滤器总是将 /Controller 作为路径。

如何同时使用过滤器和 servlet 映射?

这是我的web.xml

<filter>
    <filter-name>AuthFilter</filter-name>
    <filter-class>AuthFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>AuthFilter</filter-name>
    <url-pattern>/Controller/*</url-pattern>
</filter-mapping> 
 <servlet>
    <servlet-name>Controller</servlet-name>
    <servlet-class>Controller</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Controller</servlet-name>
    <url-pattern>/Controller/*</url-pattern>
</servlet-mapping>

<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

我的过滤器:

@WebFilter("/Controller/*")
public class AuthFilter implements Filter {

@Override
public void init(FilterConfig config) throws ServletException {
    // If you have any <init-param> in web.xml, then you could get them
    // here by config.getInitParameter("name") and assign it as field.
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession(false);
    String path = ((HttpServletRequest) request).getServletPath();

    if ((session != null && session.getAttribute("student") != null )||(excludeFromFilter(path))) {
            chain.doFilter(req, res); // Log 
        }
     else {
        response.sendRedirect("/registration-war/Controller/RegForm"); // No logged-in user found, so redirect to login page.
    }
}

private boolean excludeFromFilter(String path) {
    if (path.equals("/Controller/RegForm")) {
        return true; // add more page to exclude here
    } else {
        return false;
    }
}

【问题讨论】:

  • 你能告诉我们你的过滤器实现吗?

标签: java servlets filter mapping


【解决方案1】:

您使用 HttpServletRequest.getServletPath() 返回 servlet URL(根据您的 servlet 映射)"/Controller"

您想要的是 path info 而不是 servlet 路径:

返回与客户端发出此请求时发送的 URL 关联的任何额外路径信息。额外的路径信息在 servlet 路径之后,但在查询字符串之前,并以“/”字符开头。

例如,如果您的用户请求 /Controller/RegForm 页面,这将返回 "/RegForm"

String pathInfo = HttpServletRequest.getPathInfo();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-10
    • 2013-10-05
    • 2018-06-06
    • 2012-04-24
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多