1.拦截器类:SimpleInterceptor
package elia;
import java.util.Date;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class SimpleInterceptor extends AbstractInterceptor{
// 拦截器的名字,使用setName()方法,从struts.xml配置文件中动态获得
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// 取得被拦截的action实例
LoginAction action = (LoginAction)invocation.getAction();
System.out.println(name + "Intercepter-----------"+
"Action begin: " + new Date());
long start = System.currentTimeMillis();
// 执行该拦截器的后一个拦截器,或者直接指定action的execute方法
String result = invocation.invoke();
System.out.println(name + "Intercepter-----------"+
"Action end: " + new Date());
long end = System.currentTimeMillis();
// 输出的name为对应action中指定的name,eg:renamed Interceptor,而不是簡単なInterceptor
System.out.println(name + "Intercepter-----------"+
"Action total time: " + (end - start));
return result;
}
}
2.LoginAction
package elia;
import javax.servlet.http.HttpServletRequest;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute() throws Exception {
HttpServletRequest ss;
if("wlx".equals(username) && "071208".equals(password)) {
return "success";
} else {
return "error";
}
}
// public void validate() {
//
// if(getUsername()== null || "".equals(getUsername().trim())){
// addFieldError("username", getText("ユーザ名は必要項目です!"));
// }
// }
}
3.Login.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Sign on</title>
</head>
<body>
<s:form action="Login">
<s:textfield name="username" label="ユーザ名称:"/>
<s:password name="password" label="密码:"/>
<s:submit />
</s:form>
</body>
</html>
4.struts.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="struts2" extends="struts-default">
<interceptors>
<interceptor name="SimpleInterceptor" class="elia.SimpleInterceptor">
<param name="name">簡単なInterceptor</param>
</interceptor>
</interceptors>
<action name="Login" class="elia.LoginAction">
<result name="input">/Login.jsp</result>
<result name="error">/error.jsp</result>
<result name="success">/Welcome.jsp</result>
// 这一句需要加上,因为如果为action指定了拦截器,默认的拦截器会失去作用,要使用默认的拦截器就必须加上
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="SimpleInterceptor">
<param name="name">renamed Interceptor</param>
</interceptor-ref>
</action>
</package>
</struts>