Structs2 中拦截器获取请求参数

前言

环境:window 10,JDK 1.7,Tomcat 7

测试代码

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[]类型。

猜你喜欢

转载自www.cnblogs.com/zwer/p/10631028.html