MyShiroFilterFactoryBean.java
public class MyShiroFilterFactoryBean extends ShiroFilterFactoryBean {
private static final String ROLE_STRING = "roles[{0}]";
private String filterChainDefinitions;
@Override
public void setFilterChainDefinitions(String definitions) {
filterChainDefinitions = definitions;
Ini ini = new Ini();
ini.load(definitions);
Ini.Section section = ini.getSection("urls");
if (CollectionUtils.isEmpty(section)) {
section = ini.getSection("");
}
//模拟从数据库中读取的数据
Map<String, String[]> permsMap = new HashMap<>();
permsMap.put("/dotest1.html", new String[]{"test"});
permsMap.put("/dotest2.html", new String[]{"test", "guest"});
//permsMap.put("/dotest3.html", new String[]{"admin"});
for (String url : permsMap.keySet()) {
String[] roles = permsMap.get(url);
StringBuilder sb = new StringBuilder();
for (String role : roles) {
sb.append(role).append(",");
}
String str = sb.substring(0, sb.length() - 1);
//roles[test,guest]
section.put(url, MessageFormat.format(ROLE_STRING, str));
}
this.setFilterChainDefinitionMap(section);
}
public void update() {
synchronized (this) {
try {
AbstractShiroFilter shiroFilter =
(AbstractShiroFilter) this.getObject();
PathMatchingFilterChainResolver resolver =
(PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
DefaultFilterChainManager manager = (DefaultFilterChainManager) resolver.getFilterChainManager();
manager.getFilterChains().clear();
this.getFilterChainDefinitionMap().clear();
this.setFilterChainDefinitions(filterChainDefinitions);
Map<String, String> chains = this.getFilterChainDefinitionMap();
if (!CollectionUtils.isEmpty(chains)) {
Iterator var12 = chains.entrySet().iterator();
while (var12.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry) var12.next();
String url = (String) entry.getKey();
String chainDefinition = (String) entry.getValue();
manager.createChain(url, chainDefinition);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
PageController.java
@Controller
public class PageController {
@RequestMapping("index.html")
public String index() {
return "index";
}
@Autowired
private MyShiroFilterFactoryBean shiroFilterFactoryBean;
@RequestMapping("update.html")
public String update() {
shiroFilterFactoryBean.update();
return "index";
}
@RequestMapping("error.html")
public String error() {
return "error";
}
@RequestMapping("do{path}.html")
public String page(@PathVariable(name = "path") String path, Model model) {
model.addAttribute("path", path);
return "test";
}
}