有一種簡單的方法可以調整它以生成所需的任何輸出,以將JSP轉換為所需的任何形式,包括頁面的對象模型:
- 定義一個Node.Visitor子類來處理JSP的節點(標簽等)
- 編寫一個簡單的Compiler子類,重寫其generateJava()來調用訪問者
- 繼承編譯器執行器JspC的子類,重寫其方法getCompilerClassName()以返回您的編譯器的類
讓我們看一下代碼。
實作
1.自定義訪問者
編譯器將調用Visitor來處理已解析的JSP的樹對象模型。 此實現僅打印有關頁面中有趣的節點子集的信息,以使其嵌套清晰。
package org.apache.jasper.compiler;import java.util.LinkedList;
import org.apache.jasper.JasperException;
import org.apache.jasper.compiler.Node.CustomTag;
import org.apache.jasper.compiler.Node.ELExpression;
import org.apache.jasper.compiler.Node.IncludeDirective;
import org.apache.jasper.compiler.Node.Visitor;
import org.xml.sax.Attributes;public class JsfElCheckingVisitor extends Visitor {private String indent = "";@Overridepublic void visit(ELExpression n) throws JasperException {logEntry("ELExpression", n, "EL: " + n.getEL());super.visit(n);}@Overridepublic void visit(IncludeDirective n) throws JasperException {logEntry("IncludeDirective", n, toString(n.getAttributes()));super.visit(n);}@Overridepublic void visit(CustomTag n) throws JasperException {logEntry("CustomTag", n, "Class: " + n.getTagHandlerClass().getName() + ", attrs: "+ toString(n.getAttributes()));doVisit(n);indent += " ";visitBody(n);indent = indent.substring(0, indent.length() - 1);}private String toString(Attributes attributes) {if (attributes == null || attributes.getLength() == 0) return "";LinkedList<String> details = new LinkedList<String>();for (int i = 0; i < attributes.getLength(); i++) {details.add(attributes.getQName(i) + "=" + attributes.getValue(i));}return details.toString();}private void logEntry(String what, Node n, String details) {System.out.println(indent + n.getQName() + " at line:"+ n.getStart().getLineNumber() + ": " + details);}}
筆記:
- 訪客必須位于org.apache.jasper.compiler包中,因為基本類org.apache.jasper.compiler.Node是包私有的
- visitBody方法觸發對嵌套節點的處理
- 還有更多我可以覆蓋的方法(和通行方法doVisit),但是我只選擇了對我來說有趣的那些方法
- 節點的屬性為... sax類型。 Attributes ,它包含屬性名稱和值作為字符串
- attribute.getType(i)通常是CDATA
- Node結構包含有關父節點,標簽名稱,標簽處理程序類,源文件的相應行以及源文件的名稱的信息以及其他有用信息
- CustomTag可能是最有趣的節點類型,例如,所有JSF標簽都屬于這種類型
輸出示例(對于JSF頁面)
jsp:directive.include at line:5: [file=includes/stdjsp.jsp]
jsp:directive.include at line:6: [file=includes/ssoinclude.jsp]
f:verbatim at line:14: Class: com.sun.faces.taglib.jsf_core.VerbatimTag, attrs:
htm:div at line:62: Class: com.exadel.htmLib.tags.DivTag, attrs: [style=width:100%;]h:form at line:64: Class: com.sun.faces.taglib.html_basic.FormTag, attrs: [id=inputForm]htm:table at line:66: Class: com.exadel.htmLib.tags.TableTag, attrs: [cellpadding=0, width=100%, border=0, styleClass=clear box_main]htm:tr at line:71: Class: com.exadel.htmLib.tags.TrTag, attrs:htm:td at line:72: Class: com.exadel.htmLib.tags.TdTag, attrs:f:subview at line:73: Class: com.sun.faces.taglib.jsf_core.SubviewTag, attrs: [id=cars]jsp:directive.include at line:74: [file=/includes/cars.jsp]h:panelGroup at line:8: Class: com.sun.faces.taglib.html_basic.PanelGroupTag, attrs: [rendered=#{bookingHandler.flowersAvailable}]
...htm:tr at line:87: Class: com.exadel.htmLib.tags.TrTag, attrs: [style=height:5px]htm:td at line:87: Class: com.exadel.htmLib.tags.TdTag, attrs:
(我不打印“關閉標簽”,因為很明顯,當出現另一個具有相同或較小縮進的節點或輸出結束時,標簽結束。)
2.編譯器子類
重要的部分是generateJava,我剛剛復制了它,從中刪除了一些代碼,并添加了對Visitor的調用。 因此,實際上下面清單中的3行是新的(6,56,70)
public class OnlyReadingJspPseudoCompiler extends Compiler {/** We're never compiling .java to .class. */@Override protected void generateClass(String[] smap) throws FileNotFoundException,JasperException, Exception {return;}/** Copied from {@link Compiler#generateJava()} and adjusted */@Override protected String[] generateJava() throws Exception {// Setup page info areapageInfo = new PageInfo(new BeanRepository(ctxt.getClassLoader(),errDispatcher), ctxt.getJspFile());// JH: Skipped processing of jsp-property-group in web.xml for the current pageif (ctxt.isTagFile()) {try {double libraryVersion = Double.parseDouble(ctxt.getTagInfo().getTagLibrary().getRequiredVersion());if (libraryVersion < 2.0) {pageInfo.setIsELIgnored("true", null, errDispatcher, true);}if (libraryVersion < 2.1) {pageInfo.setDeferredSyntaxAllowedAsLiteral("true", null,errDispatcher, true);}} catch (NumberFormatException ex) {errDispatcher.jspError(ex);}}ctxt.checkOutputDir();try {// Parse the fileParserController parserCtl = new ParserController(ctxt, this);// Pass 1 - the directivesNode.Nodes directives =parserCtl.parseDirectives(ctxt.getJspFile());Validator.validateDirectives(this, directives);// Pass 2 - the whole translation unitpageNodes = parserCtl.parse(ctxt.getJspFile());// Validate and process attributes - don't re-validate the// directives we validated in pass 1/*** JH: The code above has been copied from Compiler#generateJava() with some* omissions and with using our own Visitor.* The code that used to follow was just deleted.* Note: The JSP's name is in ctxt.getJspFile()*/pageNodes.visit(new JsfElCheckingVisitor());} finally {}return null;}/*** The parent's implementation, in our case, checks whether the target file* exists and returns true if it doesn't. However it is expensive so* we skip it by returning true directly.* @see org.apache.jasper.JspCompilationContext#getServletJavaFileName()*/@Override public boolean isOutDated(boolean checkClass) {return true;}}
筆記:
- 我從生成Java中刪除了許多對我來說不重要的代碼; 對于與我預期不同的分析類型,某些代碼可能會有用,因此請查看原始的Compiler類并自己決定。
- 我不太在乎JSP EL,因此可以優化編譯器,使其只需要執行一次即可。
3.編譯器執行器
直接使用編譯器很困難,因為它取決于許多復雜的設置和對象。 因此,最簡單的方法是重用Ant任務JspC,這還有查找要處理的JSP的額外好處。 如前所述,關鍵是重寫getCompilerClassName以返回編譯器的類(第8行)
import org.apache.jasper.JspC;/** Extends JspC to use the compiler of our choice; Jasper version 6.0.29. */
public class JspCParsingToNodesOnly extends JspC {/** Overriden to return the class of ours (default = null => JdtCompiler) */@Override public String getCompilerClassName() {return OnlyReadingJspPseudoCompiler.class.getName();}public static void main(String[] args) {JspCParsingToNodesOnly jspc = new JspCParsingToNodesOnly();jspc.setUriroot("web"); // where to search for JSPs//jspc.setVerbose(1); // 0 = false, 1 = truejspc.setJspFiles("helloJSFpage.jsp"); // leave unset to process all; comma-separatedtry {jspc.execute();} catch (JasperException e) {throw new RuntimeException(e);}}
}
筆記:
- JspC通常會在指定的Uriroot下找到所有文件,但是您可以通過將其逗號分隔的名稱傳遞給setJspFiles來告訴它忽略所有選定的文件。
編譯依賴
以你的常春藤形式:
<dependency name="jasper" org="org.apache.tomcat" rev="6.0.29">
<dependency name="jasper-jdt" org="org.apache.tomcat" rev="6.0.29">
<dependency name="ant" org="org.apache.ant" rev="1.8.2">
執照
這里的所有代碼都直接來自Jasper,因此屬于同一許可證,即Apache許可證,版本2.0 。
結論
Jasper并非真正為擴展和模塊化而設計,因為關鍵的Node類是包私有的,并且其API非常復雜,以致僅重用其中的一部分非常困難。 幸運的是,通過提供一些“偽”對象,Ant任務JspC使它可以在servlet容器之外使用,并且有一種方法可以通過很少的工作來調整它以滿足我們的需求,盡管要弄清楚它并不是那么容易。 我不得不應用一些骯臟的技巧,即使用包私有類中的內容,并覆蓋一個不打算被覆蓋的方法( generateJava ),但是它可以工作并提供非常有價值的輸出,這使得您可以做任何想做的事情用一個JSP來做。
- Java Code Geeks Andygene Web原型
- 為什么自動化測試可以提高您的開發速度
- 代碼質量對客戶很重要。 很多。
- 使用FindBugs產生更少的錯誤代碼
- 針對用戶和新采用者的敏捷軟件開發建議
翻譯自: https://www.javacodegeeks.com/2011/06/hacking-jasper-to-get-object-model-of.html