spring mvc拦截器之拦截未登录

                                                                     spring mvc拦截器之拦截未登录


1.在web.xml中配置DispatcherServlet

配置好DispatcherServlet之后,DispatcherServlet会接受所有请求,包括静态资源的请求。


   spring
   org.springframework.web.servlet.DispatcherServlet
   1


   spring
   /


2.如何处理静态资源(目的:使拦截器不拦截静态资源)
(1)使用tomcat的defaultservlet来处理静态资源
  
   default  
   /js/*  
   *.css  
   /images/*  
 

(2)使用
 
   
配置它后会在Spring MVC上下文中定义一个org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,
它会像一个检查员,对进入DispatcherServlet的URL进行筛查,如果发现是静态资源的请求,就将该请求转由Web应用服务器默认的Servlet
处理,如果不是静态资源的请求,才由DispatcherServlet继续处理。

一般Web应用服务器默认的Servlet名称是"default",因此DefaultServletHttpRequestHandler可以找到它。如果你所有的Web应用服

务器的默认Servlet名称不是"default",则需要通过default-servlet-name属性显示指定:

(3)采用

 
   
           
	
	
	
注意:必须是webapp根目录下的路径
location:请求的资源地址。
mapping:映射后地址。
这里附上相关静态资源的博客http://www.cnblogs.com/fangqi/archive/2012/10/28/2743108.html
3.配置拦截器
注:在springmvc的配置文件中加入支持mvc的schema




		
		
			
			
			
			
			
		

		
			
			
		

		
			
			
		

		
			
			
		
	

4.定义实现HandlerInterceptor接口的实现类
这里只以登陆为例,(如访问购物车未登陆则转到登陆页面)
 
   
package com.tortuousroad.site.web.site.interceptor;

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

import com.tortuousroad.site.web.constants.WebConstants;
import com.tortuousroad.site.web.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.tortuousroad.site.web.base.objects.WebUser;
import com.tortuousroad.user.entity.User;
import com.tortuousroad.user.service.UserService;

/**
 * 登陆拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
	@Autowired
	private UserService userService;

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj, ModelAndView modelAndView)
			throws Exception {
	}


	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {
		WebUser webUser = CookieUtil.getLoginUser(request);
		if (null == webUser) {
			String basePath = request.getScheme() + "//:" + request.getServerName() + ":" + request.getServerPort();
			response.sendRedirect(basePath + "/login");
			return false;
		}
		return true;
	}

}
CookieUtil类
 
   
package com.tortuousroad.site.web.utils;

import com.tortuousroad.site.web.base.objects.WebUser;
import com.tortuousroad.user.entity.User;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Objects;


/**
 * Cookie工具类
 */
public class CookieUtil {
	/**
	 * 默认Cookie过期时间(单位:秒)
	 */
	public static final int MAX_AGE = 60 * 30;
	
	/**
	 * 用户登陆信息Cookie名字
	 */
	public static final String USER_INFO = "ui";

	/**
	 * 向Cookie中写入用户信息
	 * @param response
	 * @param user
     */
	public static void setLoginUser(HttpServletResponse response, WebUser user) {
		if (null == response || null == user) {
			return;
		}
		long userId = user.getUserId();
		String username = user.getUsername();
		try {
			username = URLEncoder.encode(user.getUsername(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		StringBuilder cookieValue = new StringBuilder();
		//FIXME 用户ID此处写入是用于调试,上线需要去掉
		cookieValue.append(userId).append("|").append(username).append("|").append(user.getLoginStatus());
		addCookie(response, USER_INFO, cookieValue.toString());

	}
        /*将构造好的信息放入coolie中*/
	public static void addCookie(HttpServletResponse response, String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		cookie.setMaxAge(MAX_AGE);
		response.addCookie(cookie);
	}
    /*从cookie取出用户登陆信息并且构造webuser对象返回*/
	public static WebUser getLoginUser(HttpServletRequest request) {
		if (null == request) {
			return null;
		}

		//从cookie里取出用户信息(三个字段)
		String value = getCookieValue(USER_INFO, request);
		if (StringUtils.isEmpty(value)) {
			return null;
		}

		String[] array = value.split("\\|");

		WebUser user = new WebUser();
		user.setUserId(Long.parseLong(array[0]));
		try {
			user.setUsername(URLDecoder.decode(array[1], "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			user.setUsername(array[1]);
		}
		user.setLoginStatus(Integer.parseInt(array[2]));
		return user;
	}
     /*从cookie中取出用户的登陆信息*/
	public static String getCookieValue(String name, HttpServletRequest request) {
		if (null == request || StringUtils.isEmpty(name)) {
			return null;
		}

		Cookie[] cookies = request.getCookies();
		if (null == cookies || 0 == cookies.length) {
			return null;
		}

		for (Cookie cookie : cookies) {
			if (Objects.equals(cookie.getName(), name)) {
				return cookie.getValue();
			}
		}
		return null;
	}

	/**
	 * 删除Cookie
	 * @param response HttpServletResponse
	 * @param name Cookie名
	 * @param path Cookie Path
     */
	public static void removeCookie(HttpServletResponse response, String name, String path) {
		if (null == response || StringUtils.isEmpty(name) || StringUtils.isEmpty(path)) {
			return;
		}
		Cookie cookie = new Cookie(name, "");
		cookie.setPath(path);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

WebUser类
 
   
package com.tortuousroad.site.web.base.objects;


import java.io.Serializable;

public class WebUser implements Serializable {

	 private Long userId; // 用户ID

	 private String username; // 用户名

	 private int loginStatus; // 登陆状态

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getLoginStatus() {
		return loginStatus;
	}

	public void setLoginStatus(int loginStatus) {
		this.loginStatus = loginStatus;
	}
}




你可能感兴趣的:(spring)