springboot自定义拦截器

1、拦截器

package com.example.demo.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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


public class MyHandlerInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if(session.getAttribute("username")==null){
            request.setAttribute("msg","没有权限,请先登录!");
            request.getRequestDispatcher("/").forward(request,response);
            return false;
        }

        return true;
    }

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

    }

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

    }
}

2、在登录操作是将用户存入session中

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @RequestMapping("/user/login")
    public  String login(@RequestParam("username")String username, @RequestParam("password")String password, Model model, HttpSession session){
        if(!StringUtils.isEmpty(username)&&("123").equals(password)){
            session.setAttribute("username",username);
            return "redirect:/main";
        }
        model.addAttribute("msg","用户名密码错误");
        return "index";
    }
}

3、注册拦截器

@Configuration
public class MyMvcConfig implements WebMvcConfigurer
{
	/*自定义拦截器(session保存用户)*/
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyHandlerInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/css/*")
                .excludePathPatterns("/img/*")
                .excludePathPatterns("/js/*")
                .excludePathPatterns("/")
                .excludePathPatterns("/index")
                .excludePathPatterns("/user/login");

    }
}

你可能感兴趣的:(spring,boot,spring,java)