Error Application Farm
In Controller
, we have customized a @Auth
note to implement permission control functions, such as:
@Auth(verifyLogin=false,verifyURL=false) @RequestMapping("/login") public ModelAndView loginthrows Exception{ Map<String,Object> context = getRootMap(); return forword("login", context); }
Indicates that the method does not require login validation, nor does it require URL permission validation.
- Aop. Implemented by the spring AOP intercept method call
- Interceptor. Register an interceptor to achieve the business function by reflecting the annotations of the called Controller method in the Interceptor
@Auth
It is obvious that interceptors are easier to use and have fewer code volumes. Check the signature of the Interceptor preHandle()
method:
publicbooleanpreHandle(HttpServletRequest request, throws Exception;
The third parameter, as the document learns, is the controller method that is about to be called. So we can get annotations by reflection @Auth
:
method = (HandlerMethod)handler;Auth method.getMethod().getAnnotation(Auth.class);
But the real-world problem is that handler
the actual type is not always the HandlerMethod
type, so the first line of code is often thrown ClassCastException
. The study found that the actual type would be if the GET request was to request a static file (the URI of the static file is configured in the spring configuration file), and handler
the DefaultServletHttpRequestHandler
cast would have an error.
Workaround
Before performing a cast, the instanceof
handler
HandlerMethod
Interceptor does not perform any validation logic and direct release by checking the actual type of the parameter, if not the type.
Why do you have to record it? Because I found that the foreigner to the demo did not perform type checking, misleading a lot of people, let users think handler
must be the HandlerMethod
type. It also reminds us to develop good programming habits and make sure to do type checking before performing a cast.
ClassCastException solution for SPRINGMVC interceptors with the Controller method annotated by reflection