Java struts2 攔截器 interceptors

攔截器類以下所示:html

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.edp.org.user.vo.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 特殊字符攔截器
 * 
 * @author zhangda
 *
 */
public class SpecialCharInterceptor extends AbstractInterceptor {

	Logger logger = Logger.getLogger(this.getClass());

	/**
	 * 攔截方法
	 * 
	 */
	public String intercept(ActionInvocation invocation) throws Exception {

		// 取得ActionContext實例
		ActionContext ctx = invocation.getInvocationContext();
		
		//先驗證是否傳入非法字符,以防sql注入 --張達 20151216
		String msg = validateDataBaseSpecialChar(ctx);
		if(!msg.equals("")){
			logger.error("參數傳入非法字符!");
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setHeader("Content-type", "text/html;charset=UTF-8");  
			response.setCharacterEncoding("utf-8");
	        PrintWriter out = response.getWriter();
	        out.print("{\"success\": false, \"errMsg\": \"參數傳入非法字符\"}"); 
	        out.flush();
	        out.close();
			return ActionSupport.ERROR;
		}else{
			return invocation.invoke();
		}
		
	}
	
	/***
	 * 過濾sql注入的特殊字符 zd
	 * @param ac
	 * @return
	 */
	public String validateDataBaseSpecialChar(ActionContext ac) {  
        Map<String, Object> inputMap = ac.getParameters();  
        //查詢字典請求須要傳入特殊字符
        if(ac.getContext().getName().equals("getDictionaryByTypeIds")){
        	return "";
        }else{
        	Iterator<Entry<String, Object>> it = inputMap.entrySet().iterator();  
            while (it.hasNext()) {  
                Map.Entry<String, Object> entry = it.next();  
                Object value = entry.getValue();  
                if  (value instanceof String[]) { 
                	String[] valueArray = (String[])value;
                	String valueStr = "";
                	if(valueArray != null && valueArray.length != 0){
                		for(int i=0; i<valueArray.length; i++){
                			valueStr += valueArray[0] + ",";
                    	}
                	}
                	return checkInject(valueStr);
                } 
            }  
        }
        
        return "";
    } 
	
	//防sql注入的字符串數組
	private static final String[] INJ_STR = {
		"exec ", "select ", "insert ", "update " , "delete", "count ", "master ", "drop ",
		"truncate ", "declare ", " or ", " and ", "--", "'", "\"", "\'", "\\\"", "(", ")", ";", "--", "+"
	};
	
	private static String checkInject(String str)  {
		
		for (int i=0; i<INJ_STR.length; i++) {
			if (str.toLowerCase().indexOf(INJ_STR[i]) > -1) {
				return "error";
			}
		}
		return "";
	}
}

struts配置文件以下:java

<!-- 配置攔截器  用於攔截防止sql注入的特殊字符-->
		<interceptors>
			<interceptor name="SpecialCharInter" class="com.edp.web.SpecialCharInterceptor"></interceptor>
			<!-- 配置userSessionStack攔截器棧 -->
			<interceptor-stack name="SpecialCharStack">
				<interceptor-ref name="SpecialCharInter"></interceptor-ref>
				<interceptor-ref name="defaultStack"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="SpecialCharStack"></default-interceptor-ref>
相關文章
相關標籤/搜索