I recently tried to use SpringBoot as a backend management system. Since I haven’t learned VUE yet, the front-end page uses the thymeleaf ajax mode. I encountered a problem when developing the login page two days ago. After logging in, according to the normal process, I should jump to the homepage in the controller, but my login page does not jump. There is no problem with the logic of the controller
@Controller class LoginController { @Resource lateinit var adminService: AdminService @RequestMapping("/login",method = [RequestMethod.POST]) fun login(@RequestParam name:String,@RequestParam password:String):String?{ val admin=adminService.login(name,password) return if (admin==null){ "" }else{ //一般情况下是可以直接渲染到main.html的,但是添加了Ajax之后跳转就会失效 "main" } } }
The logic in Ajax
$.ajax({ method: 'POST', url: 'http://localhost:8080/login', data: { name: $('[name="username"]').val(), password: $('[name="password"]').val() }, success:function (r) { console.log(r) }, error:function (result) { alert(result) } })
The information returned by the console
##SolutionThe solution is given here first, and the reason will be explained at the end. Adding a mainPage method in the controller, corresponding to main.html, can solve the problem.@RequestMapping("/main") fun mainPage():String{ return "main" }Then call this controller in the Ajax success callback to complete the jump.
success:function (r) { window.location.href="http://localhost:8080/main" rel="external nofollow" },Cause sorting outAt first I thought there was a problem with the controller, and then I modified the configuration of the controller in various ways. Finally, I found that no matter how I modified it, it had no effect, and I found that if I browse There is no problem if the controller path of main.html is directly called in the server. In this case, I wonder if it may be an Ajax problem. In order to verify whether it is an Ajax problem, I set a breakpoint in the code where the Ajax callback is successful. I want to see what the data returned from the background is. Do you see it? , the controller returns the entire main.html page to Ajax. That is to say, when using Ajax, the SpringBoot controller does not render the page, but returns the target page structure, so that it can jump. Weird.
The above is the detailed content of How to solve the problem of SpringBoot not jumping when Ajax is present. For more information, please follow other related articles on the PHP Chinese website!