如何将Apex类的Body内容正确传递至Visualforce页面
解决Apex类数据传递到Visualforce页面的方法
你的现有Apex类里的getApexClassInfo是静态的@AuraEnabled方法,更适合LWC组件调用,要在Visualforce页面中使用,需要调整类结构并修改页面绑定方式,具体步骤如下:
1. 修改ApexParser类
添加实例变量存储查询结果,并通过构造函数从URL参数获取目标类名,同时给原方法增加异常处理避免页面报错:
public with sharing class ApexParser { // 定义实例变量,供Visualforce页面绑定访问 public ApexClass currentApexClass {get; set;} // 构造函数:从URL参数获取类名并查询数据 public ApexParser() { String apexClassName = ApexPages.currentPage().getParameters().get('className'); if(String.isNotBlank(apexClassName)) { currentApexClass = getApexClassInfo(apexClassName); } } @AuraEnabled(cacheable=true) public static ApexClass getApexClassInfo(String ApexClassName) { try { return [ SELECT Name, Body FROM ApexClass WHERE Name =: ApexClassName LIMIT 1 ]; } catch(QueryException e) { // 查询不到目标类时返回null,避免页面报错 return null; } } }
2. 修改Visualforce页面
将outputText绑定到实例变量的Body属性,并设置escape="false"防止代码符号被HTML转义:
<apex:page controller="ApexParser" renderAs="pdf" applyHtmlTag="false" showHeader="false" cache="true" readOnly="true"> <apex:pageBlock> <h1>Test to see if this will generate</h1> <!-- 绑定到currentApexClass的Body属性,关闭转义保证代码正常显示 --> <apex:outputText value="{!currentApexClass.Body}" escape="false"/> <h2><p>END</p></h2> </apex:pageBlock> </apex:page>
3. 访问页面方式
打开页面时,需要在URL后拼接目标类名参数,例如:/apex/你的页面名称?className=要查询的Apex类名
比如你的页面叫ApexClassViewer,要查询AccountTriggerHandler类,就访问:/apex/ApexClassViewer?className=AccountTriggerHandler
内容的提问来源于stack exchange,提问作者Jhony
相关产品推荐
相关产品推荐

