Spring Boot项目开发(六)——编写过滤器,统一处理登录权限
一、编写过滤器
package com.learn.mall.filter; import com.learn.mall.common.Constant; import com.learn.mall.model.pojo.User; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; /** * 用户登录权限过滤器 */ public class AdminFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpSession session = request.getSession(); //判断用户是否登录 User user = (User) session.getAttribute(Constant.USER); if(user == null){ PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse)servletResponse).getWriter(); out.write("{\"status\":\"10007\",\"msg\":\"NEED_LOGIN\",\"data\":\"null\"}"); out.flush(); out.close(); return ; } //判断用户是否是超级管理员 if(user.getRole().equals(1)){ PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse)servletResponse).getWriter(); out.write("{\"status\":\"10008\",\"msg\":\"NEED_ADMIN\",\"data\":\"null\"}"); out.flush(); out.close(); }else{ //管理员登录则放行,执行后面的操作 filterChain.doFilter(servletRequest,servletResponse); } } @Override public void destroy() { } }
二、编写过滤器配置文件
package com.learn.mall.config; import com.learn.mall.filter.AdminFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 用户登录权限过滤器的配置 */ @Configuration public class AdminFilterConfig { @Bean public AdminFilter adminFilter(){ return new AdminFilter(); } @Bean(name = "adminFilterConf") public FilterRegistrationBean adminFilterConfig(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(adminFilter()); filterRegistrationBean.addUrlPatterns("/admin/category/*"); filterRegistrationBean.addUrlPatterns("/admin/product/*"); filterRegistrationBean.addUrlPatterns("/admin/order/*"); filterRegistrationBean.setName("adminFilterConf"); return filterRegistrationBean; } }