向现有Spring应用程序添加Web套接字支持

时间:2016-07-27 11:10:18

标签: java spring spring-mvc jetty spring-websocket

我正在使用Spring 4应用程序(不幸的是Spring Boot)并且我无法让网络套接字工作。我在TextWebSocketHandler路径注册了一个简单的/ws实现,我获取确认日志:

  

将映射的URL路径[/ ws]映射到类型的处理程序   [类   org.springframework.web.socket.server.support.WebSocketHttpRequestHandler]

...但我无法连接网络浏览器中的地址。我已经尝试过这种基于注释的配置:

@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {
    public static final String WEB_SOCKET_PATH = "/ws";
    @Autowired
    private WebSocketService handler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        log.info("Registering web socket handler {} at '{}'.", handler, WEB_SOCKET_PATH);
        registry.addHandler(handler, WEB_SOCKET_PATH);
    }
}

我可以确认WebSocketService handler不为空,实际上实现了WebSocketHandler接口。虽然配置器明显被触发,但与"ws://localhost:8081/ws"连接会导致错误:

  

WebSocket连接到' ws:// localhost:8081 / ws'失败:错误期间   WebSocket握手:意外的响应代码:404

     

error {target:WebSocket,isTrusted:true,currentTarget:WebSocket,   eventPhase:2,bubbles:false,cancelable:false,defaultPrevented:   false,timeStamp:1469616712980247,originalTarget:WebSocket,   explicitOriginalTarget:WebSocket,NONE:0}

我用来测试Web套接字机制的客户端代码非常简单:

var ws = new WebSocket("ws://localhost:8081/ws");
ws.onerror = function(e) { console.log(e); }
ws.onopen = function() { console.log("Opened"); }

我甚至尝试通过XML配置注册处理程序,但是虽然我得到了几乎相同的日志,但它仍然不起作用。请注意,我使用Jetty 9的默认配置运行应用程序(通过Gretty Gradle插件)。

在浏览Spring调试日志时,我只能猜测Spring无法将HTTP请求提升为Web套接字连接:

13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 1 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@4190548c: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4190548c: Principal: org.springframework.security.core.userdetails.User@58c7c40: Username: [removed]; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@12afc: RemoteIpAddress: 127.0.0.1; SessionId: 1om9yxo93cwce1qb1tu0rcs15n; Granted Authorities: ROLE_USER'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 2 of 13 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 3 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 4 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - Checking match of request : '/ws'; against '/logout'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - Request 'GET /ws' doesn't match 'POST /securityCheck
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 7 of 13 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4190548c: Principal: org.springframework.security.core.userdetails.User@58c7c40: Username: [removed]; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@12afc: RemoteIpAddress: 127.0.0.1; SessionId: 1om9yxo93cwce1qb1tu0rcs15n; Granted Authorities: ROLE_USER'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
13:14:02.322 [qtp1305935114-14] DEBUG - /ws at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
13:14:02.322 [qtp1305935114-14] DEBUG - Checking match of request : '/ws'; against '/login*'
13:14:02.322 [qtp1305935114-14] DEBUG - Secure object: FilterInvocation: URL: /ws; Attributes: [ROLE_USER]
13:14:02.322 [qtp1305935114-14] DEBUG - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4190548c: Principal: org.springframework.security.core.userdetails.User@58c7c40: Username: [removed]; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@12afc: RemoteIpAddress: 127.0.0.1; SessionId: 1om9yxo93cwce1qb1tu0rcs15n; Granted Authorities: ROLE_USER
13:14:02.322 [qtp1305935114-14] DEBUG - Voter: org.springframework.security.access.vote.RoleVoter@b5de58f, returned: 1
13:14:02.322 [qtp1305935114-14] DEBUG - Authorization successful
13:14:02.322 [qtp1305935114-14] DEBUG - RunAsManager did not change Authentication object
13:14:02.322 [qtp1305935114-14] DEBUG - /ws reached end of additional filter chain; proceeding with original chain
13:14:02.323 [qtp1305935114-14] DEBUG - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@425f619f
13:14:02.324 [qtp1305935114-14] DEBUG - Chain processed normally
13:14:02.324 [qtp1305935114-14] DEBUG - SecurityContextHolder now cleared, as request processing completed

查看了官方文档和示例后,似乎Web套接字配置非常标准。有什么我可能错过的或者我可能需要更改的任何配置才能在Spring中启用Web套接字吗?

2 个答案:

答案 0 :(得分:1)

结果是Web套接字按预期工作,但是/*中的web.xml未设置Spring servlet映射:

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/spring/*</url-pattern>
</servlet-mapping>

愚蠢,真的 - 我所要做的就是将地址改为ws://localhost:8081/spring/ws。让我措手不及的是,一些Spring过滤器被映射到/*,我觉得Spring servlet共享了这个映射 - 毕竟,对ws://localhost:8081/ws的调用触发了一些Spring的东西(见过)在日志中。)

我们都喜欢有多个框架的遗留应用程序,对吗?

答案 1 :(得分:0)

我认为您应该将@Controller注释添加到WebSocketConfigurer类中,如果不是所有的http请求都将由Spring的DispatcherServlet处理。相关:Spring websocket getting 404 not found