freemarker中使用shiro標籤

/**
 * 自定義一個ShiroTagFreeMarkerConfigurer繼承Spring自己提供的FreeMarkerConfigurer,目的是在FreeMarker的Configuration中添加shiro的配置
 * @author q
 *
 */
public class ShiroTagFreeMarkerConfigurer extends FreeMarkerConfigurer{
	@Override
    public void afterPropertiesSet() throws IOException, TemplateException {
        super.afterPropertiesSet();
        this.getConfiguration().setSharedVariable("shiro", new ShiroTags());
    }



修改freemarker在spring配置文件中的配置
<!-- 配置freeMarker的模板路徑 -->  
    <!-- <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">   -->
    <bean id="freemarkerConfig" class="com.ws.config.web.freemarker.ShiroTagFreeMarkerConfigurer">  
<!-- 用自定義的類 替代原生類-->
        <property name="templateLoaderPath">  
            <value>/WEB-INF/ftl/</value>  
        </property>  
        <property name="freemarkerVariables">  
            <map>  
                <entry key="xml_escape" value-ref="fmXmlEscape" />  
            </map>  
        </property>  
        <property name="defaultEncoding">  
            <value>utf-8</value>  
        </property>  
        <property name="freemarkerSettings">  
            <props>  
                <prop key="template_update_delay">5</prop> <!--檢查模板是否更新  秒 --> 
            </props>  
        </property>  
    </bean>



下面具體講講標籤應用,先列出原先的方式,再列出freemarker的方式,網上例舉 比較少
guest標籤
驗證當前用戶是否爲「訪客」,即未認證(包含未記住)的用戶
    <shiro:guest> 
    </shiro:guest> 

freemark中: <@shiro.guest>
    </@shiro.guest>

user標籤
認證經過或已記住的用戶
<shiro:user> 
</shiro:user>

freemark中:
<@shiro.user> 
    </@shiro.user>
authenticated標籤
已認證經過的用戶。不包含已記住的用戶,這是與user標籤的區別所在。
    <shiro:authenticated> 
    </shiro:authenticated> 
freemark中:
<@shiro.authenticated>  
    </@shiro.authenticated>



principal 標籤
輸出當前用戶信息,一般爲登陸賬號信息
    Hello,  <shiro:principal property="name"/>
freemarker中:
  Hello,  <@shiro.principal property="name" />, how are you today? 


hasRole標籤
驗證當前用戶是否屬於該角色
    <shiro:hasRole name="administrator"> 
        Administer the system 
    </shiro:hasRole> 

freemarker中:
<@shiro.hasRole name=」admin」>Hello admin!</@shiro.hasRole>
好了 其餘沒說的 依次類推

還有一個問題 就是 若是默認用shiro登陸後是remember me true的
那麼用戶登陸後 若是此時重啓tomcat  那麼
<@shiro.principal property="name" />仍是有值的

這時候退出按鈕的控制應該用:<@shiro.user> 
      退出     </@shiro.user> 對於必須authc的操做 必須 從新登陸  由於此時 的用戶只是讀取的 remember me(我的理解) 並無經過認證,由於tomcat重啓過了 不知道你們有沒有遇到過該狀況 能夠 研究探討下
相關文章
相關標籤/搜索