package com.example.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.dispatcher.HttpParameters;
import java.util.Map;

/**
 * 参数验证拦截器 - 演示拦截器预处理
 */
public class ValidationInterceptor extends AbstractInterceptor {
    
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("[ValidationInterceptor] 开始参数验证");
        
        // 获取参数 (Struts2 6.x 使用 HttpParameters)
        HttpParameters params = invocation.getInvocationContext().getParameters();
        
        for (String paramName : params.keySet()) {
            String[] values = params.get(paramName).getMultipleValues();
            if (values != null) {
                for (String value : values) {
                    if (containsXss(value)) {
                        System.out.println("[ValidationInterceptor] 检测到可疑参数: " + paramName);
                        return "invalidInput";
                    }
                }
            }
        }
        
        System.out.println("[ValidationInterceptor] 参数验证通过");
        return invocation.invoke();
    }
    
    private boolean containsXss(String value) {
        if (value == null) return false;
        String lower = value.toLowerCase();
        return lower.contains("<script") || 
               lower.contains("javascript:") ||
               lower.contains("onerror=");
    }
}