[Hundreds of wins] Sanchuang Competition-Interceptor and Filter to realize registration and login (non-login state can not access other pages)

Hello everyone, I am the cabbage that is covered by cabbage.
Technology : SSM framework, interceptor, filter
background : when we are logging in or registering, we cannot request access when we visit the rest of the project. There are two ways to achieve it. One is to filter with filter, but Intercept with interceptor

Login page:
Insert picture description here
Registration page:
Insert picture description here

Intercepter specific implementation:

1. First, the configuration details of spring-servlet.xml interceptor
'

如果有多个拦截器满足拦截处理的要求,则依据配置的先后顺序来执行
     -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 拦截所有的请求,这个必须写在前面,也就是写在【不拦截】的上面 -->
            <mvc:mapping path="/**" />
            <!-- 但是排除下面这些,也就是不拦截请求 -->
            <mvc:exclude-mapping path="/login.jsp" />
            <mvc:exclude-mapping path="/users/login.do" />
            <mvc:exclude-mapping path="/users/register.do" />
            <bean class="com.bzbs.interceptor.LoginInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

2. Create a class to implement the HandlerInterceptor interface
Write specific business requirements in the postHandle () method, what needs to be done after the page is intercepted

public class LoginInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		//获取session 判断里面是否存有用户信心,没有则返回登录页面
		HttpSession session=request.getSession();
		Object user =session.getAttribute("user");
		Object password =session.getAttribute("password");
		if(user==null || password==null){
			String url = request.getRequestURL().toString();
			response.sendRedirect(request.getContextPath()+"/system/login.jsp?returnURL="+url);
			return false;
		}
		return true;
	}

}

I am here to determine whether to log in. If you have already logged in, you can directly access the blocked page. If there is no value in the session, you will continue to put it back in the waiting page. After that, the original address to be accessed is spliced. After logging in, you can directly access it, allowing us to access The page is much more convenient.


Here is the filter implementation:

1. Configure web.xml content

<filter>
		<filter-name>loginFilter</filter-name>
		<filter-class>com.bzbs.filter.LoginFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>loginFilter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>

url-pattern is the page to be filtered, / * means that all pages must be blocked, here you can configure whitelist and blacklist, how to do it will not be described here
2. Create a class to implement the Filter interface

/**  
* @ClassName: LoginFilter  
* @Description: 用拦截器没有作用,改变思路,用过滤器实现登录验证,假如没有登录则返回登录页面
* @author Lily  
* @date 2020年3月11日    
*/
public class LoginFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		//首先获取http对象
		HttpServletRequest request=(HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse)res;
		//此处判断,先获得请求路径,然后对请求路径进行分析

		/*
		 * 
		 * request.getRequestURL() 返回全路径
			request.getRequestURI() 返回除去host(域名或者ip)部分的路径
			request.getContextPath() 返回工程名部分,如果工程映射为/,此处返回则为空
			request.getServletPath() 返回除去host和工程名部分的路径
		 */
		
		String uri=request.getRequestURI();
		/*首先对于登录页面我们是可以直接进行访问的,假如没有登录,则判断是否已经登录,即session
		是否有值,没有值则不允许访问
		*/
		if(!uri.endsWith("register.do")&&!uri.endsWith("login.jsp")&&!uri.endsWith("login.do")&&
				!uri.endsWith(request.getContextPath()) && !uri.endsWith(request.getContextPath() + "/")){
			//下一步想要访问非登录页面,则判断session是否有值
			Object loginUser=request.getSession().getAttribute("user");
			if(loginUser!=null){
				//让他访问
				chain.doFilter(req, res);
			}else{
				//不满足条件,则返回登录页面
				String url = request.getRequestURL().toString();
				response.sendRedirect(request.getContextPath() + "/system/login.jsp?returnURL=" + url);
			}
		}else{
			chain.doFilter(req, res);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

chain.doFilter means that the request is passed. Here, I did not configure a whitelist for the sake of convenience, and directly used if judgment.

Published 24 original articles · praised 4 · visits 2038

Guess you like

Origin blog.csdn.net/weixin_44226263/article/details/105243471