servlet过滤器在JSP中不起作用



我正在尝试为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>

然而,这并不奏效。有人能告诉我我缺了什么吗?

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

非常感谢在评论中回复的人。

相关内容

  • 没有找到相关文章

最新更新