struts2运行原理
自定义拦截器:
package com.inter;
import java.util.Set;
import org.apache.struts2.dispatcher.HttpParameters;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginInterceptor extends AbstractInterceptor {
private HttpParameters httpParameters;
@Override
public String intercept(ActionInvocation arg0) throws Exception {
ActionContext actonContext = ActionContext.getContext();
httpParameters = actonContext.getParameters();
/*
* 获取表单提交参数集合
*/
Set<String> keySet = httpParameters.keySet();
for (String str : keySet) {
/*
* 用户登录校验,可以在这里进行,在这里可以进行用户名格式、密码格式、日期、电话等相关参数进行校验
*/
System.out.println(str + "==" + httpParameters.get(str).getValue());
}
/*
* 校验完成后执行下一个拦截器,并返回结果
*/
String str = arg0.invoke();
return str;
}
}
struts.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="user" extends="struts-default">
<interceptors >
<!--自定义拦截器的配置 -->
<interceptor name="userInter" class="com.inter.LoginInterceptor"></interceptor>
</interceptors>
<action name="login" class="com.action.Login" method="login">
<interceptor-ref name="params" />
<!--自定义拦截器的引用 -->
<interceptor-ref name="userInter" />
<result name="success" >/login.jsp</result>
<result name="input">/500.jsp</result>
</action>
<action name="add" class="com.action.Login" method="add">
<result name="success" >/add.jsp</result>
<result name="input">/500.jsp</result>
</action>
</package>
</struts>