SpringMVC

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35325795/article/details/80343463
1、在springmvc-config.xml中添加一下配置

* 注意:这里拦截的是请求、而不是页面。

<!-- 配置拦截器 -->
<mvc:interceptors>
    <mvc:interceptor>
<mvc:mapping path="/user/*"/>
<bean class="cn.com.Interceptor.MyInterceptor"></bean>
    </mvc:interceptor>

</mvc:interceptors>

2、编写 Interceptor 拦截相关请求

1)、实现 HandlerInterceptor 接口

2)、继承自HandlerInterceptorAdapter 抽象类

示例代码:

package cn.com.Interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
	
public class MyInterceptor 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 {
		Object object = request.getSession().getAttribute("user");
		System.out.println("进入拦截器");
		if(object!=null){
		    System.out.println("用户已登录");
		    return true;			
		}
		    System.out.println("非法访问");
		    request.getRequestDispatcher("user/toLogin").forward(request, response);
		    return false; //拦截
	}

}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页