Embedded Jetty in Spring MVC, IoC/DI
The goal is to be able to use or reference beans configured/located on already been loaded spring application context. Read and understand my resolution below.
LOG.info("Application starting");
_applicationContext = new ClassPathXmlApplicationContext(_resourceLocations);
_webServer = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setHost("localhost");
connector.setPort(8080);
_webServer.addConnector(connector);
WebAppContext webAppContext = new WebAppContext(_webServer, "path to web app folder", "/");
GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext();
webApplicationContext.setServletContext(webAppContext.getServletContext());
webApplicationContext.setParent(_applicationContext);
webAppContext.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
webApplicationContext.refresh();
ServletHandler servletHandler = new ServletHandler();
ServletHolder servletHolder = new ServletHolder(new DispatcherServlet());
servletHolder.setName("dispatcher");
servletHandler.addServlet(servletHolder);
ServletMapping servletMapping = new ServletMapping();
servletMapping.setServletName(servletHolder.getName());
servletMapping.setPathSpec("*.htm");
servletHandler.addServletMapping(servletMapping);
webAppContext.setServletHandler(servletHandler);
_webServer.addHandler(webAppContext);
RequestLogHandler logHandler = new RequestLogHandler();
NCSARequestLog ncsaLog = new NCSARequestLog();
ncsaLog.setExtended(true);
ncsaLog.setFilename("logs/jetty-yyyy_mm_dd.log");
logHandler.setRequestLog(ncsaLog);
_webServer.addHandler(logHandler);
LOG.info("Starting main application context");
_applicationContext.start();
LOG.info("Starting Jetty Server");
try {
_webServer.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LOG.info("Application started");
return null;
Anonymous
November 21, 2011 at 7:14 AM
Thank you very much for this example.
I'm also trying to build a Spring MVC standalone application with embedded jetty. But I basically fail at the point, that the request somehow are not passed to the Spring Framework.
Jetty runs fine, and I also see that the Controllers from Spring are loaded and mapped.
I probabbly miss some configuration in the context file.
Could you give me some more informations (maybe sources) how your project structure looks and whats in your context files?
Have you also tried this with jetty 7 and Spring 3 ?
Thank you in advance,
Alig