使用注解(Annotation)实现系统登录检查和权限控制

来源:互联网 发布:钢结构图纸及数据图片 编辑:程序博客网 时间:2024/06/05 14:15


系统的大量操作都必须在用户登录的状态下进行,特别是后台管理系统。在进行系统开发时,进行登录状态检查是必不可少的步骤。此处采用注解的方法,实现登录检查。


第一步,新建注解AllowAnonymous和HasPermission("Permission String")

@Target(value=ElementType.METHOD)@Retention(value=RetentionPolicy.RUNTIME)public @interface AllowAnonymous {}

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface HasPermission {public String value();}


第二步,建立BasicServlet

在BasicServlet中通过反射读取注解信息,如果没有标记AllowAnonymous,则说明操作需要进行登录检查。对不需要登录就可以进行的操作,需要标记AllowAnonymous。

public class BasicServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doGet(req, resp);}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {String action=req.getParameter("action");if (StringUtils.isEmpty(action)) {AdminUtils.showError(req, resp, "action error");return;}Class cls=this.getClass();try {Method methodAction=cls.getMethod(action, HttpServletRequest.class,HttpServletResponse.class);AllowAnonymous allowAnonymous=methodAction.getAnnotation(AllowAnonymous.class);if (allowAnonymous==null) {//need to check login statusLong adminUserId=AdminUtils.getAdminUserId(req);if (adminUserId==null) {String ctxPath=req.getContextPath();AdminUtils.showError(req, resp, "未登陆<a target='_top' href='"+ctxPath+"/Index?action=login'>点此登录</a>");return;}HasPermission hasPermission=methodAction.getAnnotation(HasPermission.class);if (hasPermission!=null) {AdminUserService adminUserService=new AdminUserService();boolean isOk=adminUserService.hasPermission(adminUserId, hasPermission.value());if (!isOk) {AdminUtils.showError(req, resp, "无权访问");return;}}}methodAction.invoke(this, req,resp);}  catch (Exception e) {//异常处理} }}



第三部,建立其它Servlet,继承BasicServlet

@WebServlet("/Index")public class IndexServlet extends BasicServlet {public void index(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{req.getRequestDispatcher("/WEB-INF/index.jsp").forward(req, resp);}       //登录操作,不需要进行登录检查,标记AllowAnonymous       @AllowAnonymous    public void login(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{        req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req, resp);    } }

public class RoleServlet extends BasicServlet {        //标记需要的权限@HasPermission("Role.Query")public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {RoleService roleService = new RoleService();RoleDTO[] roles = roleService.getAllNotDeleted();request.setAttribute("roles", roles);request.getRequestDispatcher("/WEB-INF/role/roleList.jsp").forward(request, response);} catch (ServletException | IOException e) {AdminUtils.showError(request, response, "Service Error");}}}




阅读全文
1 0
原创粉丝点击