servlet过滤器在JSP中不起作用

时间:2013-07-01 04:27:39

标签: jsp session netbeans login servlet-filters

我正在尝试为Netbeans中的JSP项目执行servlet过滤。我想要做的是检查用户是否已登录,如果不是,则将其重定向到登录页面。我遵循了这个教程:

https://stackoverflow.com/tags/servlet-filters/info

所以我把这个java文件作为我的Filter类(文件名是LoginFilter.java):

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/app/*")
public class LoginFilter 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);

    if (session == null || session.getAttribute("usuario") == null) {
        response.sendRedirect(request.getContextPath() + "/login.jsp"); // No logged-in user found, so redirect to login page.
    } else {
        chain.doFilter(req, res); // Logged-in user found, so just continue request.
    }
}

@Override
public void destroy() {
    // If you have assigned any expensive resources as field of
    // this Filter class, then you could clean/close them here.
}

}

这是我的web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

<filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>LoginFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/app/*</url-pattern>
</filter-mapping>

然而这不起作用。有人可以告诉我我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

我设法解决了问题,问题是每次加载页面时,过滤器都会检查代码,在我的情况下,我没有在任何地方声明我的变量“usuario”,这个变量就是可以重定向到登录页面或继续加载当前页面。所以我在用户登录时进行了更改以设置变量(辅助页面检查登录,并在那里设置变量)。然后所有其他页面都不设置变量,它们只是采用登录检查中设置的内容。

非常感谢回复评论的人们。