【发布时间】: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