在登陆接口我对请求进行了拦截,用于判断是否登陆,如果没有登陆只能使用部分接口。而这个“部分接口”是通过请求的uri来判断的。
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
boolean match = new AntPathMatcher().match("/member/**", uri);
if (match) {
// member接口(登陆,注册)可以不用登陆就使用,否则需要登陆
return true;
}
//获取登录的用户信息
// .....
if (attribute != null) {
// 已经登陆了
// .....
return true;
} else {
//未登录,返回登录页面
// .....
return false;
}
}
也就是只有/member/接口是放行的。
但是经常会发现uri获取的结果为“/error”
主要原因是可能如下
- 请求的方法有误:例如接口使用的是POST方法,但是请求的是GET方法,这样就会匹配不到路径,返回“/error”路径
- 参数解析失败:常见于POST方法,无法将前端的参数转换为RequestBody就会出现错误,比较容易出错的地方就是一些对象,例如我出错的就是因为时间无法转化为Data
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2022-09-07T04:29:48.042Z": not a valid representation (error: Failed to parse Date value '2022-09-07T04:29:48.042Z': Unparseable date: "2022-09-07T04:29:48.042Z"); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2022-09-07T04:29:48.042Z": not a valid representation (error: Failed to parse Date value '2022-09-07T04:29:48.042Z': Unparseable date: "2022-09-07T04:29:48.042Z")
at [Source: (PushbackInputStream); line: 3, column: 12] (through reference chain: top.dumbzarro.greensource.member.entity.MemberEntity["birth"])]
总言而之,言而总之,就是无法正确的进入到方法里面,uri就会变成“/error”
为了防止每次路径映射错误都导致返回给前端"未登录"的错误报错,所以可以再拦截器里再多加一个判断,如下:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
if(uri.equals("/error")){
// 路径映射错误
// .....
return false;
}
boolean match = new AntPathMatcher().match("/member/**", uri);
if (match) {
// member接口(登陆,注册)可以不用登陆就使用,否则需要登陆
return true;
}
//获取登录的用户信息
// .....
if (attribute != null) {
// 已经登陆了
// .....
return true;
} else {
//未登录,返回登录页面
// .....
return false;
}
}