(1)建立业务控制器:
package com.my.ccit;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
public class Reg extends ActionSupport{
private String username;
private String password1;
private String password2;
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String execute() throws Exception {
if(username!=null && getPassword1().equals(getPassword2()) &&!getUsername().trim().equals(""))
{
System.out.println("Action 信息:正在执行Action......");
return SUCCESS;
}
else
{
return INPUT;
}
}
}
(2)建立拦截器类:
package com.my.ccit;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class Myinterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation arg0) throws Exception {
Reg reg=(Reg)arg0.getAction();
System.out.println("拦截器信息:HelloWorld拦截器!");
String result=arg0.invoke();//执行Action或者下一个拦截器
System.out.println("拦截器信息:Action执行完毕!");
return result;
}
}
(3)配置文件struts.xml
<interceptors>
<interceptor name="Myinterceptor"
class="com.my.ccit.Myinterceptor">
</interceptor>
</interceptors>
......
<action name="Reg" class="com.my.ccit.Reg">
<result name="success">/regSuccess.jsp</result>
<result name="input">/reg.jsp</result>
<!-- 引用默认拦截器 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 引用自定义默认拦截器 -->
<interceptor-ref name="Myinterceptor"></interceptor-ref>
<!-- <interceptor-ref name="SimpleInterceptor"></interceptor-ref>-->
</action>
(4) 表现层
reg.jsp:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>UI Tags Example</title>
<s:head/>
</head>
<body>
<table>
<s:form id="id" action="Reg.action">
<s:textfield name="username" label="用户名"/>
<s:textfield name="password1" label="密码"/>
<s:textfield name="password2" label="确认密码"/>
<s:datetimepicker name="birthday" label="生日" displayFormat="yyyy-MM-dd" />
<s:submit value="注册"/>
</s:form>
</table>
</body>
</html>
从以上可以看出,spring的方式比struct更加灵活。