spring boot 拦截器使用示例

使用 spring boot 拦截器只需要两个类,一个拦截器类,一个拦截器注册类,示例代码如下:

创建用户登录校验拦截器LoginInterceptor:

package com.example.demo.intercepter;

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 LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        HttpSession session = request.getSession();
        //用户已登录
        if (session.getAttribute("user") != null) {
            return true;
        } else {//用户未登录,直接跳转登录页面
            response.sendRedirect("/login");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

创建拦截器注册类WebConfigurer:

package com.example.demo.intercepter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加自定义拦截器和拦截路径,此处对所有请求进行拦截,除了登录界面和登录接口
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/user/login");
    }
}

说明:addPathPatterns方法用于添加拦截路径,excludePathPatterns方法用于添加不需要拦截的路径,两个方法的参数都是不定长数组,可以同时添加多个路径。


其他使用到的业务相关类
用户控制类UserController

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.repository.BaseRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @PostMapping("/login")
    @ResponseBody
    public Result login(HttpSession session, User user) {
        //模拟登录
        if ("admin".equals(user.getUserName()) && "123456".equals(user.getPassword())){
            session.setAttribute("user", user);
            return new Result(Result.SUCCESS, "登录成功!");
        }
        return new Result(Result.FAILED, "登录失败,请核对用户名密码后重试!");
    }

    @PostMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "/login";
    }
}

首页跳转类IndexController:

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

@Controller
public class IndexController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }
}

你可能感兴趣的:(Java)