这是我写的登录的controller和service层
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserServiceImpl userService;
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping("/doLogin")
@ResponseBody
public ResultInfo doLogin(@Valid LoginVo loginVo, HttpServletRequest request, HttpServletResponse response){
return userService.doLogin(loginVo,request,response);
}
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Resource
private RedisTemplate<String,Object> redisTemplate;
@Resource
private UserMapper userMapper;
@Override
public ResultInfo doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
String phone = loginVo.getMobile();
String password = loginVo.getPassword();
User user = userMapper.selectById(phone);
if(user==null){
throw new UserNotExistException();
}
if(!MD5Util.form2DB(password,user.getSlat()).equals(user.getPassword())){
throw new PwdErrorException();
}
String ticket = UUIdUtil.uuid();
CookieUtil.setCookie(request,response,"userTicket",ticket);
//讲用户信息存储到Redis中
ValueOperations<String, Object> value = redisTemplate.opsForValue();
value.set("user:"+ticket, JsonUtil.object2JsonStr(user),10,TimeUnit.DAYS);
return ResultInfo.success(ticket);
}
@Override
public User getUser(String ticket) {
if (StringUtils.isEmpty(ticket)){
return null;
}
return JsonUtil.jsonStr2Object(((String) redisTemplate.opsForValue().get("user:"+ticket)),User.class);
}
}
在这里抛出了两个自定义异常,分别是用户不存在和密码不相等的异常。
这是我的全局异常的代码
@RestControllerAdvice
@Component
public class GlobalExceptionHandle {
@ExceptionHandler(Exception.class)
public ResultInfo exceptionHandler(Exception e,ModelAndView modelAndView) {
if (e instanceof BindException) {
BindException bindException = (BindException) e;
String message = bindException.getBindingResult().getAllErrors().get(0).getDefaultMessage();
ResultInfo resultInfo = new ResultInfo();
resultInfo.setMsg(message);
return resultInfo;
} else if (e instanceof UserNotExistException) {
UserNotExistException userNotExistException = (UserNotExistException) e;
System.out.println(userNotExistException.getResultEnum());
return ResultInfo.error(userNotExistException.getResultEnum());
} else if (e instanceof PwdErrorException) {
PwdErrorException pwdErrorException = (PwdErrorException) e;
return ResultInfo.error(pwdErrorException.getResultEnum());
}
else if (e instanceof GlobalException) {
GlobalException globalException = (GlobalException) e;
return ResultInfo.error(globalException.getResultEnum());
}
return ResultInfo.error(ResultEnum.ERROR);
}
}
这个时候我输入一个未注册的手机号,应该显式手机号未注册,但是服务器报错了
这是服务器内的错误
找了半天也没找到是什么问题,最后发现我的全局异常处理中,有个参数modelAndView没有用,我就删了。
删除之后,我再一次登录,就成功了,也不知道为什么。