【问题标题】:How to stop the spring MVC controller execution if client close the browser tab?如果客户端关闭浏览器选项卡,如何停止 Spring MVC 控制器的执行?
【发布时间】:2020-09-20 01:45:57
【问题描述】:

我正在开发一个 web 应用程序,它使用 spring websocket 连接向特定用户发送多条消息。 我有一个 spring mvc 控制器,当从客户端接收到 STOMP 时,它开始向用户发送消息。是这样的:

@Controller
public class Controller{
     @Autowired
     private SimpMessagingTemplate template;

     @MessageMapping("/")
     @SendToUser("/queue/user")
     public void myMethod(ClientMessage msg, Principal principal){
          Object myObject = new Object();
          //stuff
          while(true){
               //more stuff
               this.template.convertAndSendToUser(principal.getName(), "/queue/user", myObject);
          }
     }
}

现在我的问题是:有办法知道客户端何时关闭(或重新加载)浏览器选项卡? 当客户端关闭选项卡以终止控制器执行时,我想退出 while 循环。 我想通过检查一些东西来停止while循环,比如:while(!session.isClose()) 谁能帮我解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    如果有人需要,我会发布我的解决方案。

    我真的不知道我做事是否正确,但我将 SessionDisconnectEvent 侦听器从特定类移到了我的控制器。因此,现在控制器实现了 ApplicationListener 并覆盖了 onApplicationEvent。当用户关闭选项卡时,布尔值设置为 true,控制器停止执行。 现在我有这样的东西:

    @Controller
    public class Controller implements ApplicationListener<SessionDisconnectEvent>{
    
         @Autowired
         private SimpMessagingTemplate template;
    
         private boolean disconnected;
    
         @MessageMapping("/")
         @SendToUser("/queue/user")
         public void myMethod(ClientMessage msg, Principal principal){
              Object myObject = new Object();
              //stuff
              while(!disconnected){
                   //more stuff
                   this.template.convertAndSendToUser(principal.getName(), "/queue/user", myObject);
              }
         }
    
         @EventListener
         @Override
         public void onApplicationEvent(SessionDisconnectEvent  applicationEvent) {
              System.out.println("SESSION " + applicationEvent.getSessionId() + " DISCONNECTED");
              this.graphService.setDisconnect(true);
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      • 2015-09-20
      • 2013-12-24
      • 2020-07-17
      • 2016-07-11
      • 2013-07-19
      • 1970-01-01
      相关资源
      最近更新 更多