当前位置: 首页 > 知识库问答 >
问题:

Spring 4 AbstractWebSocketMessageBrokerConfigurer,SockJS不能正确协商传输

纪俊良
2023-03-14
LOG: Opening Web Socket... 
LOG: Opening transport: iframe-htmlfile  url:rest/hello/904/ft3apk1g  RTO:1008 
LOG: Closed transport: iframe-htmlfile SimpleEvent(type=close, code=1006, reason=Unable to load an iframe (onload timeout), wasClean=false) 
LOG: Opening transport: iframe-xhr-polling  url:rest/hello/904/bf63eisu  RTO:1008 
LOG: Closed transport: iframe-xhr-polling SimpleEvent(type=close, code=1006, reason=Unable to load an iframe (onload timeout), wasClean=false) 
LOG: Whoops! Lost connection to undefined 
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        Map<String, ? extends FilterRegistration> registrations = servletContext.getFilterRegistrations();
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        // this is needed for async support for websockets/sockjs
        registration.setInitParameter("dispatchOptionsRequest", "true");
        registration.setAsyncSupported(true);
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SecurityConfig.class, Log4jConfig.class, PersistenceConfig.class, ServiceConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // loading the Initializer class from the dispatcher servlet context ensures it only executes once,
        // as the ContextRefreshedEvent fires once from the root context and once from the dispatcher servlet context   
        return new Class[]{SpringMvcConfig.class, WebSocketConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{
            "/rest/*",
            "/index.html",
            "/login.html",
            "/admin.html",
            "/index/*",
            "/login/*",
            "/admin/*"
        };
    }

    @Override
    protected Filter[] getServletFilters() {
        OpenEntityManagerInViewFilter openEntityManagerInViewFilter = new OpenEntityManagerInViewFilter();
        openEntityManagerInViewFilter.setBeanName("openEntityManagerInViewFilter");
        openEntityManagerInViewFilter.setPersistenceUnitName("HSQL");

        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceEncoding(true);

        return new javax.servlet.Filter[]{openEntityManagerInViewFilter, encodingFilter};
    }

}

Spring MVC配置:

@Configuration
@EnableWebMvc
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@ComponentScan(basePackages = "x.controllers")  // Only scan for controllers.  Other classes are scanned in the parent's root context
public class SpringMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(mappingJacksonHttpMessageConverter());
        converters.add(marshallingMessageConverter());
        super.configureMessageConverters(converters);
    }

    @Bean
    public InternalResourceViewResolver setupViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Bean
    public JacksonAnnotationIntrospector jacksonAnnotationIntrospector() {
        return new JacksonAnnotationIntrospector();
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setAnnotationIntrospector(jacksonAnnotationIntrospector());
        mapper.registerModule(new JodaModule());
        mapper.registerModule(new Hibernate4Module());
        return mapper;
    }

    @Bean
    public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        messageConverter.setObjectMapper(objectMapper());
        return messageConverter;
    }

    @Bean(name = "marshaller")
    public Jaxb2Marshaller jaxb2Marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("com.x);
        return marshaller;
    }

    @Bean
    public MarshallingHttpMessageConverter marshallingMessageConverter() {
        return new MarshallingHttpMessageConverter(
                jaxb2Marshaller(),
                jaxb2Marshaller()
        );
    }
}

Spring根上下文配置:

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.x.services"},   // scan for all annotated classes for the root context OTHER than controllers -- those are in the child web context. also don't rescan these config files
        excludeFilters = {
            @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class),
            @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Configuration.class)
        }
)
public class ServiceConfig {

    @Bean
    public DefaultAnnotationHandlerMapping defaultAnnotationHandlerMapping() {
        DefaultAnnotationHandlerMapping handlerMapping = new DefaultAnnotationHandlerMapping();
        handlerMapping.setAlwaysUseFullPath(true);
        handlerMapping.setDetectHandlersInAncestorContexts(true);
        return handlerMapping;
    }

    @Bean
    public DefaultConversionService defaultConversionService() {
        return new DefaultConversionService();
    }

    @Bean(name = "kmlContext")
    public JAXBContext kmlContext() throws JAXBException {
        return JAXBContext.newInstance("net.opengis.kml");
    }

    @Bean(name = "ogcContext")
    public JAXBContext ogcContext() throws JAXBException {
        return JAXBContext.newInstance("net.x");
    }
}

Spring安全:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        AuthenticationProvider rememberMeAuthenticationProvider = rememberMeAuthenticationProvider();
        TokenBasedRememberMeServices tokenBasedRememberMeServices = tokenBasedRememberMeServices();

        List<AuthenticationProvider> authenticationProviders = new ArrayList<AuthenticationProvider>(2);
        authenticationProviders.add(rememberMeAuthenticationProvider);
        authenticationProviders.add(customAuthenticationProvider);
        AuthenticationManager authenticationManager = authenticationManager(authenticationProviders);

        http
                .csrf().disable()
                //.headers().disable()
                .headers().addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
                .and()
                .authenticationProvider(customAuthenticationProvider)
                .addFilter(new RememberMeAuthenticationFilter(authenticationManager, tokenBasedRememberMeServices))
                .rememberMe().rememberMeServices(tokenBasedRememberMeServices)
                .and()
                .authorizeRequests()
                .antMatchers("/js/**", "/css/**", "/img/**", "/login", "/processLogin").permitAll()
                .antMatchers("/index.jsp", "/index.html", "/index").hasRole("USER")
                .antMatchers("/admin", "/admin.html", "/admin.jsp", "/js/saic/jswe/admin/**").hasRole("ADMIN")
                .and()
                .formLogin().loginProcessingUrl("/processLogin").loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll()
                .and()
                .exceptionHandling().accessDeniedPage("/login")
                .and()
                .logout().permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/img/**");
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(List<AuthenticationProvider> authenticationProviders) {
        return new ProviderManager(authenticationProviders);
    }

    @Bean
    public TokenBasedRememberMeServices tokenBasedRememberMeServices() {
        return new TokenBasedRememberMeServices("testKey", userDetailsService);
    }

    @Bean
    public AuthenticationProvider rememberMeAuthenticationProvider() {
        return new org.springframework.security.authentication.RememberMeAuthenticationProvider("testKey");
    }

    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}
@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
            SockJsServiceRegistration registration = registry.addEndpoint("/hello").withSockJS().setClientLibraryUrl("http://localhost:8084/swtc/js/sockjs-0.3.4.min.js");
            registration.setWebSocketEnabled(true);
            //registration.setSessionCookieNeeded(false);

    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.taskExecutor().corePoolSize(4).maxPoolSize(8);
    }

    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.taskExecutor().corePoolSize(4).maxPoolSize(8);
    }

}
@Controller
public class WebSocketController {
    @MessageMapping({"/hello", "/hello/**"})
    @SendTo("/topic/greetings")
    // in order to get principal, you must set cookiesNeeded in WebSocketConfig, which forces IE to use iframes, which doesn't seem to work
    public AjaxResponse<String> greeting(@Payload PointRadiusRequest prr, Principal principal) throws Exception {
        Thread.sleep(3000); // simulated delay
        AjaxResponse<String> ajaxResponse = new AjaxResponse<String>();
        ajaxResponse.setValue(principal.getName());
        ajaxResponse.setSuccess(true);
        return ajaxResponse;
    } 
}
<script>
            // test/prototype websocket code
            stompClient = null;

            window.connect = function() {

                var options = {protocols_whitelist: ["websocket", "xhr-streaming", "xdr-streaming", "xhr-polling", "xdr-polling", "iframe-htmlfile", "iframe-eventsource", "iframe-xhr-polling"], debug: true}; 
                wsSocket = new SockJS('rest/hello', undefined, options);

                stompClient = Stomp.over(wsSocket);
                stompClient.connect({}, function(frame) {
                    console.log('Connected: ' + frame);
                    stompClient.subscribe('/topic/greetings', function(message) {
                        console.info("response: ", JSON.parse(message.body));
                    });
                });
            };

            window.disconnect = function() {
                stompClient.disconnect();
                console.log("Disconnected");
            };

            window.sendName = function() {
                stompClient.send("/app/hello", {}, JSON.stringify({'latitude': 12, 'longitude': 123.2, radius: 3.14}));
            };
        </script>
>>> connect()
connecting
/swtc/ (line 109)
Opening Web Socket...
stomp.js (line 130)
undefined
GET http://localhost:8084/swtc/rest/hello/info

200 OK
        202ms   
sockjs....min.js (line 27)
Opening transport: websocket url:rest/hello/007/xkc17fkt RTO:912
sockjs....min.js (line 27)
SyntaxError: An invalid or illegal string was specified


...3,reason:"All transports failed",wasClean:!1,last_event:g})}f.readyState=y.CLOSE...

sockjs....min.js (line 27)
Closed transport: websocket SimpleEvent(type=close, code=2007, reason=Transport timeouted, wasClean=false)
sockjs....min.js (line 27)
Opening transport: xhr-streaming url:rest/hello/007/8xz79yip RTO:912
sockjs....min.js (line 27)
POST http://localhost:8084/swtc/rest/hello/007/8xz79yip/xhr_streaming

200 OK
        353ms   
sockjs....min.js (line 27)
Web Socket Opened...

>>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000

�

stomp.js (line 130)
POST http://localhost:8084/swtc/rest/hello/007/8xz79yip/xhr_send

204 No Content
        63ms    

<<< CONNECTED
user-name:first.mi.last
heart-beat:0,0
version:1.1

�

stomp.js (line 130)
connected to server undefined
stomp.js (line 130)

Connected: CONNECTED
version:1.1
heart-beat:0,0
user-name:xxx

>>> SUBSCRIBE
id:sub-0
destination:/topic/greetings

�

stomp.js (line 130)
POST http://localhost:8084/swtc/rest/hello/007/8xz79yip/xhr_send

204 No Content
        57ms
{"entropy":441118013,"origins":["*:*"],"cookie_needed":true,"websocket":true}

在IE中,这里是网络流量。Iframe.html文件似乎构建得很好,但它就是不能建立到后端的连接。

URL Method  Result  Type    Received    Taken   Initiator   Wait‎‎  Start‎‎ Request‎‎   Response‎‎  Cache read‎‎    Gap‎‎
/swtc/rest/hello/info?t=1399328502157   GET 200 application/json    411 B   328 ms      0   47  281 0   0   2199
/swtc/rest/hello/iframe.html    GET 200 text/html   0.97 KB 156 ms  frame navigate  328 0   156 0   0   2043
/swtc/js/sockjs-0.3.4.min.js    GET 304 application/javascript  157 B   < 1 ms  <script>    484 0   0   0   0   2043
/swtc/rest/hello/iframe.html    GET 304 text/html   191 B   < 1 ms  frame navigate  2527    0   0   0   0   0
/swtc/js/sockjs-0.3.4.min.js    GET 304 application/javascript  157 B   < 1 ms  <script>    2527    0   0   0   0   0

信息响应如下所示:

{"entropy":-475136625,"origins":["*:*"],"cookie_needed":true,"websocket":true}

如果有人想看到请求或响应头,只要让我知道。

    http://localhost:8084/swtc/rest/hello/info?t=1399328502157

        Key Value
        Response    HTTP/1.1 200 OK
        Server  Apache-Coyote/1.1
        X-Frame-Options SAMEORIGIN
        Access-Control-Allow-Origin http://localhost:8084
        Access-Control-Allow-Credentials    true
        Cache-Control   no-store, no-cache, must-revalidate, max-age=0
        Content-Type    application/json;charset=UTF-8
        Content-Length  78
        Date    Mon, 05 May 2014 22:21:42 GMT

LOG: Opening Web Socket... 
LOG: Opening transport: iframe-htmlfile  url:rest/hello/904/ft3apk1g  RTO:1008 
LOG: Closed transport: iframe-htmlfile SimpleEvent(type=close, code=1006, reason=Unable to load an iframe (onload timeout), wasClean=false) 
LOG: Opening transport: iframe-xhr-polling  url:rest/hello/904/bf63eisu  RTO:1008 
LOG: Closed transport: iframe-xhr-polling SimpleEvent(type=close, code=1006, reason=Unable to load an iframe (onload timeout), wasClean=false) 
LOG: Whoops! Lost connection to undefined 

顺便说一句,如果客户端库代码支持相对路径(它实际上使用相对路径构建html文件,应该可以工作,但仍然会在日志中产生错误),那就太好了,即:

SockJsServiceRegistration registration = registry.addEndpoint("/hello").withSockJS().setClientLibraryUrl("js/sockjs-0.3.4.min.js");

这将减少部署到生产中的痛苦。

更新2:

LOG: Opening Web Socket... 
LOG: Opening transport: iframe-htmlfile  url:rest/hello/924/1ztfjm7z  RTO:330 
LOG: Closed transport: iframe-htmlfile SimpleEvent(type=close, code=2007, reason=Transport timeouted, wasClean=false) 
LOG: Opening transport: iframe-xhr-polling  url:rest/hello/924/cgq8_s5j  RTO:330 
LOG: Closed transport: iframe-xhr-polling SimpleEvent(type=close, code=2007, reason=Transport timeouted, wasClean=false) 
LOG: Whoops! Lost connection to undefined 
Key Value
Request GET /swtc/rest/hello/info?t=1399404419358 HTTP/1.1
Accept  */*
Origin  http://localhost:8084
Accept-Language en-US
UA-CPU  AMD64
Accept-Encoding gzip, deflate
User-Agent  Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Host    localhost:8084
Connection  Keep-Alive
Cache-Control   no-cache
Key Value
Response    HTTP/1.1 200 OK
Server  Apache-Coyote/1.1
X-Content-Type-Options  nosniff
X-XSS-Protection    1; mode=block
Cache-Control   no-cache, no-store, max-age=0, must-revalidate
Pragma  no-cache
Expires 0
X-Frame-Options DENY
Access-Control-Allow-Origin http://localhost:8084
Access-Control-Allow-Credentials    true
Cache-Control   no-store, no-cache, must-revalidate, max-age=0
Content-Type    application/json;charset=UTF-8
Content-Length  78
Date    Tue, 06 May 2014 19:26:59 GMT
Opening transport: websocket url:rest/hello/849/fy_06t1v RTO:342
SyntaxError: An invalid or illegal string was specified
Closed transport: websocket SimpleEvent(type=close, code=2007, reason=Transport timeouted, wasClean=false)
Opening transport: xhr-streaming url:rest/hello/849/2r0raiz8 RTO:342
http://localhost:8084/swtc/rest/hello/849/2r0raiz8/xhr_streaming
Web Socket Opened...
>>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000

共有1个答案

汪鸿波
2023-03-14

由于SockJS在尝试WebSocket连接时产生了一个奇怪的字符串错误,然后返回到xhr_streaming,所以我决定加载。js文件的非简化版本,并在Firebug中调试它,看看发生了什么。事实证明,SockJS不喜欢相对URL,这很糟糕。

对于大多数REST/Ajax服务,我都将/rest/*映射到dispatcher servlet,通常每个控制器上都有一个@RequestMapping,每个控制器方法上都有另一个@RequestMapping。使用Dojo,我通过指定url“rest/ / 来进行AJAX调用。

我也试图用Sockjs做同样的事情。我只是指着“Rest/你好”。我将其更改为完全限定的URL“http://localhost:8084/swtc/rest/hello”,突然间,firefox可以很好地构建websocket传输层。我跳到IE进行了一个快速测试,果然,它构建了iframe会话,并且工作得很好。

 类似资料:
  • 问题内容: 我有一个似乎无法满足的简单要求:我有一个产品页面。产品具有供应商,供应商输入是带有自动完成功能的文本字段。如果用户输入数据库中不存在的供应商,则需要添加它。要添加它,我在.load()页面上有一个DIV并调用了我的/ Vendor / Create控制器方法。该方法的视图使用: 这应该通过ajax发布我的表单,完成后调用Javascript。我遇到的问题是,提交后,我的整个页面都会刷新

  • 我错过了什么关于正确关闭生产者和消费者的事情吗?

  • 我用的是跺脚。我的javascript客户端中的js over SockJS。我正在使用连接到websocket stomp over sockJS连接有2个http请求: 请求发送至/info http升级请求 客户端发送所有cookie。我也想发送自定义头(例如XSRF头),但没有找到方法。谢谢你的帮助。

  • Im使用插件IWD的伍兹商业,这是一个一致的错误,我收到。寻求帮助如何解决这个问题?我对代码非常陌生,并试图理解它。但这超出了我的知识水平。 [星期三Jul29 19:36:02.765466 2020][php7:通知][pid 31401][客户端101.161.102.84:53742]id被错误地调用。不应直接访问产品属性。回溯:要求('wp-blog-header.php'),requi

  • 我在Go有一个现有项目,我正在使用协议缓冲区/gRPC。直到最近,go\u package选项还是可选的,并且生成的go package名称将与proto package名称相同。 此文件位于项目根目录中。生成的代码文件(authenticator.pb.go)位于同一位置。原型文件: Generation命令指定我要在同一目录中输出: 今天,我推出了新版本的协议缓冲区编译器和github。com

  • 我一直在试图调试为什么我的DropDownChoice在一个简单的表单中只有下拉和提交按钮,但几个小时来没有正常工作。