请编写一个拦截器,该拦截器可以获得用户输入的用户名这个数据,业务逻辑为逐个判断用户名中是否包含“你”,“我”,“他”三个数据,如果包含则直接返回输入页面,如果不包含则运行至 PersonAction 。(除代码外,要给出拦截器和 Action 的配置文件)
时间: 2024-03-01 11:50:53 浏览: 40
拦截器代码:
```java
package com.example.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class UsernameInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String username = invocation.getInvocationContext().getParameters().get("username")[0];
if (username.contains("你") || username.contains("我") || username.contains("他")) {
return "input";
} else {
return invocation.invoke();
}
}
}
```
拦截器的功能是获取用户输入的用户名,然后判断是否包含“你”,“我”,“他”三个数据,如果包含则直接返回输入页面,否则继续执行后面的操作。
Action 配置文件:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<interceptors>
<interceptor name="usernameInterceptor" class="com.example.interceptor.UsernameInterceptor"></interceptor>
<interceptor-stack name="usernameStack">
<interceptor-ref name="usernameInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="usernameStack"></default-interceptor-ref>
<action name="person" class="com.example.action.PersonAction">
<result>/person.jsp</result>
</action>
</package>
</struts>
```
在 Action 配置文件中,我们定义了一个名为 `usernameInterceptor` 的拦截器,并将其添加到了拦截器栈 `usernameStack` 中。然后将 `usernameStack` 作为默认拦截器栈,并将其应用到 `person` 这个 Action 上。
最后,我们在 `person.jsp` 页面中添加一个表单用于输入用户名,并将表单提交到 `person` 这个 Action 上。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)