- 论坛徽章:
- 0
|
一个简单的入门例子
我们编写一个简单web应用,一个注册页面,当两次输入的密码相同时,进入success页面,反之,进入fail页面,在eclipse中的工程结构如下:
file:///C:/Documents%20and%20Settings/daijing/My%20Documents/My%20Pictures/temp.gif
这个应用主要由两个struts配置文件,两个java文件,三个jsp文件构成,文件内容和功能如下:
struts-config.xml
http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd
">
定义了一个action路径,只要是/webapp/register.do的请求,Struts的中心控制器ActionServlet委托RegisterAction处理信息,RegisterAction实例化registerForm后,接收参数,处理后向浏览器返回页面success或failure。
web.xml
http://java.sun.com/xml/ns/j2ee
" xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance
" version="2.4" xsi:schemaLocation="
http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd
">
action
org.apache.struts.action.ActionServlet
config
/WEB-INF/struts-config.xml
debug
3
detail
3
0
action
*.do
RegisterForm.java
package app;
import org.apache.struts.action.*;
public class RegisterForm extends ActionForm {
protected String username;
protected String password1;
protected String password2;
public String getUsername () {return this.username;};
public String getPassword1() {return this.password1;};
public String getPassword2() {return this.password2;};
public void setusername (String username) {this.username = username;};
public void setpassword1(String password) {this.password1 = password;};
public void setpassword2(String password) {this.password2 = password;};
}
RegisterAction.java的内容
package app;
import org.apache.struts.action.*;
import javax.servlet.http.*;
public class RegisterAction extends Action {
public ActionForward perform (ActionMapping mapping,ActionForm form,HttpServletRequest req,
HttpServletResponse res) {
// ①Cast the form to the RegisterForm
RegisterForm rf = (RegisterForm) form;
String username = rf.getUsername();
String password1 = rf.getPassword1();
String password2 = rf.getPassword2();
// ②Apply business logic
if (password1.equals(password2)) {
try {
// ③Return ActionForward for success
return mapping.findForward("success");
} catch (Exception e) {
return mapping.findForward("failure");
} }
// ④Return ActionForward for failure
return mapping.findForward("failure");
}
}
register.jsp
UserName:
enter password:
re-enter password:
这里要注意,register.do的后缀要和web.xml中action定义的后缀一致,RegisterForm.java中的参数要和register.jsp中的参数一致。
success.html
SUCCESS
Registration succeeded!
try another?
failure.html
FAILURE
Registration failed!
try again?
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/7859/showart_31432.html |
|