springboot之拦截器

时间:2024-12-27 13:07:38

拦截器:

  

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 "登录成功"; }
}