Yadvendra Rathore
Yadvendra Rathore

Reputation: 13

How to get dispatcher servlet name in Spring controller

Below is my web.xml

<servlet>
    <servlet-name>DispatcherName</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/webmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Is there any way that I can get the servlet-name "DispatcherName" in my application controller?

I want this to access the controller objects from the XMLWebApplicationContext & to do that I need the RequestDispatcher Name. Till now this is what I've tried:

webApplicationContext=WebApplicationContextUtils.getWebApplicationContext(GetServletContextWebListner.getServletContext());     
XmlWebApplicationContext xmlWebApplicationContext = (XmlWebApplicationContext)GetServletContextWebListner.getServletContext().getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT."+webApplicationContext.getApplicationName().replace("/", ""));

and tried this too

@WebListener
public class GetServletContextWebListner implements ServletContextListener {
private static ServletContext servletContext;

public static ServletContext getServletContext() {
    return servletContext;
}

@Override
public void contextInitialized(ServletContextEvent sce) {
    servletContext = sce.getServletContext();
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
    servletContext = null;
}    
}

and

   (XmlWebApplicationContext)GetServletContextWebListner.getServletContext().getServletContextName()

Since I'm not able to get the servlet name, I'm using the getApplicationName() but this may vary with the servlet name.

Upvotes: 0

Views: 2385

Answers (1)

Mohamed Nabli
Mohamed Nabli

Reputation: 1649

in you controller, you may try :

request.getServletContext().getServletContextName()

Or

RequestContextUtils.getWebApplicationContext(request).getDisplayName()

Upvotes: 1

Related Questions