【问题标题】:How to get dispatcher servlet name in Spring controller如何在 Spring 控制器中获取调度程序 servlet 名称
【发布时间】:2016-12-02 10:45:22
【问题描述】:

下面是我的 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 名称“DispatcherName”?

我希望它从 XMLWebApplicationContext 访问控制器对象,为此我需要 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 名称而异。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • @KurtVandenBranden 添加了问题
  • 不要...你应该首先使用依赖注入,其次WebApplicationContextUtils只会给你根上下文,而不是来自DispatcherServlet的上下文。
  • @M.Deinum 你能否帮助如何获取 XMLWebApplicationContext 对象?或如何获取 Dispatcher Servlet 名称
  • 为什么需要ApplicationContext?一般来说,当你做这样的事情时,你做事的方式是错误的。

标签: java spring spring-mvc servlets requestdispatcher


【解决方案1】:

在你的控制器中,你可以试试:

request.getServletContext().getServletContextName()

或者

RequestContextUtils.getWebApplicationContext(request).getDisplayName()

【讨论】:

  • 我没有请求对象 & getServletContextName 没有返回我的调度程序 servlet 名称
  • 你能添加你的控制器方法吗??
  • 我已经更新了我的答案。
猜你喜欢
  • 2018-01-30
  • 1970-01-01
  • 2014-10-13
  • 1970-01-01
  • 2023-03-14
  • 2017-12-10
  • 2012-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多