JSF和Struts框架的错误掌握与封装处理[Java编程]
本文“JSF和Struts框架的错误掌握与封装处理[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
在struts中,普通采取的全局错误掌握情势是构建一个baseAction,在其execute办法中完成前台传回办法的dispatch操作,并由 try……catch……捕捉程序错误,实现错误的掌握和展示.一个典型的BaseAction例子以下:
代码
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
……
ActionForward forwardPage = null;
try {
String parameter = mapping.getParameter();
if (parameter == null) {
String message = messages.getMessage("dispatch.handler",mapping.getPath());
response.sendError(500, message);
return null;
}
String name = processReqCode(request.getParameter(parameter));
forwardPage = dispatchMethod(mapping, form, request, response, name);
} catch (BaseException ex) {
if (log.isDebugEnabled())
log.debug("发生错误:", ex);
forwardPage = processBaseException(request, mapping, ex);
} catch (Throwable ex) {
log.error("发生错误:", ex);
ActionMessages errors = new ActionMessages();
ByteArrayOutputStream ostr = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(ostr));
errors.add("org.apache.struts.action.GLOBAL_MESSAGE", new ActionMessage
(ostr.toString()));
saveErrors(request, errors);
forwardPage = mapping.findForward("syserror");
output.setStatus("fail");
output.setError(ex.getMessage());
}
……
}
由于JSF采取了managed bean,JSP页面直接通过调用managed bean中的办法完成数据交互,不能像struts一样通过捕捉dispatch操作历程抛出的非常来完成错误的处理(因为根本就没有dispatch办法),仿佛jsf根本就不支持全局的错误处理.
假如在managed bean中throw 一个exception(这里是AppException),察看一下掌握台的日记,可以看到其实错误是从一个ActionListener的实现中抛出的(针对myfaces,这里是ActionListenerImpl),参考jsf的生命周期历程,办法出来了:
代码
public class GlobalActionListener extends ActionListenerImpl {
public void processAction(ActionEvent event) throws AbortProcessingException {
FacesContext facesContext = FacesContext.getCurrentInstance();
Application application = facesContext.getApplication();
ActionSource actionSource = (ActionSource) event.getComponent();
MethodBinding methodBinding = actionSource.getAction();
String fromAction = null;String outcome = null;
if (methodBinding != null) {
fromAction = methodBinding.getExpressionString();
try {
outcome = (String) methodBinding.invoke(facesContext, null);
} catch (EvaluationException e) {
Throwable cause = e.getCause();
if (cause != null && cause instanceof AppException) {
//这里需求按照框架的差别,判断实例能否是程序中手动抛出的错误
FacesUtils.addErrorMessage(event.getComponent().getClientId(facesContext),
cause.getMessage());}
else {
throw (AbortProcessingException) cause;
}
} catch (RuntimeException e) {
throw new FacesException("Error calling action method of component with id " +
event.getComponent().getClientId(facesContext), e);
}
NavigationHandler navigationHandler = application.getNavigationHandler();
navigationHandler.handleNavigation(facesContext, fromAction, outcome);
// Render Response if needed
facesContext.renderResponse();
}
}
以上是“JSF和Struts框架的错误掌握与封装处理[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |