接上文,頁面跳轉顯然不適合動靜分離ajax互動的架構模式,因此就需要對架構進行改造最佳化,使得後台能夠返回json資料給前端請求。 自訂攔截器
shiro對許可權、使用者資訊的校正實在預設的攔截器中進行的,要改寫資料返回方式,則需要重寫攔截器。這裡我們分別對authc,perms進行重寫。
分別定義兩個攔截器,並使用printWriter將json字串寫入response中。
LoginFilter
package com.testshiro.filter;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;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; //使用者登入校正失敗回調方法,也可以自己重寫校正方法isAccessAllowed @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; //設定編碼格式,header的content-type也要設定,否則瀏覽器不會以utf8解析,還是亂碼。設定application/json可以讓js不需要eval即可使用對象 httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8"); PrintWriter out; try { out = httpServletResponse.getWriter(); out.println("{\"code\":-1,\"msg\":\"未登入使用者。\"}"); out.flush(); out.close(); } catch (IOException e1) { log.info(e1.getMessage()); } return false; } @Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8"); PrintWriter out; try { out = httpServletResponse.getWriter(); out.println("{\"code\":-1,\"msg\":\"系統錯誤\"}"); out.flush(); out.close(); } catch (IOException e1) { log.info(e1.getMessage()); } return false; } @Override protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { return super.onLoginSuccess(token, subject, request, response); } private final static Logger log = Logger.getLogger(LoginFilter.class);}
PermsFilter
package com.testshiro.filter;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.subject.Subject;import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;public class PermsFilter extends PermissionsAuthorizationFilter { private final static Logger log = Logger.getLogger(PermsFilter.class); @Override protected boolean onAccessDenied(ServletRequest arg0, ServletResponse arg1) throws IOException { HttpServletRequest httpServletRequest = (HttpServletRequest) arg0; HttpServletResponse httpServletResponse = (HttpServletResponse) arg1; httpServletResponse.setCharacterEncoding("UTF-8"); httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8"); PrintWriter out; try { out = httpServletResponse.getWriter(); out.println("{\"code\":-1,\"msg\":\"登入使用者無權執行該操作。\"}"); out.flush(); out.close(); } catch (IOException e1) { log.info(e1.getMessage()); } return false; }}
接下來在設定檔中配置自訂攔截器
spring-shiro.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd" > <!-- Shiro Filter 攔截器相關配置 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- securityManager --> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="unauthorizedUrl" value="/403.jsp" /> <property name="filters"> <util:map> <entry key="authc" value-ref="loginFilter"/> <entry key="perms" value-ref="authoFilter"/> </util:map> </property> <!-- 過濾鏈定義 --> <property name="filterChainDefinitions"> <value> /data/sysaccount/login*=anon /data/sysaccount/**=authc,perms[sysAccount] /data/sysautho/**=authc,perms[sysAutho] /data/sysrole/**=authc,perms[sysRole] </value> </property> </bean> <bean id="loginFilter" class="com.testshiro.filter.LoginFilter"/> <bean id="authoFilter" class="com.testshiro.filter.PermsFilter"/> <!-- securityManager --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm" /> </bean> <!-- 自訂Realm實現 --> <bean id="myRealm" class="com.testshiro.realm.CustomRealm" /> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /></beans>
啟動伺服器即可。
js頁面部分代碼
.ajax({ url : xxxx, type : "GET", success : function(data) { if("code" in data&&data.code==-1){ alert(data.msg); return; } } }) ......
運行效果
未登入情況:
未授權,post請求情況
正常情況