zoukankan      html  css  js  c++  java
  • springboot之拦截器

    拦截器:

      

    package com.example.demo;
    
    import org.springframework.context.annotation.Bean;
    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;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    
    @Configuration
    public class WebConfiguration implements WebMvcConfigurer {
    
    
        @Bean
        public SecurityInterceptor getSecurityInterceptor() {
            return new SecurityInterceptor();
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
            //排除配置
            addInterceptor.excludePathPatterns("/login/**");//排除登录
            // 拦截配置
            addInterceptor.addPathPatterns("/**/**");
        }
    
        private class SecurityInterceptor extends HandlerInterceptorAdapter {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
                HttpSession session = request.getSession();
                //判断是否已有该用户登录的session
                if (session.getAttribute("account") != null) {
                    return true;
                }
                response.getWriter().print("not login");
                return false;
            }
        }
    }
    

      控制器:

    package com.example.demo;
    
    import com.example.demo.bean.User;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpSession;
    
    
    @RestController
    public class MailController {
    
    
        @GetMapping("/user")
        public User send() {
    
            User user = new User();
            user.setName("Li Hua");
            user.setAge(25);
            user.setSex(1);
            return user;
    
        }
    
        @GetMapping("/login")
        public String login(HttpSession session) {
           session.setAttribute("account", "ggband");
            return "登录成功";
    
        }
    }
    

      

    ggband
  • 相关阅读:
    CSS选择器
    CSS框模型
    AJAX
    HTML 表单
    二叉树
    词嵌入、word2vec
    双向、深层循环神经网络
    20201012----每天都在进步吗?
    20201012--环境搭建
    20201011--记录一下
  • 原文地址:https://www.cnblogs.com/ggband/p/9714247.html
Copyright © 2011-2022 走看看