首页>代码>spring mvc+thymeleaf+Knockout.js整合开发最简单的聊天室实例>/spring-mvc-chat/src/main/java/org/springframework/samples/async/chat/ChatController.java
package org.springframework.samples.async.chat; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.async.DeferredResult; @Controller @RequestMapping("/mvc/chat") public class ChatController { private final ChatRepository chatRepository; private final Map<DeferredResult<List<String>>, Integer> chatRequests = new ConcurrentHashMap<DeferredResult<List<String>>, Integer>(); @Autowired public ChatController(ChatRepository chatRepository) { this.chatRepository = chatRepository; } @RequestMapping(method=RequestMethod.GET) @ResponseBody public DeferredResult<List<String>> getMessages(@RequestParam int messageIndex) { final DeferredResult<List<String>> deferredResult = new DeferredResult<List<String>>(null, Collections.emptyList()); this.chatRequests.put(deferredResult, messageIndex); deferredResult.onCompletion(new Runnable() { @Override public void run() { chatRequests.remove(deferredResult); } }); List<String> messages = this.chatRepository.getMessages(messageIndex); if (!messages.isEmpty()) { deferredResult.setResult(messages); } return deferredResult; } @RequestMapping(method=RequestMethod.POST) @ResponseBody public void postMessage(@RequestParam String message) { this.chatRepository.addMessage(message); // Update all chat requests as part of the POST request // See Redis branch for a more sophisticated, non-blocking approach for (Entry<DeferredResult<List<String>>, Integer> entry : this.chatRequests.entrySet()) { List<String> messages = this.chatRepository.getMessages(entry.getValue()); entry.getKey().setResult(messages); } } }


13133117021 LV5
2024年12月24日
ma406805131 LV19
2024年12月18日
dapeng0011 LV15
2024年7月16日
夜起星河 LV8
2023年12月27日
buhuia LV4
2023年6月7日
ChenZheMeng LV3
2022年12月21日
win1991 LV6
2022年8月18日
123456qiqiqi LV1
2022年5月27日
fengshengtian LV8
2022年4月19日
yuxinnan LV4
2022年4月11日