一、简单表单验证示例
structs.xml配置
<struts> <package name="validate" namespace="/validate" extends="struts-default" > <action name="ValidateDemo" class="cn.hjp.validate.ValidateDemo"> <result name="success" type="dispatcher" >/validate/index.jsp</result> <result name="input" type="dispatcher" >/validate/index.jsp</result> </action> </package> </struts>
前端index页面部分代码:fielderror显示错误信息,如果前端页面HTML标签是使用的structs2标签构成,则可以不使用fielderror标签也能显示,如下面注释中代码
<%@ taglib prefix="s" uri="/struts-tags" %> <!-- <body> <s:form action="ValidateDemo" namespace="/validate" > <s:textfield name="name" label="用户名" ></s:textfield> <s:submit value="提交" ></s:submit> </s:form> </body> --> <body> <form action="/struts2-demo/validate/ValidateDemo.action" method="post" > <input type="text" name="name" /><input type="submit" value="提交"/> </form> <s:fielderror fieldName="name" /> </body>
验证判断代码写在validate方法中
public class ValidateDemo extends ActionSupport { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String execute() throws Exception { // TODO Auto-generated method stub System.out.println(this.toString()); return SUCCESS; } @Override public void validate() { // TODO Auto-generated method stub if (this.name == null || this.name.equals("")) { addFieldError("name", "姓名不能为空"); } } }
时间: 2024-11-09 04:39:51