springboot_ use custom annotation + interceptor implement access control

Here is a simple example, means that only administrators can delete function.

A custom annotation

We customize a comment, the comment notes the need to intercept the url corresponding method

package com.rong.crud.self;

import java.lang.annotation.*;

//说明该注解将被包含在javadoc中
@Documented
//可以在方法和类上使用注解
@Target({ElementType.METHOD,ElementType.TYPE})
// 定义的这个注解是注解会在class字节码文件中存在,在运行时可以通过反射获取到。
@Retention(RetentionPolicy.RUNTIME)
// 子类可以继承父类中的该注解
@Inherited
public @interface MyAnnotation {

}

Two, to the corresponding annotation method

Because we want to intercept the delete function, so notes in this function above

    /**
     * 删除
     * @param id
     * @return
     */
    @MyAnnotation
    @RequestMapping("/student/delete")
    public String delete(@RequestParam("id") Integer id){
        studentService.deleteStudent(id);
        return "redirect:/index";
    }

Third, custom interceptor

package com.rong.crud.interceptor;


import com.rong.crud.bean.User;
import com.rong.crud.self.MyAnnotation;
import org.springframework.ui.Model;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器");
        //获得名为user的对象
        Object user = request.getSession().getAttribute("user");
        //判断请求的方法上是否有注解
        boolean haveAnnotataion = handler.getClass().isAssignableFrom(HandlerMethod.class);

        if(haveAnnotataion){
            //如果有注解,判断是否是MyAnnotation
            MyAnnotation ma = ((HandlerMethod)handler).getMethodAnnotation(MyAnnotation.class);
            //如果存在该注解
            if(ma != null) {
                //判断用户名是否是admin(这里把用户名为admind的用户当作管理员)
                if(!((User)user).getName().equals("admin")){
                    //如果不是转发到/index上
                    request.setAttribute("msg","你未有权限!");
                    request.getRequestDispatcher("/index").forward(request,response);
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

Here I was forwarded to the on / index, you can refer to, in fact, you need to realize how you how to write

  @RequestMapping("/index")
    public String index(Model model, HttpServletRequest request) {
        String msg =(String)request.getAttribute("msg");
        List<Student> studentList = studentService.selectAllStudent();
        model.addAttribute("studentList", studentList);
        model.addAttribute("msg",msg);
        return "index";
    }

Configuration class interceptor, which intercepts the request specified

package com.rong.crud.config;

import com.rong.crud.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器配置类
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册拦截器
        InterceptorRegistration ir = registry.addInterceptor(new MyInterceptor());

        //添加拦截请求
        ir.addPathPatterns("/student/*");

        //添加不拦截的请求
       ir.excludePathPatterns("/student/addOrUpdate");

      
    }
}

Fourth, to achieve graphic

Let's login as an administrator (write a simple page): When you delete directly deleted

 

We log in as a normal user (omitted here login section of), you will see this is not permission to use deleted.

This reference to the following blog post: https://blog.csdn.net/sunnyzyq/article/details/95348788

Published 60 original articles · won praise 10 · views 9183

Guess you like

Origin blog.csdn.net/chaseqrr/article/details/104391745