通过拦截器获取表单传值时,首先需要在struts.xml文件里所配置的拦截器前配置params拦截器,否则会报空指针错误。如下:
<package name="myLogin" extends="struts-default">
<interceptors>
<interceptor name="loginCheck" class="testInterceptor.LoginAbstractInterceptor"></interceptor>
</interceptors>
<action name="userLogin" class="action.LoginAction">
<interceptor-ref name="params"/>
<interceptor-ref name="loginCheck"></interceptor-ref>
<result name="success">main.jsp</result>
</action>
</package>
然后在获取表单内容的时候:
先通过invocation获取ActionContext,通过Action获取Session及表单数据。
主注意:在获取表单数据时,通过context.getParameters().get(key)获取的值是数组类型的。
需要用以下加红方式进行获取。
ActionContext context = invocation.getInvocationContext();
String name = ((String[])context.getParameters().get("userName"))[0];
String password = ((String[])context.getParameters().get("password"))[0];
Map<String, Object> session = context.getSession();
如果直接用String name = (String)context.getParameters().get("userName"))获取
会报[Ljava.lang.String; cannot be cast to java.lang.String错误。