catch exception in managed bean and show message on screen in jsf2

社会主义新天地 提交于 2019-12-08 08:52:35

问题


I'm using JSF 2 and I'm getting some exception while I'm using some web service and I want to catch that exception and display the message on my .xhtml page.

How can I do that?


回答1:


You can use the try-catch block to catch and handle the exception. You can use FacesContext#addMessage() to add a faces message to the faces context. You can use <h:messages> to display faces messages.

So, something like this in the bean:

try {
    data = yourWebService.retrieve();
} catch (YourWebServiceException e) {
    String message = "Failed to retrieve data from webservice: " + e.getMessage());
    FacesContext.getCurrentInstance().addMessage(null, 
        new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
    e.printStackTrace(); // Or use a logger.
}

And this in the JSF page:

<h:messages globalOnly="true" />

(the globalOnly="true" will force the <h:messages> to only show messages with a null client ID)




回答2:


To give you an example to what BalusC has explained, you could write a simple method that gets called in a catch statement.

private void addErrorMessage(String msg, String clientId) {
        String codingErrorMsgKey = "coding_error_msg";
        FacesMessage fm;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (StringUtils.isEmpty(msg)) {
            ResourceBundle bundle = facesContext.getApplication().getResourceBundle(facesContext, "bundle");
            fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, bundle.getString(codingErrorMsgKey), bundle.getString(codingErrorMsgKey));
        }
        else {
            fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
        }
        facesContext.addMessage(clientId, fm);
    }

What the method does is really simple : you give it a message that you may have resolved earlier form your application's resource bundle, then a global (only if clientId is null) error (because of FacesMessage.SEVERITY_ERROR) FacesMessage is created. The created error message is then added to the facesContext using a default string as the message if you didn't provide any.

Since this method is able to create global and clientId-related error messages, you won't have to use globalOnly property. Simply specify <h:messages/> to have the tag display all of your messages (global or not).

Again, this only is sample code. You may have to adjust/improve to make it your own. Also, you could almost duplicate this method to handle information messages.

As a generic way of dealing with error messages, you could make this method available in a super class that every controller would then extend.



来源:https://stackoverflow.com/questions/13297328/catch-exception-in-managed-bean-and-show-message-on-screen-in-jsf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!