2009年1月10日星期六

JSF_010:JSF FacesContext

在JSF中,所有请求都由FacesServlet处理,它会为每一个请求创建一个javax.faces. context. FacesContext类的实例。
那么,如何获取当前的FacesContext实例呢?很简单,FacesContext facesContext = FacesContext.getCurrentInstance(); 。
至于我们熟悉的其它对象信息,如ServletContext、ServletRequest和ServletResponse,则是通过获取ExternalContext后,调用相应方法再获取。

1. 获取ServletContext对象
Object contextAttribute = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map contextMap = externalContext.getApplicationMap();
if (contextMap!=null)
contextAttribute = contextMap.get("user");

String initParam = externalContext.getInitParameter("userName");

Map paramMap = externalContext.getInitParameterMap();
if (paramMap!=null)
System.out.println(paramMap.get("userName"));

2. 获取Session中的参数值
Object sessionAttribute = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map sessionMap = externalContext.getSessionMap();
if (sessionMap!=null)
sessionAttribute = sessionMap.get(key);

3. 获取Resquest 对象
Object requestAttribute = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map requestMap = externalContext.getRequestMap();
if (requestMap!=null)
requestAttribute = requestMap.get(key);

Map requestParameterMap = externalContext.getRequestParameterMap();
if (requestParameterMap!=null)
id = (String) requestParameterMap.get("id"); Map requestParameterMap = externalContext.getRequestParameterMap();
Iterator parameterNames = externalContext.getRequestParameterNames();
while (parameterNames.hasNext()) {
String parameterName = (String) parameterNames.next();
String parameterValue =(String) requestParameterMap.get(parameterName);
System.out.println(parameterName + " : " + parameterValue);
}

Map requestParameterValuesMap = externalContext.getRequestParameterValuesMap();
if (requestParameterValuesMap!=null) {
id = (String[]) requestParameterValuesMap.get("id");
for (int i=0; i<id.length; i++) {
System.out.println(id[i]);
}
}


Map headerMap = externalContext.getRequestHeaderMap();
if (headerMap!=null) {
host = (String) headerMap.get("host");
System.out.println(host);
}

Map headerValuesMap = externalContext.getRequestHeaderValuesMap();
if (headerValuesMap!=null) {
Enumeration headers =(Enumeration) headerValuesMap.get("Accept-Encoding");
while (headers.hasMoreElements()) {
String value = (String) headers.nextElement();
System.out.println(value);
}
}

4. 获取Managed Bean
FacesContext context = FacesContext.getCurrentInstance();
ValueBinding binding =context.getApplication().createValueBinding("#{user}");
UserBean user = (UserBean) binding.getValue(context);

没有评论: