如何在Spring控制器中获取调度程序servlet名称

时间:2016-12-02 10:45:22

标签: java spring spring-mvc servlets requestdispatcher

下面是我的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>

有没有办法在我的应用程序控制器中获取servlet-name“DispatcherName”?

我想让它从XMLWebApplicationContext&amp ;;中访问控制器对象。要做到这一点,我需要RequestDispatcher名称。 直到现在这是我尝试过的:

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

并尝试了这个

@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;
}    
}

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

由于我无法获取servlet名称,因此我使用的是getApplicationName(),但这可能因servlet名称而异。

1 个答案:

答案 0 :(得分:1)

在您的控制器中,您可以尝试:

request.getServletContext().getServletContextName()

RequestContextUtils.getWebApplicationContext(request).getDisplayName()
相关问题