In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to solve the problem of Session failure in ajax access. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Recently, due to a project, the module switched to ajax request data. When the Session fails, there is no return value after the ajax request, only the response html:window.open ('http://192.168.0.118:8080/welcomeAction/loginUI.do','_top');
Now that Ajax is widely used in Web projects, it can be said to be ubiquitous, which leads to another problem: what should I do when an Ajax request encounters a session timeout?
Obviously, the traditional page jump is no longer applicable here, because the Ajax request is initiated by the XMLHTTPRequest object, not the browser, and the page jump after validation failure cannot be reflected in the browser, because the information returned (or output) by the server is received by the JavaScript (XMLHTTPRequest object).
So how should we deal with this situation?
Method
Since the message returned by the server is received by the XMLHTTPRequest object, and the XMLHTTPRequest object is under the control of JavaScript, can we use JavaScript to complete the page jump?
Of course you can, and it's easy to achieve! But for one thing, we need to determine whether the HTTP request is an Ajax request (because the AJAX request and the normal request need to be handled separately). How can we tell? In fact, an Ajax request is different from an ordinary HTTP request, which is reflected in the header information of the HTTP request, as shown below:
The above two images are intercepted with Firefox's Firebug, the former is the ordinary HTTP request header information, and the latter is the request header information of the Ajax request. Notice that the first picture is circled in a red box. This is where the Ajax request differs from the normal request. The AJAX request header contains the X-Requested-With message with a value of XMLHttpRequest, which is exactly where we can use it.
Let's take a look at how the code is implemented.
Interceptor filter
When using Struts2, we usually use Interceptor (interceptor) to intercept permission issues.
Interceptor part of the code:
Public String intercept (ActionInvocation invocation) throws Exception {/ / TODO Auto-generated method stub ActionContext ac = invocation.getInvocationContext (); HttpServletRequest request = (HttpServletRequest) ac.get (StrutsStatics.HTTP_REQUEST); String requestType = request.getHeader ("X-Requested-With"); System.out.println ("+ reqestType:" + requestType); HttpServletResponse response = (HttpServletResponse) ac.get (StrutsStatics.HTTP_RESPONSE); / / String basePath = request.getContextPath (); String path = request.getContextPath () String basePath = request.getScheme () + ": / /" + request.getServerName () + ":" + request.getServerPort () + path; / / get session Map session = ac.getSession () / / determine whether session exists and whether the user information in session exists. If there is, there is no need to intercept if (session! = null & & session.get (Constants.FE_SESSION_BG_USER)! = null & & session.get (Constants.FE_SESSION_BG_AUTH)! = null) {System.out.println (invocation.getProxy (). GetActionName () + "+"); System.out.println ("namespace:" + invocation.getProxy (). GetNamespace ()) / / access path String visitURL = invocation.getProxy (). GetNamespace () + "/" + invocation.getProxy (). GetActionName () + Constants.FE_STRUTS_ACTION_EXTENSION; visitURL = visitURL.substring (1); Map authMap = (Map) session.get (Constants.FE_SESSION_BG_AUTH); Map actionMap = (Map) authMap.get (Constants.FE_BG_ACTIONMAP) If (actionMap! = null & &! actionMap.isEmpty () & & visitURL! = null) {if (actionMap.containsValue (visitURL)) {System.out.println (visitURL+ "- -"); return invocation.invoke ();} else {String forbidden = basePath + Constants.FE_BG_FORBIDDEN; response.sendRedirect (forbidden) Return null;}} return invocation.invoke ();} else {if (StringUtils.isNotBlank (requestType) & & requestType.equalsIgnoreCase ("XMLHttpRequest")) {response.setHeader ("sessionstatus", "timeout"); response.sendError (518, "session timeout."); return null;} else {String actionName = invocation.getProxy (). GetActionName () System.out.println (actionName); / / if the intercepted actionName is loginUI or login, no processing will be done, otherwise redirect to the login page if (StringUtils.isNotBlank (actionName) & & actionName.equals (Constants.FE_BG_LOGINUI)) {return invocation.invoke ();} else if (StringUtils.isNotBlank (actionName) & & actionName.equals (Constants.FE_BG_LOGIN)) {return invocation.invoke () } else {String login = basePath + "/" + Constants.FE_BG_LOGIN_NAMESPACE + "/" + Constants.FE_BG_LOGINUI + Constants.FE_STRUTS_ACTION_EXTENSION;// System.out.println ("+ + basePath:" + basePath); / / response.sendRedirect (login); PrintWriter out = response.getWriter (); / / out.println ("); / / out.println (") / / out.println ("window.open ('" + login+ "','_ top');"); / / out.println ("); / / out.println ("); out.write ("window.open ('" + login+ "','_ top');"); return null;}
As can be seen from the above code, when Session verification fails (that is, Session timeout), we get the value of the request header information X-Requested-With through HttpServletRequest. If it is not empty and equal to XMLHttpRequest, then the request is an Ajax request. Our response is to add a header message to the response (custom) and make the response object HttpServletResponse return server error information (the status is defined casually by ourselves) All this information will be received by JavaScript, so the following work will be done by JavaScript code.
Javascript code
The .ajaxSetup method is used to set the default options for AJAX requests, which we can think of as global option settings, so we can refer this code to the external JS file and reference it on the page as needed.
/ * set default options for future (global) AJAX requests * mainly set AJAX requests when Session expires * / $.ajaxSetup ({type: 'POST', complete: function (xhr,status) {var sessionStatus = xhr.getResponseHeader (' sessionstatus'); if (sessionStatus = = 'timeout') {var top = getTopWinow () Var yes = confirm ('because you have not operated for a long time, session has expired, please log in again.'); if (yes) {top.location.href ='/ skynk/index.html';}) / * get the top-level window object of the current page * @ return from any nested hierarchical window on the page * / function getTopWinow () {var p = window; while (p! = p.parent) {p = p.parent;} return p } this is the end of the article on "how to solve the problem of Session failure in ajax access". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.