同一Controller内方法调用及管理员权限校验异常处理问题
问题1:让未登录用户调用更新接口时抛出指定异常
要实现这个需求,得先在updatePlayersDataAfterMatch接口里加一层管理员登录状态校验。可以用Spring的HttpSession来存储登录状态,登录成功后把管理员信息存入Session,更新接口先判断Session里有没有登录的管理员,没有就抛AdminNeedToLoginFirstException。
修改后的updatePlayersDataAfterMatch方法:
@PutMapping(value = "/updateplayerdataaftermatch") public ResponseEntity<Boolean> updatePlayersDataAfterMatch(@Valid @RequestBody Param param, HttpSession session) { // 从Session获取已登录的管理员信息,这里假设登录成功后存在"loggedInAdmin"键下 Admin loggedInAdmin = (Admin) session.getAttribute("loggedInAdmin"); if (loggedInAdmin == null) { throw new AdminNeedToLoginFirstException("管理员需先登录才能执行此操作"); } boolean updateSuccess = service.updatePlayersDataAfterMatch(param); if (updateSuccess) { return new ResponseEntity<>(updateSuccess, HttpStatus.OK); } else { throw new PlayerDetailNotFoundException("你要更新的球员不存在或名称拼写错误:" + param.getPlayerName()); } }
另外,得在adminLoginwithOTP方法里,登录成功后把管理员信息存入Session:
@PostMapping(value="/enterOTPforLogin/{otp}") public ResponseEntity<Boolean> adminLoginwithOTP(@Valid @PathVariable @NotNull(message="请输入OTP") String otp, HttpSession session) { boolean successfull = service.adminLoginwithOTP(otp); if (successfull) { // 这里需要调整你的service逻辑,让它返回登录成功的管理员对象 Admin loggedInAdmin = service.getLoggedInAdmin(); session.setAttribute("loggedInAdmin", loggedInAdmin); return new ResponseEntity<>(successfull, HttpStatus.OK); } else { throw new OTPWrongEnteredException("输入的OTP错误,请重新生成"); } }
问题2:同一个Controller类里调用Controller方法的正确姿势
绝对不能用new IPLController()来创建实例调用方法!Spring管理的Controller是单例Bean,new出来的对象不受Spring托管,里面的service等依赖不会被注入,大概率会出现空指针或者逻辑错误。
推荐两种正确做法:
首选:把公共逻辑抽到Service层
Controller只负责接收请求、返回响应,业务逻辑都放到Service层里。如果两个Controller方法需要复用逻辑,直接调用同一个Service方法就行,这才符合分层架构的设计,代码也更清晰。次选:通过@Autowired注入自身(不推荐,仅作参考)
如果确实要在Controller内部调用自己的方法,可以让Spring把自身注入进来:
@RestController public class IPLController { @Autowired private IPLController self; // 注入自身实例 @PostMapping(value="/enterOTPforLogin/{otp}") public ResponseEntity<Boolean> adminLoginwithOTP(...) { // 调用自身的其他方法 self.someOtherMethod(); // ...其他业务逻辑 } }
但这种方式不推荐,毕竟Controller的职责就是处理请求,复用逻辑下沉到Service层才是合理的。
内容的提问来源于stack exchange,提问作者Ankush Kamble
相关产品推荐
相关产品推荐

