欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring MVC配置自定义拦截器

程序员文章站 2022-07-03 20:07:43
...

以拦截非法访问为例:

拦截器代码:

package cn.mySmbms.interceptor;

import java.io.IOException;
import java.util.List;

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

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.mySmbms.pojo.User;
import cn.mySmbms.utils.Constants;

/**
 * 自定义拦截器,对所有访问该系统的请求(登录请求除外),进行身份验证,以保证数据的安全性
 * 
 * @author 30869
 * 
 */
public class SysInterceptor extends HandlerInterceptorAdapter {
	private List<String> uncheckUrls;
	public List<String> getUncheckUrls() {
		return uncheckUrls;
	}
	public void setUncheckUrls(List<String> uncheckUrls) {
		this.uncheckUrls = uncheckUrls;
	}


	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws IOException {
		String requestUrl = request.getRequestURI();//获取url
		if (uncheckUrls.contains(requestUrl)) {//判断是否是非拦截url
			return true;
		} else {
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute(Constants.USER_SESSION);
			if (null == user) {
				response.sendRedirect(request.getContextPath() + "/401.jsp");
				return false;
			}
		}
		return true;
	}
}

springmvc配置:

<!-- 配置拦截器,拦截器的详细规则见class,多个拦截器,顺序执行 --> 
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**"/><!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller -->
			<bean class="cn.mySmbms.interceptor.SysInterceptor">
			<!-- 配置不需要拦截的url -->
			<property name="uncheckUrls">
				<list>
					<value>/mySmbms/userController/login.html</value>
					<value>/mySmbms/userController/userLogin</value>
				</list>
			</property>
			</bean>
		</mvc:interceptor>
	</mvc:interceptors>



上一篇: logback

下一篇: logback配置文件