0
votes

I'm using Embedded Jetty and Spring MVC and i'm starting my WebApplication through the main function. i don't like the way it's looks, it's not very clean and i have the feeling i'm doing something wrong even though it's working just fine. my problem is that i want to initialize ServerHolder,ServletContextHandler and Server objects outside the main method, but i cannot do it because DispatcherServlet requires and ApplicationContext.

Any ideas?

public static void main(String[] args) throws Exception {

    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(EPConfiguration.class);

    ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext));

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");

    BasicConfigurator.configure();

    Server server = new Server();
    server.setHandler(context);
    //HTTP
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(9999);

    server.setConnectors(new Connector[]{connector});
    server.start();
    server.join();
}
1

1 Answers

0
votes

I'm not familier with Jetty, but you can setup and initialize DispatcherServlet in the following way:

  1. Declare a java class which implements the abstract class AbstractAnnotationConfigDispatcherServletInitializer (it usually will be called WebAppInitializer).
  2. Implement its abstract methods - getRootConfigClasses() (which return the classes which configure Application Context), getServletConfigClasses() (which returns the classes which configure the ServletContext) and getServletMappings() (which sets the DispatcherServletmapping).
  3. I usually call the class that configures the ServletContext as WebConfig. You should annotate it with the @Configuration and @EnableWebMvc. In addition you should use it to define a ViewResolver bean:

```java

@Bean
public ViewResolver viewResolver() {
   InternalResourceViewResolver resolver = new InternalResourceViewResolver();
   resolver.setPrefix("/WEB-INF/view"):
   resolver.setSuffix(".jsp");
   resolver.setExposeContextBeansAsAttributes(true);
   return resolver;
}

```