半翻译半整理的一点struts的东东,很浅显的,欢迎指正(四)-JSP技术-3P代码网
繁体中文
设为首页
加入收藏
当前位置:JSP技术首页 >> 资料/其它 >> 半翻译半整理的一点struts的东东,很浅显的,欢迎指正(四)

半翻译半整理的一点struts的东东,很浅显的,欢迎指正(四)

2004-10-01 08:26:10  作者:  来源:互联网  浏览次数:10  文字大小:【】【】【
简介:二、    出错管理(Managing Errors) Struts框架有两个主要的类来管理出错,一个是org.apache.struts.action.ActionError类,它对错误信息进行包装。另一个是org.apache.struts.action.Actio...
关键字:东东 浅显 struts 一点

二、 出错管理(Managing Errors)

Struts框架有两个主要的类来管理出错,一个是org.apache.struts.action.ActionError类,它对错误信息进行包装。另一个是org.apache.struts.action.ActionErrors类,它是ActionError实例的容器。这两个类经常要在ActionForm及Action类中使用。其具体的使用如下:

ActionErrors errors = new ActionErrors();

errors.add("propertyname", new ActionError("key");

errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("key");

关于"propertyname"和ActionErrors.GLOBAL_ERROR,对前者用在ActionForm中,这里是对应表现层(JSP)中的属性值。而对后者则用在Action中,它对应struts-config.xml的中描述的信息。例子:

ActionForm类:

public class LoginForm extends ActionForm {

…………………

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if ( (username == null ) || (username.length() == 0) ) {

errors.add("username",new ActionError("errors.username.required"));

}

if ( (password == null ) || (password.length() == 0) ) {

errors.add("password",new ActionError("errors.password.required"));

}

return errors;

}

…………………

}

Action类:

public class LoginAction extends Action {

……………………

public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

String user = null;

// Default target to success

String target = "success";

// Use the LoginForm to get the request parameters

String username = ((LoginForm)form).getUsername();

String password = ((LoginForm)form).getPassword();

user = getUser(username, password);

// Set the target to failure

if ( user == null ) {

target = "login";

ActionErrors errors = new ActionErrors();

errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("errors.login.unknown",username));

// Report any errors we have discovered back to the

// original form

if (!errors.empty()) {

saveErrors(request, errors);

}

}

else {

HttpSession session = request.getSession();

session.setAttribute("USER", user);

}

// Forward to the appropriate View

return (mapping.findForward(target));

}

}

在表现层中表现错误只须要写上标签即可。

责任编辑:admin
相关文章