notes
10, Springboot2.x user logs on to develop the interceptor combat
Introduction: User login combat development interceptor interceptor LoginInterceptor
1, the implements HandlerInterceptor implement the interface LoginInterceptor
2, rewrite preHandler
String = accessToken request.getHeader ( "token");
IF (accessToken = null =) {
accessToken = request.getParameter ( "token");
}
IF (accessToken = null) {!
Claims Claims = JWTUtils.checkJWT (accessToken);
Integer ID = (Integer) claims.get ( "ID");
String = name (String) claims.get ( "name");
request.setAttribute ( "user_id", ID);
request.setAttribute ( "name",name);
//普通用户
return true;
}
return false;
3、配置拦截器
@Configuration
InterceptorConfig implements WebMvcConfigurer
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/api/v1/*/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
4、响应前端数据
public static void sendJsonMessage(HttpServletResponse response, Object obj) throws Exception {
Gson g = new Gson();
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print(g.toJson(obj));
writer.close();
response.flushBuffer();
}
Start
Create a login interceptor
implements the interface, and override the method
override method
has some default method in the interface. New features jdk8 of
intercept before entering the Controller
First we need to get the token. If you can not get inside Header. It is taken from the parameter inside.
Acquiring decrypted token value which
is defined at the top of a variable Gson
package a respective data process
here again is not equal to null Claims determine what
abnormalities must be modified to throw herein in the above methods
here id userId not just wrong here.
Connector Configuration
New interceptor profile
increase @Configuration indicates that this is a configuration file that implements the interface WebMvcConfigurer
methods within the interface rewrites
the registry into them. This put a good interception to register.
New OrderController
is mainly used to simulate determine whether the landing.
test
Start Service
access video can be accessed.
Path access user, will be blocked interceptors.
Breakpoint debugging in the interceptor
casually pass a token value in the past
token value, although there are, but the decryption will fail
The domain debugging
Url address to get the scan code of
the jump successfully, to get this token, copy down
the copy down token
to copy down the token. Then go visit
into the interceptor breakpoint inside. Claims to decrypt successfully obtained
the release of the next single will be prompted to success