springboot2.0---02、beetl整合shiro
阿新 • • 發佈:2018-12-20
第一步、Maven
<dependency> <groupId>com.ibeetl</groupId> <artifactId>beetl-framework-starter</artifactId> <version>1.1.55.RELEASE</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency>
第二步、程式碼
#預設配置 ENGINE=org.beetl.core.engine.DefaultTemplateEngine DELIMITER_PLACEHOLDER_START=${ DELIMITER_PLACEHOLDER_END=} [email protected] DELIMITER_STATEMENT_END= DIRECT_BYTE_OUTPUT = FALSE HTML_TAG_SUPPORT = true HTML_TAG_FLAG = # HTML_TAG_BINDING_ATTRIBUTE = var NATIVE_CALL = TRUE TEMPLATE_CHARSET = UTF-8 ERROR_HANDLER = org.beetl.core.ConsoleErrorHandler NATIVE_SECUARTY_MANAGER= org.beetl.core.DefaultNativeSecurityManager MVC_STRICT = FALSE #資源配置,resource後的屬性只限於特定ResourceLoader RESOURCE_LOADER=org.beetl.core.resource.ClasspathResourceLoader #classpath 根路徑 #RESOURCE.root=/templates/ #是否檢測檔案變化,開發用true合適,但線上要改為false RESOURCE.autoCheck=true #自定義指令碼方法檔案的Root目錄和字尾 RESOURCE.functionRoot=functions RESOURCE.functionSuffix=html #自定義標籤檔案Root目錄和字尾 RESOURCE.tagRoot=htmltag RESOURCE.tagSuffix=tag ##### 擴充套件 ############## ## 內建的方法 FN.date = org.beetl.ext.fn.DateFunction ##內建的功能包 FNP.strutil = org.beetl.ext.fn.StringUtil ##內建的預設格式化函式 FTC.java.util.Date = org.beetl.ext.format.DateFormat ## 標籤類 TAG.include= org.beetl.ext.tag.IncludeTag
@Configuration //載入配置檔案 public class BeetlConf { @Bean(name = "beetlConfig") public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() { BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration(); ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()); //配置root路徑 try { WebAppResourceLoader webAppResourceLoader = new WebAppResourceLoader(patternResolver.getResource("classpath:/templates/").getFile().getPath()); beetlGroupUtilConfiguration.setResourceLoader(webAppResourceLoader); } catch (IOException e) { e.printStackTrace(); } beetlGroupUtilConfiguration.setConfigFileResource(patternResolver.getResource("classpath:config/beetl.properties")); //獲取SpringBoot的ClassLoader ClassLoader loader = Thread.currentThread().getContextClassLoader(); if(loader==null){ loader = BeetlConf.class.getClassLoader(); } //設定SpringBoot模板路徑路徑 ClasspathResourceLoader cploder = new ClasspathResourceLoader(loader,"/templates/"); beetlGroupUtilConfiguration.setResourceLoader(cploder); beetlGroupUtilConfiguration.init(); //設定Springboot的shiro標籤 GroupTemplate groupTemplate = beetlGroupUtilConfiguration.getGroupTemplate(); groupTemplate.registerFunctionPackage("so", new ShiroExt()); groupTemplate.setClassLoader(loader); return beetlGroupUtilConfiguration; } @Bean(name = "beetlViewResolver") public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) { BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver(); beetlSpringViewResolver.setContentType("text/html;charset=UTF-8"); beetlSpringViewResolver.setSuffix(".html"); beetlSpringViewResolver.setOrder(0); beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration); return beetlSpringViewResolver; } }
//shiro標籤
public class ShiroExt {
/**
* The guest tag
*
* @return
*/
public boolean isGuest() {
return getSubject() == null || getSubject().getPrincipal() == null;
}
/**
* The user tag
*
* @return
*/
public boolean isUser() {
return getSubject() != null && getSubject().getPrincipal() != null;
}
/**
* The authenticated tag
*
* @return
*/
public boolean isAuthenticated() {
return getSubject() != null && getSubject().isAuthenticated();
}
public boolean isNotAuthenticated() {
return !isAuthenticated();
}
/**
* The principal tag
*
* @param map
* @return
*/
public String principal(Map map) {
String strValue = null;
if (getSubject() != null) {
// Get the principal to print out
Object principal;
String type = map != null ? (String) map.get("type") : null;
if (type == null) {
principal = getSubject().getPrincipal();
} else {
principal = getPrincipalFromClassName(type);
}
String property = map != null ? (String) map.get("property") : null;
// Get the string value of the principal
if (principal != null) {
if (property == null) {
strValue = principal.toString();
} else {
strValue = getPrincipalProperty(principal, property);
}
}
}
if (strValue != null) {
return strValue;
} else {
return null;
}
}
/**
* The hasRole tag
*
* @param roleName
* @return
*/
public boolean hasRole(String roleName) {
return getSubject() != null && getSubject().hasRole(roleName);
}
/**
* The lacksRole tag
*
* @param roleName
* @return
*/
public boolean lacksRole(String roleName) {
boolean hasRole = getSubject() != null
&& getSubject().hasRole(roleName);
return !hasRole;
}
/**
* The hasAnyRole tag
*
* @param roleNames
* @return
*/
public boolean hasAnyRole(String roleNames) {
boolean hasAnyRole = false;
Subject subject = getSubject();
if (subject != null) {
// Iterate through roles and check to see if the user has one of the
// roles
for (String role : roleNames.split(",")) {
if (subject.hasRole(role.trim())) {
hasAnyRole = true;
break;
}
}
}
return hasAnyRole;
}
/**
* The hasPermission tag
*
* @param p
* @return
*/
public boolean hasPermission(String p) {
return getSubject() != null && getSubject().isPermitted(p);
}
/**
* The lacksPermission tag
*
* @param p
* @return
*/
public boolean lacksPermission(String p) {
return !hasPermission(p);
}
@SuppressWarnings({ "unchecked" })
private Object getPrincipalFromClassName(String type) {
Object principal = null;
try {
Class cls = Class.forName(type);
principal = getSubject().getPrincipals().oneByType(cls);
} catch (ClassNotFoundException e) {
}
return principal;
}
private String getPrincipalProperty(Object principal, String property) {
String strValue = null;
try {
BeanInfo bi = Introspector.getBeanInfo(principal.getClass());
// Loop through the properties to get the string value of the
// specified property
boolean foundProperty = false;
for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
if (pd.getName().equals(property)) {
Object value = pd.getReadMethod().invoke(principal,
(Object[]) null);
strValue = String.valueOf(value);
foundProperty = true;
break;
}
}
if (!foundProperty) {
final String message = "Property [" + property
+ "] not found in principal of type ["
+ principal.getClass().getName() + "]";
throw new RuntimeException(message);
}
} catch (Exception e) {
final String message = "Error reading property [" + property
+ "] from principal of type ["
+ principal.getClass().getName() + "]";
throw new RuntimeException(message, e);
}
return strValue;
}
protected Subject getSubject() {
return SecurityUtils.getSubject();
}
}
前端頁面示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>首頁 · 後臺模板 HTML</title>
</head>
<body>
${beetl}
@if(so.hasPermission("user:all")){
<a href="/user/online/list">使用者管理</a>
@}
@if(so.hasPermission("role:all")){
<a href="/user/online/list">角色管理</a>
@}
@if(so.hasPermission("permission:all")){
<a href="/user/online/list">許可權管理</a>
@}
<a href="/login/exit">退出</a>
</body>
</html>