这个问题困扰了我一天,看了下面两个文章,豁然开朗:

https://www.cnblogs.com/gj1990/p/8057348.html

https://412887952-qq-com.iteye.com/blog/2392741

按照如下方法即可解决无法显示静态资源问题:

一、让springboot拦截器来接管静态资源,同时在shiroconfig中通过new方式注册过滤器

1、代码一

 import java.util.Arrays;

 import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /**
* SpringBoot管理器
*/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer { private final Logger logger = LoggerFactory.getLogger(WebMvcConfiguration.class); @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginRequiredInterceptor()).excludePathPatterns(Arrays.asList("/css/**", "/js/**","/img/**","/fonts/**"));
}
}

2、代码二

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /**
* 登录拦截器
*
*
*/
public class LoginRequiredInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(LoginRequiredInterceptor.class); @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info(request.getRequestURI());
return super.preHandle(request, response, handler);
} @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
logger.info(request.getRequestURI());
super.afterCompletion(request, response, handler, ex);
}
}

三、shiro配置中使用new方式生成filter

filters.put("authc", new ExtendFormAuthenticationFilter());
filterChainDefinitionMap.put("/**", "user,authc");

四、自定义filter

import com.simon.common.util.R;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter; public class ExtendFormAuthenticationFilter extends FormAuthenticationFilter { private static final Logger log = LoggerFactory.getLogger(FormAuthenticationFilter.class); /**
* 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。
* onAccessDenied是否执行取决于isAccessAllowed的值,如果返回true则onAccessDenied不会执行;如果返回false,执行onAccessDenied
* 如果onAccessDenied也返回false,则直接返回,不会进入请求的方法(只有isAccessAllowed和onAccessDenied的情况下)
* */ @Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { if(this.isLoginRequest(request, response)) {
if(this.isLoginSubmission(request, response)) {
if(log.isTraceEnabled()) {
log.trace("Login submission detected. Attempting to execute login.");
} return this.executeLogin(request, response);
} else {
if(log.isTraceEnabled()) {
log.trace("Login page view.");
} return true;
}
} else {
if(log.isTraceEnabled()) {
log.trace("Attempting to access a path which requires authentication. Forwarding to the Authentication url [" + this.getLoginUrl() + "]");
} this.saveRequestAndRedirectToLogin(request, response);
return false;
}
} /** * 当登录成功 * @param token * @param subject * @param request * @param response * @return * @throws Exception */
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response; if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest
.getHeader("X-Requested-With"))) {// 不是ajax请求
issueSuccessRedirect(request, response);
} else {
httpServletResponse.setCharacterEncoding("UTF-8");
PrintWriter out = httpServletResponse.getWriter(); //out.println("{\"success\":true,\"message\":\"登入成功\"}");
out.println(R.ok());
out.flush();
out.close();
}
return false;
} /** * 当登录失败 * @param token * @param e * @param request * @param response * @return */
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request)
.getHeader("X-Requested-With"))) {// 不是ajax请求
setFailureAttribute(request, e);
return true;
}
try {
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String message = e.getClass().getSimpleName();
if ("IncorrectCredentialsException".equals(message)) {
out.println("{\"success\":false,\"message\":\"密码错误\"}");
} else if ("UnknownAccountException".equals(message)) {
out.println("{\"success\":false,\"message\":\"账号不存在\"}");
} else if ("LockedAccountException".equals(message)) {
out.println("{\"success\":false,\"message\":\"账号被锁定\"}");
} else {
out.println("{\"success\":false,\"message\":\"未知错误\"}");
}
out.flush();
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
} 第二种方式就是“取消Filter自动注册,不会添加到FilterChain中“,方法如下:
一、定义过滤器,如上第四步
二、在shiroconfig中声明自定义FormAuthenticationFilter
    @Bean
public ExtendFormAuthenticationFilter getLoginAdviceFilter(){
ExtendFormAuthenticationFilter filter=new ExtendFormAuthenticationFilter();
filter.setRememberMeParam("username");
filter.setPasswordParam("password");
//对应前端的checkbox的name = rememberMe
filter.setRememberMeParam("rememberMe");
filter.setLoginUrl(loginUrl);
return filter;
}

三、取消注册

    @Bean
public FilterRegistrationBean registrationBean(ExtendFormAuthenticationFilter customFormAuthenticationFilter){
FilterRegistrationBean registration = new FilterRegistrationBean(customFormAuthenticationFilter);
registration.setEnabled(false);//怎么取消 Filter自动注册,不会添加到FilterChain中.
return registration;
}

通过以上步骤就实现了解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题


解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题的更多相关文章

  1. shiro 自定义filter

    1.自定义登录filter package com.creatunion.callcenter.filter; import com.alibaba.fastjson.JSONObject; impo ...

  2. Shiro自定义realm实现密码验证及登录、密码加密注册、修改密码的验证

    一:先从登录开始,直接看代码 @RequestMapping(value="dologin",method = {RequestMethod.GET, RequestMethod. ...

  3. shiro session过期后ajax请求跳转(转)

    配置了 Shrio框架,session也集成进去了 ,发现问题session会话过期,点击页面,一直请求失败.本来想集成拦截器,过滤器,但是已经用了shiro框架,sessionDestroyed 方 ...

  4. 解决validaform先验证后 ajax提交

    $(".myfroms").Validform({//form class btnSubmit:".submitLayer", 绑定提交按钮 tiptype:4 ...

  5. web项目中url-pattern改成'/'后,js、css、图片等静态资源(404)无法访问问题解决办法

    感谢http://blog.csdn.net/this_super/article/details/7884383的文章 1.增加静态资源url映射 如Tomcat, Jetty, JBoss, Gl ...

  6. web项目中url-pattern改成'/'后,js、css、图片等静态资源(404)无法访问问题解决办法

    感谢http://blog.csdn.net/this_super/article/details/7884383的文章 1.增加静态资源url映射 如Tomcat, Jetty, JBoss, Gl ...

  7. 解决Shiro+SpringBoot自定义Filter不生效问题

    在SpringBoot+Shiro实现安全框架的时候,自定义扩展了一些Filter,并注册到ShiroFilter,但是运行的时候发现总是在ShiroFilter之前就进入了自定义Filter,结果当 ...

  8. shiro 返回json字符串 + 自定义filter

    前言: 在前后端分离的项目中, 在使用shiro的时候, 我们绝大部分时候, 并不想让浏览器跳转到那个页面去, 而是告诉前端, 你没有登录, 或者没有访问权限. 那这时候, 我们就需要返回json字符 ...

  9. Shiro权限管理框架(五):自定义Filter实现及其问题排查记录

    明确需求 在使用Shiro的时候,鉴权失败一般都是返回一个错误页或者登录页给前端,特别是后台系统,这种模式用的特别多.但是现在的项目越来越多的趋向于使用前后端分离的方式开发,这时候就需要响应Json数 ...

随机推荐

  1. go微服务框架kratos学习笔记七(kratos warden 负载均衡 balancer)

    目录 go微服务框架kratos学习笔记七(kratos warden 负载均衡 balancer) demo demo server demo client 池 dao service p2c ro ...

  2. python小知识点总结

    小知识点总结 1.python2和python3的区别   python2 python3 默认编码 ascii utf-8 input() raw_input() input() print 可以不 ...

  3. Java单体应用 - 开发工具 - 01.IntelliJ IDEA

    原文地址:http://www.work100.net/training/monolithic-tools-intellij-idea.html 更多教程:光束云 - 免费课程 IntelliJ ID ...

  4. SpringBoot系列教程之事务传递属性

    200202-SpringBoot系列教程之事务传递属性 对于mysql而言,关于事务的主要知识点可能几种在隔离级别上:在Spring体系中,使用事务的时候,还有一个知识点事务的传递属性同样重要,本文 ...

  5. Windows下Charles从下载安装到证书设置和浏览器抓包

    1.在Charles官网https://www.charlesproxy.com/download/下载,我这边下载的是免费体验版的. 2.安装好以后打开,配置Charles证书:选择help——SS ...

  6. 虚拟机ubuntu系统怎么添加 VMware tools

    首先弹出光盘 然后安装 点击安装VMware tools 然后进入光盘 打开VMware tools 文件夹 将解压文件拉到桌面上 打开桌面上的文件夹 不选中文件 然后键入下面的内容 输入密码 输入y ...

  7. 【WPF学习】第三十五章 资源字典

    如果希望在多个项目之间共享资源,可创建资源字典.资源字典只是XAML文档,除了存储希望使用的资源外,不做其他任何事情. 一.创建资源字典 下面是一个资源字典示例,它包含一个资源: <Resour ...

  8. mysql基础--查询

    1.mysql查询的五种子句: where子句(条件查询):按照“条件表达式”指定的条件进行查询. group by子句(分组):按照“属性名”指定的字段进行分组.group by子句通常和count ...

  9. 九 Shell中的数组

    数组:用一个变量存储一组数据,并能够对这组数据中的某一个数据单独操作. 数组的类型:一维数组.二维数组.多维数组 变量的类型 Shell中默认无类型 变量的值默认均视为文本 用在数字运算中时,自动将其 ...

  10. 项目架构级别规约框架Archunit调研

    背景 最近在做一个新项目的时候引入了一个架构方面的需求,就是需要检查项目的编码规范.模块分类规范.类依赖规范等,刚好接触到,正好做个调研. 很多时候,我们会制定项目的规范,例如: 硬性规定项目包结构中 ...