1.编写java类,代码如下:
package com.koubei;
import com.opensymphony.xwork2.ActionSupport;
public class Regist extends ActionSupport{
private String name;
private int age; //这里有的教程里会设置成Integer类型,不过运行时是会提示错误的
private String message;
public void validateRegist(){
if(name==null||"".equals(name)){
this.addFieldError("name", "请输入名字");
}
if(age<13 || age>25){
this.addFieldError("age", "年龄在13到25之间");
}
}
public String regist(){
message = "恭喜"+this.name+"注册成功";
return SUCCESS;
}
//get、set方法自己写吧
}
2.注册主页面Regist.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>注册页面</title>
</head>
<body>
<s:form action="Regist.action">
<s:textfield name="name" label="姓名" />
<s:fielderror>
<s:param>name</s:param>
</s:fielderror>
<s:textfield name="age" label="年龄" />
<s:fielderror>
<s:param>age</s:param>
</s:fielderror>
<s:submit value="提交"></s:submit>
</s:form>
</body>
</html>
注册成功后跳转的Succeed.jsp页面:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>注册成功页面</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
3.struts.xml文件中的配置:
<action name="Regist" class="com.koubei.Regist" method="regist">
<result>/Succeed.jsp</result>
<result name="input">/Regist.jsp</result>
</action>
打开服务器,在浏览器中输入http://localhost:8080/XXX/Regist.jsp运行即可。