1 package freemarker.ext.jsp; 2 3 import java.lang.reflect.InvocationTargetException ; 4 import java.lang.reflect.Method ; 5 6 import javax.servlet.jsp.PageContext ; 7 8 import freemarker.core.Environment; 9 import freemarker.template.TemplateModel; 10 import freemarker.template.TemplateModelException; 11 import freemarker.template.utility.UndeclaredThrowableException; 12 13 17 class PageContextFactory { 18 19 private static final Method constructor; 20 21 static { 22 Class impl; 23 try { 24 try { 25 PageContext .class.getMethod("getExpressionEvaluator", null); 26 impl = Class.forName("freemarker.ext.jsp.FreeMarkerPageContext2"); 27 } 28 catch(NoSuchMethodException e) { 29 impl = Class.forName("freemarker.ext.jsp.FreeMarkerPageContext1"); 30 } 31 constructor = impl.getDeclaredMethod("create", null); 32 } 33 catch(ClassNotFoundException e) { 34 throw new NoClassDefFoundError (e.getMessage()); 35 } 36 catch(NoSuchMethodException e) { 37 throw new NoSuchMethodError (e.getMessage()); 38 } 39 } 40 41 static FreeMarkerPageContext getCurrentPageContext() throws TemplateModelException { 42 Environment env = Environment.getCurrentEnvironment(); 43 TemplateModel pageContextModel = env.getGlobalVariable(PageContext.PAGECONTEXT); 44 if(pageContextModel instanceof FreeMarkerPageContext) { 45 return (FreeMarkerPageContext)pageContextModel; 46 } 47 try { 48 FreeMarkerPageContext pageContext = 49 (FreeMarkerPageContext)constructor.invoke(null, null); 50 env.setGlobalVariable(PageContext.PAGECONTEXT, pageContext); 51 return pageContext; 52 } 53 catch(IllegalAccessException e) { 54 throw new IllegalAccessError (e.getMessage()); 55 } 56 catch(InvocationTargetException e) { 57 if(e.getTargetException() instanceof TemplateModelException) { 58 throw (TemplateModelException)e.getTargetException(); 59 } 60 throw new UndeclaredThrowableException(e); 61 } 62 } 63 64 } 65 | Popular Tags |