개발

Spring Websocket info 404 에러 나는 경우

개미v 2020. 5. 11. 17:00

 

웹소켓이 처음 connection 시에 "http://localhost/컨텍스트/echo/info?t=1589183059903" 같은 형태의 URL을 호출해서 연결이 되는데 404에러 나는 경우 해결방법입니다.

 

스프링에서 호출 URL을 처리 못한다는 것이니, 맵팽 관련된 부분을 확인해야 합니다.

 

1. web.xml 에서 url-pattern

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

 

2-1. [java로 설정한 경우] WebSocketConfig.java 에서 EnabledWebSocket 어노테이션, setAloowedOrigins, withSockJS 옵션 확인

package com.chat.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import com.chat.controller.EchoHandler;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
	
	@Autowired
	private EchoHandler echoHandler;
	
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(echoHandler, "/echo").setAllowedOrigins("*").withSockJS();
    }
}

 

2-2. [xml로 설정한 경우] websocket-config.xml 에서 allowed-origins, websocket-enabled 옵션 확인

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd">

	<websocket:handlers allowed-origins="*" >
        <websocket:mapping handler="echoHandler" path="/echo" />
        <websocket:sockjs websocket-enabled="true" />
    </websocket:handlers>
    
    <bean id="echoHandler" class="com.chat.controller.EchoHandler" />
    
</beans>