JSFUtils
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle; import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression; import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; /**
* General useful static utilies for working with JSF.
* NOTE: Updated to use JSF 1.2 ExpressionFactory.
*
* @author Duncan Mills
* @author Steve Muench
*
* $Id: JSFUtils.java 1885 2007-06-26 00:47:41Z ralsmith $
*/
public class JSFUtils { private static final String NO_RESOURCE_FOUND = "Missing resource: "; /**
* Method for taking a reference to a JSF binding expression and returning
* the matching object (or creating it).
* @param expression EL expression
* @return Managed object
*/
public static Object resolveExpression(String expression) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class);
return valueExp.getValue(elContext);
} /**
* @return
*/
public static String resolveRemoteUser() {
FacesContext facesContext = getFacesContext();
ExternalContext ectx = facesContext.getExternalContext();
return ectx.getRemoteUser();
} /**
* @return
*/
public static String resolveUserPrincipal() {
FacesContext facesContext = getFacesContext();
ExternalContext ectx = facesContext.getExternalContext();
HttpServletRequest request = (HttpServletRequest)ectx.getRequest();
return request.getUserPrincipal().getName();
} /**
* @param expression
* @param returnType
* @param argTypes
* @param argValues
* @return
*/
public static Object resolveMethodExpression(String expression,
Class returnType,
Class[] argTypes,
Object[] argValues) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
MethodExpression methodExpression =
elFactory.createMethodExpression(elContext, expression, returnType,
argTypes);
return methodExpression.invoke(elContext, argValues);
} /**
* Method for taking a reference to a JSF binding expression and returning
* the matching Boolean.
* @param expression EL expression
* @return Managed object
*/
public static Boolean resolveExpressionAsBoolean(String expression) {
return (Boolean)resolveExpression(expression);
} /**
* Method for taking a reference to a JSF binding expression and returning
* the matching String (or creating it).
* @param expression EL expression
* @return Managed object
*/
public static String resolveExpressionAsString(String expression) {
return (String)resolveExpression(expression);
} /**
* Convenience method for resolving a reference to a managed bean by name
* rather than by expression.
* @param beanName name of managed bean
* @return Managed object
*/
public static Object getManagedBeanValue(String beanName) {
StringBuffer buff = new StringBuffer("#{");
buff.append(beanName);
buff.append("}");
return resolveExpression(buff.toString());
} /**
* Method for setting a new object into a JSF managed bean
* Note: will fail silently if the supplied object does
* not match the type of the managed bean.
* @param expression EL expression
* @param newValue new value to set
*/
public static void setExpressionValue(String expression, Object newValue) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class); //Check that the input newValue can be cast to the property type
//expected by the managed bean.
//If the managed Bean expects a primitive we rely on Auto-Unboxing
Class bindClass = valueExp.getType(elContext);
if (bindClass.isPrimitive() || bindClass.isInstance(newValue)) {
valueExp.setValue(elContext, newValue);
}
} /**
* Convenience method for setting the value of a managed bean by name
* rather than by expression.
* @param beanName name of managed bean
* @param newValue new value to set
*/
public static void setManagedBeanValue(String beanName, Object newValue) {
StringBuffer buff = new StringBuffer("#{");
buff.append(beanName);
buff.append("}");
setExpressionValue(buff.toString(), newValue);
} /**
* Convenience method for setting Session variables.
* @param key object key
* @param object value to store
*/ public static void storeOnSession(String key, Object object) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getSessionMap();
sessionState.put(key, object);
} /**
* Convenience method for getting Session variables.
* @param key object key
* @return session object for key
*/
public static Object getFromSession(String key) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getSessionMap();
return sessionState.get(key);
} /**
* @param key
* @return
*/
public static String getFromHeader(String key) {
FacesContext ctx = getFacesContext();
ExternalContext ectx = ctx.getExternalContext();
return ectx.getRequestHeaderMap().get(key);
} /**
* Convenience method for getting Request variables.
* @param key object key
* @return session object for key
*/
public static Object getFromRequest(String key) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getRequestMap();
return sessionState.get(key);
} /**
* Pulls a String resource from the property bundle that
* is defined under the application <message-bundle> element in
* the faces config. Respects Locale
* @param key string message key
* @return Resource value or placeholder error String
*/
public static String getStringFromBundle(String key) {
ResourceBundle bundle = getBundle();
return getStringSafely(bundle, key, null);
} /**
* Convenience method to construct a <code>FacesMesssage</code>
* from a defined error key and severity
* This assumes that the error keys follow the convention of
* using <b>_detail</b> for the detailed part of the
* message, otherwise the main message is returned for the
* detail as well.
* @param key for the error message in the resource bundle
* @param severity severity of message
* @return Faces Message object
*/
public static FacesMessage getMessageFromBundle(String key,
FacesMessage.Severity severity) {
ResourceBundle bundle = getBundle();
String summary = getStringSafely(bundle, key, null);
String detail = getStringSafely(bundle, key + "_detail", summary);
FacesMessage message = new FacesMessage(summary, detail);
message.setSeverity(severity);
return message;
} /**
* Add JSF info message.
* @param msg info message string
*/
public static void addFacesInformationMessage(String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_INFO, msg, "");
ctx.addMessage(getRootViewComponentId(), fm);
} /**
* Add JSF error message.
* @param msg error message string
*/
public static void addFacesErrorMessage(String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, "");
ctx.addMessage(getRootViewComponentId(), fm);
} /**
* Add JSF error message for a specific attribute.
* @param attrName name of attribute
* @param msg error message string
*/
public static void addFacesErrorMessage(String attrName, String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_ERROR, attrName, msg);
ctx.addMessage(getRootViewComponentId(), fm);
} // Informational getters /**
* Get view id of the view root.
* @return view id of the view root
*/
public static String getRootViewId() {
return getFacesContext().getViewRoot().getViewId();
} /**
* Get component id of the view root.
* @return component id of the view root
*/
public static String getRootViewComponentId() {
return getFacesContext().getViewRoot().getId();
} /**
* Get FacesContext.
* @return FacesContext
*/
public static FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
/*
* Internal method to pull out the correct local
* message bundle
*/ private static ResourceBundle getBundle() {
FacesContext ctx = getFacesContext();
UIViewRoot uiRoot = ctx.getViewRoot();
Locale locale = uiRoot.getLocale();
ClassLoader ldr = Thread.currentThread().getContextClassLoader();
return ResourceBundle.getBundle(ctx.getApplication().getMessageBundle(),
locale, ldr);
} /**
* Get an HTTP Request attribute.
* @param name attribute name
* @return attribute value
*/
public static Object getRequestAttribute(String name) {
return getFacesContext().getExternalContext().getRequestMap().get(name);
} /**
* Set an HTTP Request attribute.
* @param name attribute name
* @param value attribute value
*/
public static void setRequestAttribute(String name, Object value) {
getFacesContext().getExternalContext().getRequestMap().put(name,
value);
} /*
* Internal method to proxy for resource keys that don't exist
*/ private static String getStringSafely(ResourceBundle bundle, String key,
String defaultValue) {
String resource = null;
try {
resource = bundle.getString(key);
} catch (MissingResourceException mrex) {
if (defaultValue != null) {
resource = defaultValue;
} else {
resource = NO_RESOURCE_FOUND + key;
}
}
return resource;
} /**
* Locate an UIComponent in view root with its component id. Use a recursive way to achieve this.
* @param id UIComponent id
* @return UIComponent object
*/
public static UIComponent findComponentInRoot(String id) {
UIComponent component = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
UIComponent root = facesContext.getViewRoot();
component = findComponent(root, id);
}
return component;
} /**
* Locate an UIComponent from its root component.
* Taken from http://www.jroller.com/page/mert?entry=how_to_find_a_uicomponent
* @param base root Component (parent)
* @param id UIComponent id
* @return UIComponent object
*/
public static UIComponent findComponent(UIComponent base, String id) {
if (id.equals(base.getId()))
return base; UIComponent children = null;
UIComponent result = null;
Iterator childrens = base.getFacetsAndChildren();
while (childrens.hasNext() && (result == null)) {
children = (UIComponent)childrens.next();
if (id.equals(children.getId())) {
result = children;
break;
}
result = findComponent(children, id);
if (result != null) {
break;
}
}
return result;
} /**
* Method to create a redirect URL. The assumption is that the JSF servlet mapping is
* "faces", which is the default
*
* @param view the JSP or JSPX page to redirect to
* @return a URL to redirect to
*/
public static String getPageURL(String view) {
FacesContext facesContext = getFacesContext();
ExternalContext externalContext = facesContext.getExternalContext();
String url =
((HttpServletRequest)externalContext.getRequest()).getRequestURL().toString();
StringBuffer newUrlBuffer = new StringBuffer();
newUrlBuffer.append(url.substring(0, url.lastIndexOf("faces/")));
newUrlBuffer.append("faces");
String targetPageUrl = view.startsWith("/") ? view : "/" + view;
newUrlBuffer.append(targetPageUrl);
return newUrlBuffer.toString();
} }
JSFUtils的更多相关文章
- adf常用方法总结
1.使用clientAttribute传值.获取值 或组件上面放客户端属性 <af:selectBooleanCheckbox text="" label="&qu ...
- ADF 入门帮助
本文是由英文帮助翻译所得: 1>task flows “任务流 task flows”可以包括非可视化的组件,比如方法调用.“页片段 page fragment”可以运行在一个页面的某个局部区域 ...
- adf笔记
1>jsf页面js调试,手动添加debugger调试 方案:在页面中添加debugger,然后打开“开发者工具”(必须打开),直接运行页面自动跳转到debugger处. 2>jdevelo ...
随机推荐
- vue2.0的虚拟DOM渲染
1.为什么需要虚拟DOM 前面我们从零开始写了一个简单的类Vue框架(文章链接),其中的模板解析和渲染是通过Compile函数来完成的,采用了文档碎片代替了直接对页面中DOM元素的操作,在完成数据的更 ...
- [javaEE] EL表达式获取数据
jsp标签: <jsp:include> <jsp:forward> 实现请求转发 <jsp:param> 给上面的添加参数的 EL表达式: 1.获取变量数据 &l ...
- jsp servlet基础复习 Part1
jsp和servlet的一些基础知识整理,用于备忘. 一.jsp与servlet的基本关系 1.jsp-->web容器-->servlet-->加载进容器的虚拟机执行-->输出 ...
- Java 基础(7)——运算符
学完基础的变量常量等知识.再往后和变量常量紧密相关的当然是加减乘除等等运算方法了~(当然加减乘除也只是一部分) 首先按照运算过程参与的元素,把运算符号简单粗暴的分为一元运算符.二元运算符.三元运算符等 ...
- Spring Cloud实战之初级入门(六)— 服务网关zuul
目录 1.环境介绍 2.api网关服务 2.1 创建工程 2.3 api网关中使用token机制 2.4 测试 2.5 小结 3.一点点重要的事情 1.环境介绍 好了,不知不觉中我们已经来到了最后一篇 ...
- js 去除空格回车换行
开发中遇到特殊需求,需要将空格回车换行替换成逗号 直接使用正则表达式解决: 变量.replace(/\s+/g,","); 如果想要去除则将后面逗号变成空就OK了.
- SQL COUNT DISTINCT
Create table trade ( sell_id int, --卖家 buy_id int, -- 卖家 time date --交易时间 ) sell_id, buy_id, time s ...
- 解决 spring cloud 项目的 com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect 错误信息
在项目中引入:引入hystrix依赖,如下 <dependency> <groupId>org.springframework.cloud</groupId> &l ...
- TextView的跑马灯效果(AS开发实战第二章学习笔记)
TextView的跑马灯效果跑马灯用到的属性与方法说明singleLine 指定文本是否单行显示ellipsize 指定文本超出范围后的省略方式focusable 指定是否获得焦点,跑马灯效果要求设置 ...
- HTML 5篇(持续更新)
1.sessionStorage .localStorage 和 cookie 之间的区别 (一)共同点:都是保存在浏览器端,且同源的. (二)区别:cookie数据始终在同源的http请求中携带(即 ...