半翻譯半整理的一些struts的東東,很淺顯的,歡迎指正(4)
發(fā)表時(shí)間:2023-07-17 來(lái)源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]二、出錯(cuò)管理(Managing Errors)Struts框架有兩個(gè)主要的類來(lái)管理出錯(cuò),一個(gè)是org.apache.struts.action.ActionError類,它對(duì)錯(cuò)誤信息進(jìn)行包裝。另一個(gè)...
二、出錯(cuò)管理(Managing Errors)
Struts框架有兩個(gè)主要的類來(lái)管理出錯(cuò),一個(gè)是org.apache.struts.action.ActionError類,它對(duì)錯(cuò)誤信息進(jìn)行包裝。另一個(gè)是org.apache.struts.action.ActionErrors類,它是ActionError實(shí)例的容器。這兩個(gè)類經(jīng)常要在ActionForm及Action類中使用。其具體的使用如下:
ActionErrors errors = new ActionErrors();
errors.add("propertyname", new ActionError("key");
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("key");
關(guān)于"propertyname"和ActionErrors.GLOBAL_ERROR,對(duì)前者用在ActionForm中,這里是對(duì)應(yīng)表現(xiàn)層(JSP)中的屬性值。而對(duì)后者則用在Action中,它對(duì)應(yīng)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, HttpServletResponseresponse) 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));
}
}
在表現(xiàn)層中表現(xiàn)錯(cuò)誤只須要寫(xiě)上<html:error />標(biāo)簽即可。