View Javadoc

1   package org.limmen.crs.web.util;
2   
3   import java.util.ArrayList;
4   import java.util.List;
5   
6   import javax.faces.FacesException;
7   import javax.faces.application.ViewHandler;
8   import javax.faces.component.UIViewRoot;
9   import javax.faces.context.ExternalContext;
10  import javax.faces.context.FacesContext;
11  
12  public class SimpleNavigationHandler extends
13  		javax.faces.application.NavigationHandler {
14  
15  	private static String CMD_BACK = "_back";
16  
17  	private static String PAGE_HISTORY = "_history";
18  
19  	@SuppressWarnings("unchecked")
20  	@Override
21  	public void handleNavigation(FacesContext facesContext, String fromAction,
22  			String outcome) {
23  
24  		if (outcome == null) {
25  
26  			throw new FacesException("'outcome' must be filled!");
27  		}
28  
29  		List<String> history = null;
30  
31  		ExternalContext externalContext = facesContext.getExternalContext();
32  		history = (List) externalContext.getSessionMap().get(PAGE_HISTORY);
33  
34  		if (history == null) {
35  
36  			history = new ArrayList<String>();
37  			externalContext.getSessionMap().put(PAGE_HISTORY, history);
38  		}
39  
40  		if (outcome.endsWith(CMD_BACK)) {
41  
42  			// return to the previous page
43  			if (history.size() > 0) {
44  
45  				outcome = history.remove(history.size() - 1);
46  			}
47  			else {
48  
49  				// current page
50  				outcome = facesContext.getViewRoot().getViewId();
51  			}
52  		}
53  		else {
54  
55  			history.add(facesContext.getViewRoot().getViewId());
56  		}
57  
58  		ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
59  
60  		if (!outcome.startsWith("/")) {
61  
62  			outcome = "/" + outcome;
63  		}
64  
65  		// create new view
66  		UIViewRoot viewRoot = viewHandler.createView(facesContext, outcome);
67  		facesContext.setViewRoot(viewRoot);
68  		facesContext.renderResponse();
69  	}
70  }