【问题标题】:No WebApplicationContext found: not in a DispatcherServlet request未找到 WebApplicationContext:不在 DispatcherServlet 请求中
【发布时间】:2014-12-23 07:14:29
【问题描述】:

我有一个 Spring 应用程序。由于某些原因,我有一个标准的 servlet,我需要该 servlet 才能访问一些 spring bean(我知道这并不理想,我会在未来寻找更好的东西)。

在 Web.xml 中

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<servlet>
    <description>Tunnel servlet.</description>
    <servlet-name>Tunnel</servlet-name>
    <servlet-class>
        com.something.GuacamoleController
    </servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Tunnel</servlet-name>
    <url-pattern>/path</url-pattern>
</servlet-mapping>

和 GuacamoleController

public class GuacamoleController extends GuacamoleHTTPTunnelServlet {

    @Override
    protected GuacamoleTunnel doConnect(HttpServletRequest request)
            throws GuacamoleException {

        WebApplicationContext webApplicationContext = RequestContextUtils.getWebApplicationContext(request);

        [...]
    }
}

但它抛出了这个错误:

java.lang.IllegalStateException: No WebApplicationContext found: not in a DispatcherServlet request?

如何使这种情况成为 DispatcherServlet 请求?

我需要 Web 应用程序上下文,以便我可以使用 getBean 方法手动访问服务实例

【问题讨论】:

  • 如果您使用 Spring MVC,为什么要创建自己的 servlet?
  • 情况需要如此。最好的办法是将此 servlet (guac-dev.org/doc/gug/…) 转换为 Spring Controller。也能解决问题。
  • 情况需要如此。嗯,这正是你的问题,这就是你应该问的问题。
  • AL已经做了,我等了三天没有回复。我必须解决这个问题才能进行一些测试。能不能把注意力集中在问题上?

标签: java spring spring-mvc servlets


【解决方案1】:

您不在DispatcherServlet 的上下文中,而是在您自己的Servlet 实现中滚动。

可能处于ContextLoaderListener 的上下文中。使用

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());

获取由ContextLoaderListener 加载的WebApplicationContext。如果不存在,该方法会抛出异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-31
    • 2017-02-12
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2016-01-07
    • 2017-09-17
    • 2016-06-11
    相关资源
    最近更新 更多