Structs2 中攔截器獲取請求參數

前言

環境:window 10,JDK 1.7,Tomcat 7java

測試代碼

package com.szxy.interceptor;

import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement;

import java.util.Set;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.szxy.pojo.User;

/**
 * 自定義攔截器
 * 
 * 繼承  AbstractInterceptor 類
 * 重寫 intercept 方法
 */
public class LoginInterceptor extends AbstractInterceptor{

    @Override
    public String intercept(ActionInvocation invocate) throws Exception {
        System.out.println("使用登陸攔截器...");
        //獲取上下文對象
        ActionContext context = invocate.getInvocationContext();
        // 獲取請求參數 
        // 注意:獲取的請求參數中的map的值是String[] 數組類型
        Map<String, Object> map = context.getParameters();

        /*for(Entry<String, Object> entry: map.entrySet()){
            System.out.println(entry.getKey()+"\t"+((String[])entry.getValue())[0]);
        }*/
        
        String uname =  ((String[])(map.get("user.uname")))[0];
        String pwd =  ((String[])(map.get("user.pwd")))[0];
        String addr = ((String[])(map.get("user.addr")))[0];
        /*System.out.println("uname:\t"+(uname!=""));*/
        //判斷請求參數是否爲空
        if(uname!=""&&pwd!=""&&addr!=""){
            return invocate.invoke();//放行
        }
        System.out.println("信息填寫有問題");
        context.getSession().put("msgNull", "false");
        return Action.LOGIN;
    }
}

structs.xml 配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<!-- Struts2 配置文件的根元素  -->
<struts>
    <package name="test" namespace="/" extends="struts-default">
        <!-- 攔截器 -->
        <interceptors>
        <!-- 自定義攔截器 -->
            <interceptor name="loginInterceptor" class="com.szxy.interceptor.LoginInterceptor"></interceptor>
            <interceptor-stack name="loginStack">
                <!--    
                     一旦申請自定義攔截器,就不會自動使用默認攔截器。
                    若要使用,須要本身聲明默認攔截器。
                 -->
                <interceptor-ref name="defaultStack"></interceptor-ref>
                <interceptor-ref name="loginInterceptor"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        
        <action name="login" class="com.szxy.action.UserAction">
            <result name="success">/test.jsp</result>
            <result name="error" type="redirect">/login.jsp</result>
            <!-- 使用攔截器欄  -->
            <interceptor-ref name="loginStack"></interceptor-ref>
            <result name="login"  type="redirect">/login.jsp</result>
        </action>
    </package>
</struts>

總結

ActionContextgetParameter 方法的返回類型是 Map<String,Object>,而且對應鍵的值的類型 是String[]類型。apache

相關文章
相關標籤/搜索