美文网首页
Spring MVC 作业讲解

Spring MVC 作业讲解

作者: 烦远远 | 来源:发表于2022-06-06 00:00 被阅读0次

1 增加权限注解类

注解值是String数组

package com.lagou.edu.mvcframework.annotations;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Security {
    String[] value() default {} ;
}

2 doPost方法添加权限校验代码

在dopost方法中增加验证注解值是否跟参数值name一致

        // 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list))
        Handler handler = getHandler(req);

        if(handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        // 验证权限类型
        if (handler.getMethod().isAnnotationPresent(Security.class)) {
            Security annotation = handler.getMethod().getAnnotation(Security.class);
            String[] securities = annotation.value();
            String name = req.getParameter("name");
            Optional<String> first = Arrays.stream(securities).filter(security -> name.equals(security)).findFirst();
            if (!first.isPresent()) {
                resp.getWriter().write("no Security!");
                return;
            }
        }

3 验证结果

controller 配置权限注解值为 hava 和 all

    @LagouRequestMapping("/query")
    @Security({"have","all"})
    public String query(HttpServletRequest request, HttpServletResponse response,String name) {
        return demoService.get(name);
    }

预计结果:浏览器输入 have 或者 all 方法可正常运行,输入其它的值页面会报 no Security!
输入 have 运行结果如图

运行结果
输入 all运行结果如图
运行结果
输入 no运行结果如图
运行结果

相关文章

网友评论

      本文标题:Spring MVC 作业讲解

      本文链接:https://www.haomeiwen.com/subject/ilmdmrtx.html