淘淘商城08_权限管理及登录02之添加拦截器

我们添加拦截器,拦截的是Controller里面的东西

在web工程添加新的包com.taotao.interceptor

LoginInterceptor.java

package com.taotao.interceptor;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.pojo.ActiveUser;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		//执行后
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		//执行前
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		//1.获取到请求的URL
		String url = request.getRequestURI();
		//2.判断,公共的资源给放行,否则拦截
		if (url.equals("/login")||url.equals("/error")||url.equals("/user/login")) {
			return true;
		}
		
		HttpSession session = request.getSession();//获取到session
		ActiveUser activeUser = (ActiveUser) session.getAttribute("activeUser");//获取到session中存储的activeUser
		if (null != activeUser) {//判断session中有数据
			return true;
		}
		//跳转页面
		request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
		return false;
	}

}

在springmvc.xml中配置

<mvc:interceptors>
	<!-- 用户认证拦截 -->
		<mvc:interceptor>
			<mvc:mapping path="/**"/>
			<mvc:exclude-mapping path="/**/fonts/*"/>
	        <mvc:exclude-mapping path="/**/*.css"/>
	        <mvc:exclude-mapping path="/**/*.js"/>
	        <mvc:exclude-mapping path="/**/*.png"/>
	        <mvc:exclude-mapping path="/**/*.gif"/>
	        <mvc:exclude-mapping path="/**/*.jpg"/>
	        <mvc:exclude-mapping path="/**/*.jpeg"/>
	        <mvc:exclude-mapping path="/**/*validatecode*"/>
	        <mvc:exclude-mapping path="/**/*Login*"/>
	        <mvc:exclude-mapping path="/**/*error*"/>
			<bean class="com.taotao.interceptor.LoginInterceptor"/>
		</mvc:interceptor>
	</mvc:interceptors>

拦截器优化:

因为项目越来越多,拦截器需要放行的也越来越多,所以在这么写就太麻烦了。

在这里就需要将需要放行的放入到一个配置文件annotionURL.properties中

#配置公开的URL
/user/login=登录url
/login=登录页面
/error=失败页面提示

还需要一个工具类读取这个配置文件:ResourcesUtil.java

package com.taotao.utils;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;

/**
 * 资源文件读取工具类
 * 
 */
public class ResourcesUtil implements Serializable {

	private static final long serialVersionUID = -7657898714983901418L;

	/**
	 * 系统语言环境,默认为中文zh
	 */
	public static final String LANGUAGE = "zh";

	/**
	 * 系统国家环境,默认为中国CN
	 */
	public static final String COUNTRY = "CN";
	private static Locale getLocale() {
		Locale locale = new Locale(LANGUAGE, COUNTRY);
		return locale;
	}

	/**
	 * 根据语言、国家、资源文件名和key名字获取资源文件值
	 * 
	 * @param language
	 *            语言
	 * 
	 * @param country
	 *            国家
	 * 
	 * @param baseName
	 *            资源文件名
	 * 
	 * @param section
	 *            key名字
	 * 
	 * @return 值
	 */
	private static String getProperties(String baseName, String section) {
		String retValue = "";
		try {
			Locale locale = getLocale();
			ResourceBundle rb = ResourceBundle.getBundle(baseName, locale);
			retValue = (String) rb.getObject(section);
		} catch (Exception e) {
			e.printStackTrace();
			// TODO 添加处理
		}
		return retValue;
	}

	/**
	 * 通过key从资源文件读取内容
	 * 
	 * @param fileName
	 *            资源文件名
	 * 
	 * @param key
	 *            索引
	 * 
	 * @return 索引对应的内容
	 */
	public static String getValue(String fileName, String key) {
		String value = getProperties(fileName,key);
		return value;
	}

	public static List<String> gekeyList(String baseName) {
		Locale locale = getLocale();
		ResourceBundle rb = ResourceBundle.getBundle(baseName, locale);

		List<String> reslist = new ArrayList<String>();

		Set<String> keyset = rb.keySet();
		for (Iterator<String> it = keyset.iterator(); it.hasNext();) {
			String lkey = (String)it.next();
			reslist.add(lkey);
		}

		return reslist;

	}

	/**
	 * 通过key从资源文件读取内容,并格式化
	 * 
	 * @param fileName
	 *            资源文件名
	 * 
	 * @param key
	 *            索引
	 * 
	 * @param objs
	 *            格式化参数
	 * 
	 * @return 格式化后的内容
	 */
	public static String getValue(String fileName, String key, Object[] objs) {
		String pattern = getValue(fileName, key);
		String value = MessageFormat.format(pattern, objs);
		return value;
	}

	public static void main(String[] args) {
		System.out.println(getValue("resources.messages", "101",new Object[]{100,200}));
		
		
		//根据操作系统环境获取语言环境
		/*Locale locale = Locale.getDefault();
		System.out.println(locale.getCountry());//输出国家代码
		System.out.println(locale.getLanguage());//输出语言代码s
		
		//加载国际化资源(classpath下resources目录下的messages.properties,如果是中文环境会优先找messages_zh_CN.properties)
		ResourceBundle rb = ResourceBundle.getBundle("resources.messages", locale);
		String retValue = rb.getString("101");//101是messages.properties文件中的key
		System.out.println(retValue);
		
		//信息格式化,如果资源中有{}的参数则需要使用MessageFormat格式化,Object[]为传递的参数,数量根据资源文件中的{}个数决定
		String value = MessageFormat.format(retValue, new Object[]{100,200});
		System.out.println(value);
*/

	}
}

然后优化LoginInterceptor代码:

package com.taotao.interceptor;

import java.util.List;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.pojo.ActiveUser;
import com.taotao.utils.ResourcesUtil;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		//执行后
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		//执行前
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		//1.获取到请求的URL
		String url = request.getRequestURI();
		//2.判断,公共的资源给放行,否则拦截
		//用工具类ResourcesUtil.java读取annotionURL.properties,返回一个list集合,读取annotionURL.properties中的key值
		List<String> open_url = ResourcesUtil.gekeyList("annotionURL");
		for (String open_urls : open_url) {
			if (url.indexOf(open_urls)>=0) {
				return true;
			}
		}
		
		HttpSession session = request.getSession();//获取到session
		ActiveUser activeUser = (ActiveUser) session.getAttribute("activeUser");//获取到session中存储的activeUser
		if (null != activeUser) {//判断session中有数据
			return true;
		}
		//跳转页面
		request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
		return false;
	}

}

猜你喜欢

转载自blog.csdn.net/fjz_lihuapiaoxiang/article/details/85000224