先说说ActionError,
一般的情况下我们会自己写的ActionForm的validate方法来对提交过来的表单做验证
开始的时候我也是在想这个仅仅是return 了一个ActionErrors
这里是我的form源码
package com.little.struts.form;
public class HelloForm extends ActionForm {
private String username;
public String getUsername() {
return username;
}
public ActionErrors validate(ActionMapping mapping,//这里就是我们做验证的
HttpServletRequest request) {
ActionErrors errors=new ActionErrors();
if(username==null||username.length()<1){
errors.add("error", new ActionMessage("test"));//就是我的国际化文件中的key
}
System.out.println("ActionErrors validate");
return errors;
}
public void setUsername(String username) {
this.username = username;
}
}
下面我的国际化文件ApplicationResource.properties
usernull=welcome to java World !{0}//这个{0}是表示一个占位符的,以便我们以后来动态地改变
test=username is null
下面是我的Action的源码
package com.little.struts.action;
import com.little.struts.form.HelloForm;
public class HelloAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
HelloForm helloForm = (HelloForm) form;
ActionMessages msgs=new ActionMessages();//创建一个消息的类似如容器的东东
ActionMessage msg=new ActionMessage("usernull",helloForm.getUsername());//真正的消息
//usernull就是国际化文件中的一个key
//helloForm.getUsername()就填充了国际化文件中的{0}
msgs.add("name", msg); //添加消息到容器,
//我发现name是可以随便取名的
this.saveMessages(request, msgs); //这个实际上就是把消息容器放到request中的Attribute里
return mapping.findForward("hello");
}
}
这样我们就只剩下如何在jsp页面中读取消息了
<%@ page language="java" pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<body>
<html:messages id="msg" message="true"> //message的属性默认的是false也就是错误的信息
<bean:write name="msg"/>
</html:messages>
<html:errors/> //这里当然是输出错误信息啦
<html:form action="/hello">
username : <html:text property="username"/> //当然这里的form也可写成html的形式
<html:submit/>
</html:form>
</body>
</html>
讲到了这里是不是发现有一个疑问,error发生的时候是如何实现跳转的???
下面请看我的struts-config.xml
<struts-config>
<data-sources />
<form-beans >
<form-bean name="helloForm" type="com.little.struts.form.HelloForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="helloForm"
input="/form/hello.jsp" //这里就是当错误发生的时候跳转路径
name="helloForm"
path="/hello"
scope="request"
type="com.little.struts.action.HelloAction" >
<forward name="hello" path="/form/hello.jsp"></forward>
</action>
</action-mappings>
<message-resources parameter="com.little.struts.ApplicationResources" />//国际化文件配置
</struts-config>
总结;
当error发生的时候,struts也像是一个中断一样,直接的跳转
标签:username,ActionErrors,ActionMessage,form,struts,ActionError,HelloForm,public From: https://blog.51cto.com/u_16065168/6443065