1. 程式人生 > >淘淘商城08_許可權管理及登入02之新增攔截器

淘淘商城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;
	}

}