2017-10-16 61 views
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) 
+0

首先你需要選擇一種方法。每種都有優點/缺點:選項1。 HTML保持彙集結果。選項2。使用websockets。 – Rafa

+0

如果使用websocket,通知將是實時的,但持續池化儀式並非如此? –

+0

正確。另外,pooling實現起來更簡單,但可能會增加服務器端的額外負載 – Rafa

回答

0

一般來說,這樣的授權委託給客戶。即客戶端輪詢服務器所感興趣的更改,一旦檢測到客戶端做出相應反應。最古老的方式(現在已經過時)是在HTML中添加一個標籤,強制整個頁面刷新一定的頻率,這意味着頁面向服務器發送請求並接收更新的頁面以顯示。在我們的日子裏,有各種各樣的框架對頁面進行部分更新。第一個是Ajax,然後是DHTML等等。我不是客戶端程序員。但是就概念而言,這樣的任務通常會給客戶端