过滤器一直返回NEED_LOGIN
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() { } }
@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; } }
问题描述:
用 Postman 登录成功后,请求后台删除目录功能,发现返回NEED_LOGIN,检查
currentUser 对象为 Null,检查代码无误,就是不知道什么问题?
相关截图:
8
收起
正在回答
1回答
同学你好,同学提供的代码并没有问题,所以错误应该不是这里导致的。
建议同学检查一下登录的代码,即UserController中的login方法,检查一下在登录的时候,调用UserService之后返回的User对象中的userName和password是否正确。然后检查一下是否正确的将User对象存储在了session中。代码如下:
@PostMapping("/login") @ResponseBody public ApiRestResponse login(@RequestParam("userName") String userName, @RequestParam("password") String password, HttpSession session) throws ImoocMallException { if (StringUtils.isEmpty(userName)) { return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_USER_NAME); } if (StringUtils.isEmpty(password)) { return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_PASSWORD); } User user = userService.login(userName, password); //保存用户信息时,不保存密码 user.setPassword(null); session.setAttribute(Constant.IMOOC_MALL_USER, user); return ApiRestResponse.success(user); }
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星