private void createServlet(Class<?> servletClass, ApplicationContext applicationContext, Map<String, String> initParameters) { if (servletCache.containsKey(applicationContext)) { servlet = servletCache.get(applicationContext); return; } MockServletConfig config = new MockServletConfig(); config.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, new ApplicationContextWrapper(applicationContext, config.getServletContext())); if (initParameters!=null) { for (Map.Entry<String, String> param: initParameters.entrySet()) { config.addInitParameter(param.getKey(), param.getValue()); } } try { servlet = (HttpServlet) BeanUtils.instantiate(servletClass); servlet.init(config); servletCache.put(applicationContext, servlet); } catch (Exception e) { throw new IllegalArgumentException("Error when creating servlet "+servletClass.getName(),e); } }
private HttpJspBase loadJsp(String forwardedUrl, File compilationDir) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, ServletException { String jspClassName = toJspClassName(forwardedUrl); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { compilationDir.toURI().toURL() }); Class<?> cls = Class.forName(jspClassName, true, classLoader); HttpJspBase instance = (HttpJspBase) cls.newInstance(); MockServletConfig servletConfig = new MockServletConfig(new MockServletContext()); servletConfig.getServletContext().setAttribute(InstanceManager.class.getName(), new InstanceManagerImplementation()); JspApplicationContext jspApplicationContext = JspFactory.getDefaultFactory().getJspApplicationContext( servletConfig.getServletContext()); // Register the ELResolver with JSP jspApplicationContext.addELResolver(manager.getELResolver()); // Register ELContextListener with JSP jspApplicationContext.addELContextListener(Reflections .<ELContextListener> newInstance("org.jboss.weld.el.WeldELContextListener")); // Push the wrapped expression factory into the servlet context so that // Tomcat or Jetty can hook it in using a container code servletConfig.getServletContext().setAttribute(EXPRESSION_FACTORY_NAME, manager.wrapExpressionFactory(jspApplicationContext.getExpressionFactory())); instance.init(servletConfig); JspFactory.setDefaultFactory(new org.apache.jasper.runtime.JspFactoryImpl()); instance._jspInit(); return instance; }