我有一个Spring MVC项目,它使用Thymeleaf进行前端数据绑定。我希望在更新用户姓名时显示成功消息。这是更新屏幕:example。此时,用户被重定向到登录页面,但我希望在更新名称时显示一条消息,并在重定向前等待5秒。我可以在页面的get方法中传递一个布尔值,并在调用post方法时将其设置为true吗?
@RequestMapping(value = "/resetUserName", method = RequestMethod.GET)
public ModelAndView displayResetUsernamePage(ModelAndView modelAndView, @ModelAttribute User user) {
logger.info("Entered displayResetUsernamePage function");
return modelAndView;
}
@RequestMapping(value = "/resetUserName", method = RequestMethod.POST)
public ModelAndView setNewUsername(ModelAndView modelAndView, @ModelAttribute User user, HttpServletRequest httpServletRequest, @AuthenticationPrincipal User currentUser) throws ServletException {
logger.info("Entered setNewUsername function");
User exists = userService.findUserByUserName(user.getUsername());
if (exists == null) {
User updatedUser = userService.updateUsername(currentUser.getUsername(), user);
logger.info("Username change successful: " + currentUser.getUsername() + " is now " + user.getUsername());
emailService.sendEmailResetUsername(user, currentUser);
} else {
throw new ResourceNotFoundException();
}
modelAndView.setViewName("login");
httpServletRequest.logout();
return modelAndView;
}
以下是get和post方法,我可以将一个布尔值传递给get方法并在post方法中将其设置为true吗?然后在Thymeleaf中显示它:如果$ {resetSuccess}显示html?
类似的东西:
<div th:if="${resetSuccess}">
Username change successfull !
</div>
答案 0 :(得分:1)
您希望更新用户信息并等待5秒钟并重定向到登录页面。
这是您的示例代码:
修改帖子方法
@RequestMapping(value = "/reset/account/{idx}", method = RequestMethod.POST)
public @ResponseBody String resetAccount(@PathVariable long idx, @RequestBody User user) {
// select user by idx.
// update old user by new user.
// need to handle return string message.
return "success";
}
<强> AJAX 强>
// you need user idx.
var userIdx = 32;
// make user JSON.
var user = {
"name" : "username"
}
user = JSON.stringify(user);
$.ajax({
url : "/reset/account" + userIdx,
type : 'POST',
data : user,
contentType : 'application/json',
dataType : 'text',
success : function(response) {
// updated user information.
if ("success" == response) {
// show success message box.
setTimeout(function() {
location.href = "/your/login/page";
}, 5000);
} else {
// handling false or fail.
}
},
error : function(request, status, error) {
}
});