Shiro+mybatis+springmvc Instance Record (ii)--shiro support AJAX requests

Source: Internet
Author: User
Tags flush getmessage json xmlns log4j

From the above, the page jump is obviously not suitable for static and dynamic separation of Ajax interaction architecture mode, so the framework needs to be modified to optimize, allowing the background to return JSON data to the front-end request. Custom Interceptors

Shiro the check of permissions, user information is in the default interceptor, to overwrite the way data is returned, you need to rewrite the interceptor. Here we rewrite the authc,perms separately.
Define two interceptors separately, and use PrintWriter to write the JSON string to 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;
            The user login check fails the callback method, or you can override the checksum method isaccessallowed @Override protected Boolean onaccessdenied (ServletRequest request, Servletresponse response) throws Exception {HttpServletRequest httpservletrequest = (httpservletrequest) r
        Equest;

        HttpServletResponse HttpServletResponse = (httpservletresponse) response; Set the encoding format, the header of the Content-type also to set, or the browser will not be UTF8 parsing, or garbled.
Setting Application/json allows JS to use object httpservletresponse.setcharacterencoding ("UTF-8") without eval.        Httpservletresponse.setheader ("Content-type", "application/json;charset=utf-8");
        PrintWriter out;
            try {out = Httpservletresponse.getwriter (); Out.println ("{\" code\ ": -1,\" msg\ ": \" user not logged in.)
            \"}");
            Out.flush ();
        Out.close ();
        } catch (IOException E1) {Log.info (E1.getmessage ());
    } return false; } @Override protected Boolean onloginfailure (Authenticationtoken token, authenticationexception E, Se Rvletrequest request, Servletresponse response) {HttpServletRequest HttpServletRequest = (httpservlet
        request) 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\ ": \" system error \ "}");
            Out.flush ();
        Out.close ();
        } catch (IOException E1) {Log.info (E1.getmessage ());
    } return false; } @Override protected Boolean onloginsuccess (Authenticationtoken token, Subject Subject, Servletreque St request, servletresponse Response) throws Exception {return super.onloginsuccess (token, subject, R
    Equest, 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\ ": \" The logged on user does not have permission to perform the operation.
            \"}");
            Out.flush ();
        Out.close ();
        } catch (IOException E1) {Log.info (E1.getmessage ());
    } return false;
 }
}

Next Configure the custom interceptor in the configuration file
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/c Ontext http://www.springframework.org/schema/context/spring-context-4.0.xsd Http://www.springframework.org/schem   
    A/util http://www.springframework.org/schema/util/spring-util-4.0.xsd "> <!--Shiro Filter Interceptor-related configuration- <bean id= "Shirofilter" class= "Org.apache.shiro.sprinG.web.shirofilterfactorybean "> <!--securitymanager-<property name=" SecurityManager "R ef= "SecurityManager"/> <property name= "loginurl" value= "/login.jsp"/> <property name= "una
                Uthorizedurl "value="/403.jsp "/> <property name=" Filters "> <util:map>
            <entry key= "authc" value-ref= "Loginfilter"/> <entry key= "perms" value-ref= "Authofilter"/> </util:map> </property> <!--filter Chain definition--<property name= "Filterchaind Efinitions "> <value>/data/sysaccount/login*=anon/data/sysaccoun T/**=authc,perms[sysaccount]/data/sysautho/**=authc,perms[sysautho]/data/sysrole/**=auth C,perms[sysrole] </value> </property> </bean> <bean id= "Loginfilte R "class=" Com.testshiro.Filter. Loginfilter "/> <bean id=" Authofilter "class=" Com.testshiro.filter.PermsFilter "/> <!--SecurityManager --<bean id= "SecurityManager" class= "Org.apache.shiro.web.mgt.DefaultWebSecurityManager" > <prop Erty name= "Realm" ref= "Myrealm"/> </bean> <!--custom Realm implementation--<bean id= "Myrealm" class = "Com.testshiro.realm.CustomRealm"/> <bean id= "lifecyclebeanpostprocessor" class= "ORG.APACHE.SHIRO.SPRING.L   Ifecyclebeanpostprocessor "/> </beans>

Start the server.

JS Page part Code

. Ajax ({
                url:xxxx,
                type: "GET",
                success:function (data) {
                    if ("code" in Data&&data.code==-1) {
                        alert (data.msg);
                        return;}}
            )
            ......
Run effect no sign-in situation:


not authorized, POST request condition

Normal situation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.