实验思路
- 编写Interceptor 继承 AbstractInterceptor类
- 重写public String intercept(ActionInvocation invocation)方法
- 编写struts2.xml
关键struts2.xml 代码
复制代码 my first interceptor
testuser 123 my changed interceptor 复制代码
目录结构
实验结果
代码(关键代码,文末有实验5github链接)
struts.xml
复制代码 my first interceptor /error.jsp /users/login_userLoginPage.do /users/login_userLoginPage ${directUrl} testadmin 123testuser 123 my changed interceptor ${directUrl}
MyInterceptor.java
package com.zy.javaee.interceptor;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;import com.zy.javaee.controller.actions.UserLoginAction;import com.zy.javaee.domin.User;import java.util.Date;import java.util.Map;/** * Created by Joey_Tsai on 2018/4/11. */public class MyInterceptor extends AbstractInterceptor { private String myInterceptorParam; private String defaultUsername; public String getDefaultPassword() { return defaultPassword; } public void setDefaultPassword(String defaultPassword) { this.defaultPassword = defaultPassword; } private String defaultPassword; public String getDefaultUsername() { return defaultUsername; } public void setDefaultUsername(String defaultUsername) { this.defaultUsername = defaultUsername; } // private String defaultPassword; public String getMyInterceptorParam() { return myInterceptorParam; } public void setMyInterceptorParam(String myInterceptorParam) { this.myInterceptorParam = myInterceptorParam; } //省略getter和setter @Override public String intercept(ActionInvocation invocation) throws Exception { // TODO Auto-generated method stub Map paramMap = invocation.getInvocationContext().getParameters(); String[] username = (String[]) paramMap.get("user.username"); String[] password = (String[]) paramMap.get("user.password"); String result; if (username != null && password != null){ String[] usernameParam = username[0].split(","); String[] passwordParam = password[0].split(","); User user = new User(); user.setUsername(usernameParam[0]); user.setPassword(passwordParam[0]); User defaultUser = new User(); defaultUser.setUsername(defaultUsername); defaultUser.setPassword(defaultPassword); UserLoginAction userLoginAction = (UserLoginAction) invocation.getAction(); userLoginAction.setUser(user); userLoginAction.setDefaultUser(defaultUser); System.out.println(myInterceptorParam + " 拦截器---开始执行登录Action的时间为" + new Date()); long start = System.currentTimeMillis(); result = invocation.invoke(); System.out.println(myInterceptorParam + " 拦截器---执行完登录Action的时间为" + new Date()); long end = System.currentTimeMillis(); System.out.println(myInterceptorParam + " 拦截器---执行Action的时间为" + (end - start) + "ms"); } else result = invocation.invoke(); return result; }}复制代码
GITHUB链接:https://github.com/joeytsai03/javaee_test5.git