繁体   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