【发布时间】:2013-06-28 03:50:08
【问题描述】:
我正在尝试为 Netbeans 中的 JSP 项目做一个 servlet 过滤器。我想要做的是检查用户是否登录,如果没有,则将其重定向到登录页面。我遵循了本教程:
https://stackoverflow.com/tags/servlet-filters/info
所以我有这个 java 文件作为我的过滤器类(文件名是 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>
但是这不起作用。有人可以告诉我我缺少什么吗?
【问题讨论】:
-
您用来测试过滤器的 url 是什么?仅当 url 包含路径 'app' 时才会调用此过滤器
-
使用
annotation或web.xml标记并从不在默认包中创建您的类型。 -
我尝试将
/app/* 修改为/scoreBoardAPPPL/* 但仍然无法正常工作。跨度> -
我将其更改为
/* 现在它可以工作了,但是,当它尝试重定向到页面 login.jsp 时,浏览器挂起并重定向像在无限循环中一样登录.jsp。我会检查我的代码,看看我能做什么。
标签: jsp session netbeans login servlet-filters