在 Struts2 中,通配符规则主要用于拦截 URL 并根据规则执行相应的操作。要自定义通配符规则,你需要遵循以下步骤:
com.opensymphony.xwork2.interceptor.Interceptor 接口的自定义拦截器类。在这个类中,你可以实现你需要的方法,例如 init(), destroy() 和 intercept()。import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; public class CustomInterceptor implements Interceptor { @Override public void init() { // 初始化拦截器 } @Override public void destroy() { // 销毁拦截器 } @Override public String intercept(ActionInvocation invocation) throws Exception { // 在这里编写你的拦截逻辑 return invocation.invoke(); } } struts.xml)中配置你的自定义拦截器。在 <struts> 标签内,添加一个 <package> 标签来定义你的拦截器。然后,在 <package> 标签内,添加一个 <interceptors> 标签来定义你的自定义拦截器。最后,在 <interceptors> 标签内,添加一个 <interceptor> 标签来定义你的自定义拦截器类,并使用 name 属性为其指定一个名称。<struts> <package name="default" extends="struts-default"> <interceptors> <interceptor name="customInterceptor" class="com.example.CustomInterceptor" /> </interceptors> </package> <action name="yourAction" class="com.example.YourAction"> <interceptor-ref name="customInterceptor" /> <result name="success">/success.jsp</result> </action> </struts> struts.xml 文件中使用自定义拦截器来定义通配符规则。在 <action> 标签内,使用 <interceptor-ref> 标签引用你的自定义拦截器,并使用 name 属性为其指定一个名称。然后,使用 <result> 标签定义成功时的结果页面。例如,以下代码展示了如何使用自定义拦截器来拦截 /custom/* 路径下的所有请求:
<struts> <package name="default" extends="struts-default"> <interceptors> <interceptor name="customInterceptor" class="com.example.CustomInterceptor" /> </interceptors> <action name="customAction" class="com.example.CustomAction"> <interceptor-ref name="customInterceptor" /> <result name="success">/custom/success.jsp</result> </action> </package> </struts> 这样,当用户访问 /custom/* 路径下的任何请求时,Struts2 会使用你的自定义拦截器来处理这些请求。在拦截器的 intercept() 方法中,你可以编写自己的逻辑来处理这些请求。