JEE项目登录过滤器开发:会话校验与getRequestURI使用疑问
关于JEE认证过滤器中
request.getRequestURI()的正确用法 嘿,我来帮你把这个认证过滤器的逻辑捋清楚~你现在写的if(request.getRequestURI().startsWith("/"))其实没啥用,因为所有HTTP请求的URI都是以/开头的,等于这个判断条件永远为真,起不到过滤作用。
咱先明确核心需求:要拦截所有需要登录才能访问的页面,同时放行登录页、静态资源这些不需要认证的路径。下面是具体的正确用法和完整代码示例:
第一步:理解request.getRequestURI()的返回值
它返回的是从服务器根目录开始的完整请求路径,比如你的应用部署在/jee-project上下文路径下,用户访问http://localhost:8080/jee-project/user/profile,那么request.getRequestURI()会返回/jee-project/user/profile。
如果要拿到相对于你应用的路径,可以结合request.getContextPath()来处理,避免因为部署路径变化导致判断出错:
String contextPath = request.getContextPath(); String relativePath = request.getRequestURI().substring(contextPath.length()); // 上面的relativePath就会是 /user/profile
第二步:编写正确的过滤逻辑
- 先定义不需要拦截的路径(登录页、静态资源等)
- 判断当前请求是否在允许列表里,是则直接放行
- 不在允许列表的话,检查会话中是否有已登录的用户信息
- 未登录就重定向到登录页,已登录则放行请求
完整的doFilter方法示例
@Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponse response = (HttpServletResponse) arg1; String contextPath = request.getContextPath(); String requestURI = request.getRequestURI(); String relativePath = requestURI.substring(contextPath.length()); // 定义不需要认证就能访问的路径 List<String> allowedPaths = Arrays.asList( "/login.jsp", "/login", // 处理登录请求的Servlet路径 "/css/", "/js/", "/images/" ); // 判断当前请求是否在允许列表中 boolean isAllowed = allowedPaths.stream() .anyMatch(path -> relativePath.startsWith(path)); if (isAllowed) { // 放行不需要认证的请求 chain.doFilter(request, response); return; } // 检查会话中是否有已登录用户(不创建新会话) HttpSession session = request.getSession(false); boolean isLoggedIn = session != null && session.getAttribute("loggedInUser") != null; if (isLoggedIn) { // 已登录,放行请求 chain.doFilter(request, response); } else { // 未登录,重定向到登录页 response.sendRedirect(contextPath + "/login.jsp"); } }
几个关键注意点
- 用
request.getSession(false)而不是request.getSession():后者会在没有会话时创建新会话,没必要,我们只需要检查已有会话里的用户信息。 - 静态资源一定要放行:不然你的登录页可能加载不了CSS、JS,样式全乱了。
- 路径判断用
startsWith更灵活:比如"/css/"可以匹配所有CSS目录下的资源,不用逐个列出来。
内容的提问来源于stack exchange,提问作者kristheman
相关产品推荐
相关产品推荐

