我需要记录从托管Bean触发的操作。此链接Logging the invoked managed bean action in a PhaseListener帮助我解决与操作相关的问题。但是,当我使用actionListener
时,我有NullPointerException
@Override
public void beforePhase(PhaseEvent event) {
FacesContext context = event.getFacesContext();
if (context.isPostback()) {
UICommand component = findInvokedCommandComponent(context);
if (component != null) {
String methodExpression = component.getActionExpression().getExpressionString();
// It'll contain #{bean.action}.
}
}
}
private UICommand findInvokedCommandComponent(FacesContext context) {
UIViewRoot view = context.getViewRoot();
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
if (context.getPartialViewContext().isAjaxRequest()) {
return (UICommand) view.findComponent(params.get("javax.faces.source"));
} else {
for (String clientId : params.keySet()) {
UIComponent component = view.findComponent(clientId);
if (component instanceof UICommand) {
return (UICommand) component;
}
}
}
return null;
}
NullPointerException
出现在行
String methodExpression = component.getActionExpression().getExpressionString();
如何获取actionListener
方法的名称?
我试过了
private UICommand findInvokedCommandComponent(FacesContext context) {
UIViewRoot view = context.getViewRoot();
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
if (context.getPartialViewContext().isAjaxRequest()) {
UIComponent component = view.findComponent(params.get("javax.faces.source"));
if (component instanceof UICommand) {
// component.get
UICommand comp= (UICommand) component;
ActionListener[] actionListeners= comp.getActionListeners();
System.out.println("Taille des Listeners : "+actionListeners.length);
ActionListener method;
method = actionListeners[0];
String toString = method.toString();
System.out.println("ActionListener : "+toString);
return (UICommand) component;
}
} else {
for (String clientId : params.keySet()) {
UIComponent component = view.findComponent(clientId);
if (component instanceof UICommand) {
return (UICommand) component;
}
}
}
return null;
}
System.out.println("ActionListener : "+toString); returns ActionListener : `javax.faces.event.MethodExpressionActionListener@16a779b` . What I would like to have is `#{bean.action}` .Maybe I did it the wrong way
答案 0 :(得分:2)
您处于良好的状态,但您需要获得实现MethodExpressionActionListener
的{{1}}。使用它,你仍然无法获得开箱即用的ActionListener
,可能唯一的方法是通过反射得到它(不是最好的东西......)。
也就是说,您可以像这样修改代码:
MethodExpression
您需要使用此方法从if (component != null) {
String methodExpression = "";
if(component.getActionExpression() != null)
{
methodExpression = component.getActionExpression().getExpressionString();
}
else if(component.getActionListeners().length > 0)
{
methodExpression = getActionListener((MethodExpressionActionListener)component.getActionListeners()[0]).getExpressionString();
}
System.out.println("Method Expression : " + methodExpression);
}
:
MethodExpressionActionListener