0
我是Spring框架的新手,並嘗試創建一個API供其他人使用。HTTP POST的通知
這是在我的控制器類
POST方法
// -------------------Create a Report-------------------------------------------
@RequestMapping(value = "/report/", method = RequestMethod.POST)
public ResponseEntity<?> createReport(@RequestBody Report report, UriComponentsBuilder ucBuilder) {
logger.info("Creating Report : {}", report);
if (reportRepository.isReportExist(report)) {
logger.error("Unable to create. A report with name {} already exist", report.getCrisisID());
return new ResponseEntity(new CustomErrorType("Unable to create. A Report with crisisID " +
report.getCrisisID() + " already exist."),HttpStatus.CONFLICT);
}
reportRepository.saveReport(report);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/api/report/{crisisID}").buildAndExpand(report.getCrisisID()).toUri());
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}
GET方法
// -------------------Retrieve All Reports---------------------------------------------
@RequestMapping(value = "/report/", method = RequestMethod.GET)
public ResponseEntity<List<Report>> listAllReports() {
List<Report> reports = reportRepository.findAllReports();
if (reports.isEmpty()) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<Report>>(reports, HttpStatus.OK);
}
下面是一個示例代碼爲他人創建報表對象,併發送給我的API。
// POST
private static void createReport() {
System.out.println("Testing create Report API----------");
RestTemplate restTemplate = new RestTemplate();
Report report = new Report(20, "General", 4, "AA1",10000,"crisis details", "1 hour", "COA1", "COA1");
URI uri = restTemplate.postForLocation(REST_SERVICE_URI + "/report/", report,
Report.class);System.out.println("Location : "+uri.toASCIIString());
}
我想知道如果下面是可能的,或者是否有任何方式來處理這種情況:
- 當有人創建了一個報告,並通過POST URL發送給我,我的POST方法能夠自動檢測到創建了新的報告條目,然後在我的HTML/JSP頁面(例如彈出窗口)中發送通知。
更新
RestApiController.java
@RestController
@RequestMapping("/api")
public class RestApiController {
public static final Logger logger = LoggerFactory.getLogger(RestApiController.class);
@Autowired
ReportRepository reportRepository; //Service which will do all data retrieval/manipulation work
// -------------------Create a Report-------------------------------------------
@RequestMapping(value = "/report/", method = RequestMethod.POST)
@SendTo("/channel/publicreport")
public ResponseEntity<?> createReport(@RequestBody Report report, UriComponentsBuilder ucBuilder) {
logger.info("Creating Report : {}", report);
if (reportRepository.isReportExist(report)) {
logger.error("Unable to create. A report with name {} already exist", report.getCrisisID());
return new ResponseEntity(new CustomErrorType("Unable to create. A Report with crisisID " +
report.getCrisisID() + " already exist."),HttpStatus.CONFLICT);
}
reportRepository.saveReport(report);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/api/report/{crisisID}").buildAndExpand(report.getCrisisID()).toUri());
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}
}
WebSocketConfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chatservice");
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/channel");
}
}
main.js
'use strict';
var stompClient = null;
var username = null;
function connectReport(event) {
username = "myname";
if(username) {
//var socket = new SockJS('/ws');
//stompClient = Stomp.over(socket);
stompClient = Stomp.client('ws://localhost:8080/chatservice');
stompClient.connect({}, onConnectedReport, onError);
}
event.preventDefault();
}
function onConnectedReport() {
// Subscribe to the Public Channel
stompClient.subscribe('/channel/publicreport',onReportMessageReceived);
}
function onError(error) {
connectingElement.textContent = 'Could not connect to WebSocket server. Please refresh this page to try again!';
connectingElement.style.color = 'red';
}
function onReportMessageReceived(payload) {
//Code for pop up window
}
window.addEventListener("load", connectReport, true)
首先你需要選擇一種方法。每種都有優點/缺點:選項1。 HTML保持彙集結果。選項2。使用websockets。 – Rafa
如果使用websocket,通知將是實時的,但持續池化儀式並非如此? –
正確。另外,pooling實現起來更簡單,但可能會增加服務器端的額外負載 – Rafa