簡體   English   中英

更改頁面 spring 引導應用程序

[英]Changing pages spring boot application

我在更改頁面時遇到問題。 所以我有一個按鈕,當用戶按下該按鈕時,會調用 ajax Post。 這里的例子:

 $.ajax({
        contentType: "application/json",
        type: "POST",
        data: JSON.stringify(project),
        url: "/saveProject",
        success: function (data) {
            console.log('done');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('error while post');
        }
    });

@RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public @ResponseBody
String saveProject(@RequestBody Project newProject, Authentication authentication) {
    projectService.saveProjectNew(newProject, authentication);

    return "mywork.html";

}

所以最后我想從我當前所在的頁面重定向到 mywork.html 。 但是什么也沒發生,我留在同一頁面上。 我可能錯過了一些我不知道的東西。 對此很陌生。

To redirect the page into the mywork.html You need to write the code once you get the response from the Ajax call So under the success function of Ajax you should use

windows.location.href = "Your context path"+"/mywork.html";

請參考以下參考代碼:

$.ajax({
    contentType: "application/json",
    type: "POST",
    data: JSON.stringify(project),
    url: "/saveProject",
    success: function (data) {
        windows.location.href = "Your context path"+"/mywork.html";

    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('error while post');
    }
});

這里的 spring web 客戶端代碼不會將調用轉移到 mywork.html。

所有呼叫將僅通過 Ajax 呼叫轉移。

return "mywork.html";

此代碼僅用於 model 您在調用端點后檢索到的響應。

Http 重定向可以從后端以及您發布的前端 ajax 代碼觸發。

為了從 ui 進行重定向,您可以添加 window 重定向,就像@Anurag 在他對 ajax 成功回調的回答中指出的那樣。

但是在您的示例中,您試圖將用戶從后端端點本身重定向到新頁面。 因此,如果您已經有一個 controller 返回映射/mywork.html的視圖,以便重定向從 spring 后端工作,您需要執行以下操作:

@RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public String saveProject(@RequestBody Project newProject, Authentication authentication) {
    projectService.saveProjectNew(newProject, authentication);
    return "redirect:/mywork.html";

}

或使用ResponseEntity像:

HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(newUrl));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);

在您的代碼中,您將注釋@ResponseBody用於 controller 方法,該方法基本上使端點成為 rest 端點,默認情況下返回 json。 因此,要使重定向工作,請刪除注釋並使其成為正常的 controller 方法返回視圖。

不過,如果您想從 rest 端點重定向,請使用HttpServletResponse ,例如:

@RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public @ResponseBody String saveProject(@RequestBody Project newProject, Authentication authentication, HttpServletResponse response) {
    projectService.saveProjectNew(newProject, authentication);
    response.sendRedirect("url-here");   
}

欲了解更多信息鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM