shiro+mybatis+springmvc執行個體記錄(二)——shiro支援ajax請求

來源:互聯網
上載者:User

接上文,頁面跳轉顯然不適合動靜分離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請求情況

正常情況

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.