Filter过滤器完成验证代码的封装
- filter是什么
- 1 使用filter
- 2 filter配置到项目中
验证用户权限是需要反复使用的代码块,把他封装到filter中,减少代码冗余
filter是什么
init()方法:初始化方法,在创建Filter后立即调用。可用于完成初始
化动作。
doFilter()方法:拦截请求与响应方法,可用于对请求和响应实现预
处理。
destroy()方法:销毁方法,在销毁Filter之前自动调用。可用于完成
资源释放等动作。
1 使用filter
不使用filter时,controller层验证代码
User currentUser = (User)httpSession.getAttribute(Constant.IMOOC_MALL_USER);
# 检查用户是否登录
if(currentUser==null){
return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_LOGIN);
}
#检查是否是管理员
boolean adminRole = userService.checkAdminRole(currentUser);
if(adminRole){
categoryService.add(addCategoryReq);
return ApiRestResponse.success();
}else {
return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_ADMIN);
}
使用filter代码就替换了统一返回的方式
package com.imooc.mall.filter;
import com.imooc.mall.common.ApiRestResponse;
import com.imooc.mall.common.Constant;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.pojo.Category;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.service.UserService;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 描述: 管理员校验过滤器
*/
public class AdminFilter implements Filter {
@Autowired
UserService userService;
@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 currentUser = (User) session.getAttribute(Constant.IMOOC_MALL_USER);
if (currentUser == null) {
PrintWriter out = new HttpServletResponseWrapper(
(HttpServletResponse) servletResponse).getWriter();
out.write("{\n"
+ " \"status\": 10007,\n"
+ " \"msg\": \"NEED_LOGIN\",\n"
+ " \"data\": null\n"
+ "}");
out.flush();
out.close();
return;
}
//校验是否是管理员
boolean adminRole = userService.checkAdminRole(currentUser);
if (adminRole) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
PrintWriter out = new HttpServletResponseWrapper(
(HttpServletResponse) servletResponse).getWriter();
out.write("{\n"
+ " \"status\": 10009,\n"
+ " \"msg\": \"NEED_ADMIN\",\n"
+ " \"data\": null\n"
+ "}");
out.flush();
out.close();
}
}
@Override
public void destroy() {
}
}
替换为(是返回给前端信息,用response)以字节流方式。
PrintWriter out = new HttpServletResponseWrapper(
(HttpServletResponse) servletResponse).getWriter();
out.write("{\n"
+ " \"status\": 10007,\n"
+ " \"msg\": \"NEED_LOGIN\",\n"
+ " \"data\": null\n"
+ "}");
out.flush();
out.close();
其中,放行的代码:
filterChain.doFilter(servletRequest, servletResponse);
2 filter配置到项目中
package com.imooc.mall.config;
import com.imooc.mall.filter.AdminFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 描述: Admin过滤器的配置
*/
@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;
// }
@Bean
public FilterRegistrationBean<AdminFilter> requestContextFilterFilterRegistrationBean() {
FilterRegistrationBean<AdminFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new AdminFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.addUrlPatterns("/admin/category/*");
registrationBean.addUrlPatterns("/admin/product/*");
registrationBean.addUrlPatterns("/admin/order/*");
registrationBean.setName("adminFilterConf");
registrationBean.setOrder(2);
return registrationBean;
}
}
这个配置filter的bug弄了挺久。。。
使用filter过滤器,对于admin开头的url进行统一鉴权。