JSR-356: How to abort a websocket connection during the handshake?

前端 未结 4 443
误落风尘
误落风尘 2021-01-11 15:49

I need to be able to abort a websocket connection during the handshake in case the HTTP request does not meet certain criteria. From what I understand, the proper place to d

4条回答
  •  攒了一身酷
    2021-01-11 16:16

    The easiest way is to setup simple web-filter in your web.xml which will be executed before handshake.

    Smth like:

    public class MyHandshakeFilter implements Filter {
    
    @Override
    public void init(FilterConfig config) throws ServletException {
        // do nothing
    }
    
    /**
     * Passes request to chain when request port is equal to specified in the allowedPort property
     * and returns HttpServletResponse.SC_NOT_FOUND in other case.
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
    
        if () {
            // request conditions are met. continue handshake...
            chain.doFilter(request, response);
        } else {
            // request conditions are NOT met. reject handshake...
            ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
    }
    }
    

    and in web.xml:

    
        yourHandshakeFilter
        com....MyHandshakeFilter
    
    
        yourHandshakeFilter
        /yourEndpointUrl
    
    

    and your ServerEndpoint should be smth like:

    @ServerEndpoint("/yourEndpointUrl")
    public class MyServerEndpoint {
    ...
    }
    

提交回复
热议问题