SpringMVC 设置interceptor防止未认证访问

156 阅读1分钟

引言

如果使用了Spring Security,只需要相关的配置就可以达到认证访问的目的。如果没使用呢?那也可以使用interceptor达到同样的目的。

1. 配置servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

<!-- interceptor -->
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**" />
 		<mvc:exclude-mapping path="/login" />
		<beans:bean class="com.cuts.siled.interceptor.TestLoginInterceptor" />
	</mvc:interceptor>
</mvc:interceptors>

2. 实现HandlerInterceptor

java编码,实现HandlerInterceptor。假设在登录页面已经设置session属性username,这里可以得到username。如果username为空则强制跳转到登录页面。这样可以防止没有通过登录直接url的访问。

public class TestLoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Logger logger = LoggerFactory.getLogger(TestLoginInterceptor.class);
		logger.debug("preHandle interceptor!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! : " + request.getRequestURL());
		String usr = (String)request.getSession().getAttribute("username");
		logger.warn("username:" + usr);
		
		if (usr == null) {
		    response.sendRedirect("/test/page/index.jsp");
		    return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("afterCompletion");
	}

}