Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect HttpServlet with Spring Application Context in web.xml?

Tags:

spring

I'm trying to connect my FooServlet which extends HttpServlet with the ApplicationContext which is in the same Project. The Application Context is already used by a Wicket Servlet

It works with

servletContext = this.getServletContext();
wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
(IMyBean)wac().getBean("myServiceBean")

Now I try to aviod to use explicitly Spring Classes in my Code (WebApplicationContextUtils) as it's not the IoC way.

The Wicket Servlet is connected with the Application context in the web.xml

<servlet>
  <servlet-name>ExampleApplication</servlet-name>
  <servlet-class>org.apache.wicket.protocol.http.WicketServlet</servlet-class>
    <init-param>
      <param-name>applicationFactoryClassName</param-name>
      <param-value>org.apache.wicket.spring.SpringWebApplicationFactory</param-value>
    </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

I found the class Spring HttpServletBean but I don't know if it serves for my Case

like image 416
Martin Dürrmeier Avatar asked Dec 08 '09 13:12

Martin Dürrmeier


1 Answers

I found a way to inject Beans in my HttpServlet (Note: I don't need a Presentation View, otherwise there are more advanced Spring Classes)

Add a ContextLoaderListener to web.xml so that Spring's root WebApplicationContext is loaded

   <listener>
      <listener-class>
        org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>

Configure Servlet using Springs HttpRequestHandlerServlet Class

<servlet>
 <servlet-name>FooServlet</servlet-name>
 <display-name>Foo Servlet</display-name>
 <servlet-class>
      org.springframework.web.context.support.HttpRequestHandlerServlet
    </servlet-class>
</servlet>

Let your Servlet implement the org.springframework.web.HttpRequestHandler Interface

Define your Servlet as a Bean in ApplicationContext (beanID must be same as "servlet-name"). Now it's possible to inject all necassary Beans in the Spring DependencyInjection way without dependency lookup.

like image 70
Martin Dürrmeier Avatar answered Nov 07 '22 10:11

Martin Dürrmeier