1.定义一个全局注解:
/**
* 要求登录<br>
* 要求登录注解
*
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface NeedLogin {
boolean value();
}
@Target({ ElementType.METHOD, ElementType.TYPE })
表示的是注解可以使用的范围,这里用于描述方法和
描述类、接口(包括注解类型) 或enum声明
@Retention(RetentionPolicy.RUNTIME)
定义了该Annotation被保留的时间长短:在运行时有效
@Documented
表示是一个公用注解
上面已经定义好了一个自定义注解了
@SuppressWarnings("unchecked")
@RequestMapping("toJobList")
@NeedLogin(true)
public ModelAndView toAmJobList(HttpServletRequest request, ModelAndView view, HttpSession session) {
可以在controller上添加
@NeedLogin(true)这个注解
<pre name="code" class="java"> @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 访问的链接
String requestUrl = request.getRequestURI();
// 上下文路径
String contentPath = request.getContextPath();
// 去掉uri中的上下文路径 后的 url ,数据库中配置的url 都是 没有上下文路径的
String shortRequetUri = requestUrl.replace(contentPath, "");
HandlerMethod methodhandler = (HandlerMethod) handler;
// 方法
Method method = methodhandler.getMethod();
// 获取求头
String requestheader = request.getHeader("X-Requested-With"); // Ajax请求
// 注入 权限接口实现
if (null == permissionService) {
ServletContext context = request.getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
permissionService = (PermissionService) ac.getBean("permissionService");
}
if (null == crmOperatorGwService) {
ServletContext context = request.getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
crmOperatorGwService = (CrmOperatorGwService) ac.getBean("crmOperatorGwService");
}
// 获取 操作者角色 的注解
Role role = methodhandler.getBean().getClass().getAnnotation(Role.class);
// 获取方法上的 是否 登录注解
NeedLogin needLoginAnnotation = method.getAnnotation(NeedLogin.class);
这个是拦截器中的部分代码,我们在这里通过判断
@NeedLogin是否包含这个注解去完成我们自己的逻辑