在进行登录操作时我们都要使用拦截器拦截用户的访问,以避免用户未登录操作。
以下是对登录操作的简单拦截,自己可针对自己的业务进行扩展。
自定义BaseInterceptor实现HandlerInterceptor,用户发送的每个请求都会被preHandle()方法拦截,我们就可以在preHandle方法中实现自己的业务员逻辑,哪些不需要被拦截等等操作。
package com.vanfon.p2p.back.interceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import com.vanfon.p2p.entity.system.Admin;import com.vanfon.p2p.entity.system.Log;import com.vanfon.p2p.utils.ThreadLocalUtils;public class BaseInterceptor implements HandlerInterceptor {@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception arg3) throws Exception {// System.out.println("afterCompletion---");}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {// System.out.println("postHandle---");}@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {Admin user = (Admin) request.getSession().getAttribute("admin");String requestURI = request.getRequestURI();String loginUrl = "/login.jhtml";String uri = requestURI.substring(requestURI.lastIndexOf("/"));if (user == null) {if (uri.startsWith("/login") || uri.startsWith("/imageLogin") || uri.startsWith("/checkLogin")) {return true;} else {// 非法请求 重定向到登录页面response.sendRedirect(request.getContextPath() + loginUrl);return false;}} else {// 添加日志String ip = request.getRemoteAddr();Long adminId = user.getId();Log log = new Log();log.setAdminId(adminId);log.setIp(ip);ThreadLocalUtils.set(log);return true;}}}
配置:applicationContext-mvc.xml
<!-- 自定义拦截器 --><mvc:interceptors><bean class="com.vanfon.p2p.back.interceptor.BaseInterceptor" /></mvc:interceptors>