Spring Websocket,404连接时出错.应用程序未使用Spring MVC



我正在努力学习Spring示例教程:https://spring.io/guides/gs/messaging-stomp-websocket/

但我需要它在现有的应用程序上工作,我需要添加WebSocket支持。我的想法是,一旦我完成了基本的工作,就从那里开始建设。

我与URL中的示例的不同之处在于:

  1. 我没有使用SpringBootApplication,而是使用Tomcat(7.0.69)
  2. 这意味着我确实有一个web.xml(包含在下面)
  3. 我用main跳过了Application.java。。。我正在构建一个WAR,并将其手动部署到Tomcat中

当我启动Tomcat时,我阅读了以下似乎相关的内容:

03:06:52,908  INFO SimpleBrokerMessageHandler:157 - Starting...
03:06:52,908  INFO SimpleBrokerMessageHandler:260 - BrokerAvailabilityEvent[available=true, SimpleBrokerMessageHandler [DefaultSubscriptionRegistry[cache[0 destination(s)], registry[0 sessions]]]]
03:06:52,913  INFO SimpleBrokerMessageHandler:166 - Started.

问题如下:当我点击index.html上的connect时,当我试图在映射url"/hello"处访问服务器时,我得到了404(不确定为什么会有信息,我想这是协议的一部分。)http://localhost:8080/hello/info

我在谷歌上搜索了这个,甚至在stackoverflow中找到了一些答案。有些人已经修复了将DispatcherServlet映射到websocket url的前缀添加。。。

然而,我的应用程序没有使用SpringMVC,所以我没有配置DispatcherServlet。。。我只为WebSockets包含它看起来有些过头了。

我尝试将注释@EnableWebMvc添加到WebSocketConfig类中(链接中是代码,我有相同的行)

任何建议都将不胜感激!

WEB.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>App</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

我放弃了为不使用Spring MVC的应用程序使用MVC Dispatcher的尝试。

这解决了问题:

web.xml

    <servlet>
    <!-- Only used by websockets -->
    <servlet-name>SpringMVCDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/websockets-application-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>SpringMVCDispatcherServlet</servlet-name>
    <url-pattern>/ws/*</url-pattern>
</servlet-mapping>

然后,在index.html中,我只在连接时添加了前缀/ws/(只有在那里,发送没有前缀的消息是可以的)。

最新更新