Spring MVC拦截器,登录拦截简单配置

SpringMVC的拦截器(Interceptor)和Servlet的过滤器(Filter)有着近乎相同的功能,推荐登录使用Filter去做登录的拦截(个人比较喜欢Filter过滤的范围,要比Interceptor大很多)。

好了,首先写SpringMVC的拦截器,我们要写一个类,并且这个类实现HandlerInterceptor接口(也可以继承HandlerInterceptorAdapter类):

/**
 *
 */
package com.zjoa.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * 
 * @author DuZhuo
 * 登录拦截器
 */
@Repository
public class SystemInitInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {

		//获取url地址
		String reqUrl=request.getRequestURI().replace(request.getContextPath(), "");
		//当url地址为登录的url的时候跳过拦截器
		if(reqUrl.contains("/login.htm")){
			return true;
		}else{
			HttpSession session=request.getSession();
			Object obj=session.getAttribute("user");
			if(obj==null||"".equals(obj.toString())){
				response.sendRedirect("error.jsp");
			}
		}
		return true;
	}



}
然后我们去配置SpringMVC的xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc   
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	
	<context:component-scan base-package="com.zjoa"/>
	<!--设置登录拦截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/*.htm" />
			<mvc:mapping path="/*/*.htm" />
			<bean class="com.zjoa.interceptor.SystemInitInterceptor"/>
		</mvc:interceptor>
	</mvc:interceptors>
</beans>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值