当前位置:编程学习 > JSP >>

半翻译半整理的一点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的<global-forwards />中描述的信息。例子:
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));
    }
}
在表现层中表现错误只须要写上<html:error />标签即可。

上一个:HTML、Swing还是XML,Java客户端工具选择?(四) 转
下一个:半翻译半整理的一点struts的东东,很浅显的,欢迎指正(三)

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,