过滤器检测用户是否登陆

情景:系统中的某些页面只有在正常登陆后才可以使用,用户请求这些页面时要检查 session 中有无该用户信息,但在所有必要的页面加上session的判断相当麻烦的事情

解决方案:编写一个用于检测用户是否登陆的过滤器,如果用户未登录,则重定向到指的登录页面

要求:需检查的在 Session 中保存的关键字; 如果用户未登录,需重定向到指定的页面(URL不包括 ContextPath); 不做检查的URL列表(以分号分开,并且 URL 中不包括 ContextPath)都要采取可配置的方式

package com.Greatest.Filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
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;

/**
 * Servlet Filter implementation class loginFilter
 */
@WebFilter("/login/*")
public class loginFilter extends MyFilter {
	// 1.从WEB.XML文件中获取sessionKey,redirecturl,uncheckedUrls
	private String sessionKey;
	private String rediret;
	private String unchecked;

	@Override
	protected void init() {
		ServletContext sc = getFconfig().getServletContext();
		sessionKey = sc.getInitParameter("userSessionKey");
		rediret = sc.getInitParameter("rediretPage");
		unchecked = sc.getInitParameter("uncheckedUrls");
	}    
    
	@Override
	public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain Chain)
			throws IOException, ServletException {
		String uli = request.getRequestURI();
		// login/a.jsp,/login/list.jsp, /login/login.jsp,
	    System.out.println(uli);
		String url = request.getRequestURL().toString();
		System.out.println(url);
         
		// 1.获取请求的servletPath
		// /login/b.jsp
		String servletpath = request.getServletPath();
		System.out.println(servletpath);
		// 2.检查1 获取的servletpath是否为不需要检查的url中的一个若是,则直接放行。方法结束
		List<String> urls = Arrays.asList(unchecked.split(","));
		if (urls.contains(servletpath)) {
			Chain.doFilter(request, response);
			return;
		}
		// 3.需要检查   从session中获取sessionKey(username)对应的值 若值不存在 则重定项到redirectUrl /login/login.jsp
		// 登录页面
		Object user = request.getSession().getAttribute(sessionKey);
		if (user == null) {
			response.sendRedirect(request.getContextPath() + rediret);
			return;
		}
		// 4.若存在则放行 允许访问
		Chain.doFilter(request, response);
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
     <h4>AAA</h4>
     <a href="list.jsp">Return...</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
          <a href="a.jsp">AAA</a>
          <br><br>
          <a href="b.jsp">BBB</a>
          <br><br>
          <a href="c.jsp">CCC</a>
          <br><br>
          <a href="d.jsp">DDD</a>
          <br><br>
          <a href="e.jsp">EEE</a>
          <br><br>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
      <%//1.获取用户登录信息
         String name=request.getParameter("username");
         //2.若登录信息完整则把登录信息放到HttpSession
         if(name!=null&&!name.trim().equals("")){
        	 session.setAttribute(application.getInitParameter("userSessionKey"), name);
        	 //3 重定向到list.jsp
        	 response.sendRedirect("list.jsp");
         }else{
        	 response.sendRedirect("login.jsp");
         }
      %>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
       <form action="dologin.jsp" method="post">
           username:<input type="text" name="username"/>
           <input type="submit" value="Submit"/>
       </form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <!--用户信息放入到session中的键的名字       变为可配置的 -->
  <context-param>
     <param-name>userSessionKey</param-name>
     <param-value>USERSESSIONKEY</param-value>
  </context-param>
  <!--若未登录,需要重定向的页面 -->
  <context-param>
     <param-name>rediretPage</param-name>
     <param-value>/login/login.jsp</param-value>
  </context-param> 
  <!--不需要拦截(或检查)的URL列表 -->
  <context-param>
     <param-name>uncheckedUrls</param-name>
     <param-value>/login/a.jsp,/login/list.jsp,/login/b.jsp,/login/dologin.jsp,/login/login.jsp</param-value>
  </context-param>
  <context-param>
    <param-name>enoding</param-name>
    <param-value>UTF-8</param-value>
  </context-param>
  <context-param>
    <param-name>username</param-name>
    <param-value>tom</param-value>
  </context-param>
  <context-param>
    <param-name>password</param-name>
    <param-value>123123</param-value>
  </context-param>
  <filter>
    <filter-name>Enoding</filter-name>
    <filter-class>com.Greatest.Filter.Enoding</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>Enoding</filter-name>
    <url-pattern>/enoding/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>SecondFilter</filter-name>
    <filter-class>com.Greatest.Filter.SecondFilter</filter-class>
  </filter>
  <filter>
    <filter-name>HelloFilter</filter-name>
    <filter-class>com.Greatest.Filter.helloFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SecondFilter</filter-name>
    <url-pattern>/test.jsp</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>HelloFilter</filter-name>
    <url-pattern>/test.jsp</url-pattern>
    <dispatcher>ERROR</dispatcher>
  </filter-mapping>
  <error-page>
    <exception-type>java.lang.ArithmeticException</exception-type>
    <location>/test.jsp</location>
  </error-page>
</web-app>

猜你喜欢

转载自blog.csdn.net/qq_42676998/article/details/82817142
今日推荐