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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章