使用ResponseEntity<>改写以下代码:@Controller @RequestMapping("/user") public class UserController { @RequestMapping(value = "/login", method = RequestMethod.POST) public ModelAndView login(User user,HttpSession httpSession) { ModelAndView modelAndView = new ModelAndView(); if (user.getUserName().equals("张三") && user.getPassword().equals("123")) { //modelAndView.addObject("user", user); httpSession.setAttribute("user",user); modelAndView.setViewName("success"); } else { modelAndView.setViewName("fail"); } return modelAndView; } }
时间: 2024-01-06 11:06:28 浏览: 104
springmvc:@Controller @RequestMapping @RequestParam,模型和ModelAndView Spring MVC实践
@Controller
@RequestMapping("/user")
public class UserController {
@PostMapping("/login")
public ResponseEntity<String> login(User user, HttpSession httpSession) {
if (user.getUserName().equals("张三") && user.getPassword().equals("123")) {
httpSession.setAttribute("user", user);
return ResponseEntity.ok("success");
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("fail");
}
}
}
注意,这里返回的是一个ResponseEntity<String>对象,其中泛型指定了返回值的类型为String。如果登录成功,使用ResponseEntity.ok()返回一个状态码为200的响应,并将成功信息放入响应体;如果登录失败,使用ResponseEntity.status(HttpStatus.UNAUTHORIZED)返回一个状态码为401的响应,并将失败信息放入响应体。
阅读全文