Strut2 to determine whether Ajax calls
1. Ajax and traditional form forms
in fact, both are typically via HTTP POST requests. The difference is that when the browser submits form forms, it expects the server to return a full HTML page. While Ajax calls are made by XMLHttpRequest objects (different browsers may not be the same), browsers expect the server to return HTML fragments, specifically JSON, XML, and so on. Returns to the browser how to use, is also determined by the JS script itself.
2. Request is not Ajax
so on the server side, how can you tell if an HTTP request is an AJAX call? This requires a look at the header of HTTP.
&NBSP
We can judge by the X-request-with in the header. Although different browsers send AJAX requests with different objects, if you use jquery to send AJAX requests, the identity is already added to jquery when implementing Ajax internally. The jquery source is this: Xhr.setrequestheader ("X-requested-with", "XMLHttpRequest");
So, if the foreground page of the project is to send Ajax requests through jquery, it is safe to judge.
&NBSP
Below is the header information that is carried by the HTTP request.
Normal form form submission
===mimeheaders = =
Accept = */*
referer =http://localhost:8080/user2/toquerypage.action
Accept-language = zh-cn
user-agent = mozilla/4.0 (compatible; MSIE8.0; Windows NT 6.1; WOW64; trident/4.0; SLCC2. NET CLR 2.0.50727;. NET CLR3.5.30729;. NET CLR 3.0.30729; Media Center PC 6.0; infopath.3;. net4.0c;. net4.0e)
accept-encoding = gzip, deflate
host = localhost:8080
connection = keep-alive Cache-control
= No-cache
Ajax Calls (IE)
===mimeheaders = =
X-requested-with = XMLHttpRequest
accept-language = ZH-CN
referer : 8080/user2/toquerypage.action
Accept = Application/json, text/javascript,*/* q=0.01
content-type = application/x-www-form-urlencoded
accept-encoding = gzip, deflate
user-agent = mozilla/4.0 (compatible; MSIE8.0; Windows NT 6.1; WOW64; trident/4.0; SLCC2. NET CLR 2.0.50727;. NET CLR3.5.30729;. NET CLR 3.0.30729; Media Center PC 6.0; infopath.3;. net4.0c;. NET4.0E)
host = localhost:8080
content-length =
connection = keep-alive Cache-control
= No-cache
3. Get HTTP request headers in action
in the action class, we get the HttpServletRequest object through the Servletrequestaware interface, and then we get the header information we want through the GetHeader method.
public abstract class Baseaction <PARAMVO extends Baseparamvo, Resultvo extends Baseresultvo> extends Actionsupport implements Servletrequestaware {private static final String
Ajax_result_name = "Ajaxresult";
private static final String Xhr_object_name = "XMLHttpRequest";
private static final String Header_request_with = "X-requested-with";
/** * Request object, used to determine whether the requested Ajax call/private httpservletrequest request;
Private PARAMVO Paramvo;
Private Resultvo Resultvo;
@Override public String Execute () {string resultpage = SUCCESS;
try {resultvo = Doexecute (PARAMVO);
catch (Baseexception e) {resultpage = ERROR;
} if (Xhr_object_name.equals (Request.getheader (Header_request_with)) {resultpage = Ajax_result_name;
return resultpage; }
}
STRUTS2 Performance Tuning Interceptor
when we need to implement some small requirements in our work, we should do a simple research to see if the open source framework we are using has the functionality we need so that we don't have to reinvent the wheel.
Let's take a performance test for example to find out how to investigate whether the STRUTS2 framework has this functionality.
1. Struts-default.xml
Because many of the core features of Struts2 are based on internal interceptors, we first need to see if it has a performance tuning associated interceptor. This requires viewing the default profile Struts-default.xml in Strut2-core-2.3.1.2.jar.
<span style= "White-space:pre" > </span><interceptor name= "Alias" class= " Com.opensymphony.xwork2.interceptor.AliasInterceptor "/> <interceptor name=" autowiring "class=" Com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor "/> <interceptor name=" Chain "class=" Com.opensymphony.xwork2.interceptor.ChainingInterceptor "/> <interceptor name=" Conversionerror "class=" Org.apache.struts2.interceptor.StrutsConversionErrorInterceptor "/> <interceptor name=" Cookie "class=" Org.apache.struts2.interceptor.CookieInterceptor "/> <interceptor name=" clearsession "class=" Org.apache.struts2.interceptor.ClearSessionInterceptor "/> <interceptor name=" createsession "class=" Org.apac He.struts2.interceptor.CreateSessionInterceptor "/> <interceptor name=" debugging "class=" org.apache.struts2. Interceptor.debugging.DebuggingInterceptor "/> <interceptor name=" execandwait "class=" Org.apache.Struts2.interceptor.ExecuteAndWaitInterceptor "/> <interceptornameinterceptorname=" Exception "class=" Com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor "/> <interceptor name=" FileUpload "class=" Org.apache.struts2.interceptor.FileUploadInterceptor "/> <interceptor name=" i18n "class=" Com.opensymphony.xwork2.interceptor.I18nInterceptor "/> <interceptor name=" Logger "class=" Com.opensymphony.xwork2.interceptor.LoggingInterceptor "/> <interceptor name=" Modeldriven "class=" Com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor "/> <interceptor name=" Scopedmodeldriven "class=" Com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor "/> <interceptor name=" params "class=" Com.opensymphony.xwork2.interceptor.ParametersInterceptor "/> <interceptor name=" Actionmappingparams "class=" "Org.apache.struts2.interceptor.ActionMappingParametersInteceptor"/> <interceptor name= "Prepare "class=" Com.opensymphony.xwork2.interceptor.PrepareInterceptor "/> <interceptor name=" Staticparams "C lass= "Com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/> <interceptor name= "Scope" class= " Org.apache.struts2.interceptor.ScopeInterceptor "/> <interceptor name=" ServletConfig "class=" Org.apache.struts2.interceptor.ServletConfigInterceptor "/> <interceptor name=" Timer "class=" Com.opensymphony.xwork2.interceptor.TimerInterceptor "/> <interceptor name=" token "class=" org.apache.struts2 . Interceptor. Tokeninterceptor "/> <interceptor name=" tokensession "class=" Org.apache.struts2.interceptor.TokenSessionStoreInterceptor "/> <interceptor name=" Validation "class=" Org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor "/> <interceptor name=" Workflow " class= "Com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/> <interceptor name= "Store" class= "Org.apache.struts2.interceptor.MessageStoreInterceptor"/> <interceptor name= "checkbox" class= "Org.ap Ache.struts2.interceptor.CheckboxInterceptor "/> <interceptor name=" profiling "class=" Org.apache.struts2.int Erceptor. Profilingactivationinterceptor "/> <interceptor name=" Roles "class=" Org.apache.struts2.interceptor.RolesInte Rceptor "/> <interceptor name=" Annotationworkflow "class=" com.opensymphony.xwork2.interceptor.annotations.An Notationworkflowinterceptor "/> <interceptor name=" MultiSelect "class=" Org.apache.struts2.interceptor.Multis
Electinterceptor "/>
Struts2 like a visionary built a lot of interceptors, you can see that profiling is likely to meet our needs interceptor, then open the source of a probe.
2. Profilingactivationinterceptor
Org.apache.struts2.interceptor.ProfilingActivationInterceptor.java
public class Profilingactivationinterceptor Extendsabstractinterceptor {private S
Tring Profilingkey = "Profiling";
Private Boolean DevMode;
@Inject (strutsconstants.struts_devmode) public void Setdevmode (String mode) {This.devmode = "true". Equals (mode);
@Override public String Intercept (actioninvocationinvocation) throws Exception {if (DevMode) {
Object Val =invocation.getinvocationcontext () getparameters (). get (Profilingkey); if (val!= null) {string sval = (val instanceof string?
String) Val: ((string[]) val) [0]); Boolean enable = "Yes". Equalsignorecase (sval) | |
"True". Equalsignorecase (Sval);
Utiltimerstack.setactive (enable);
Invocation.getinvocationcontext (). GetParameters (). Remove (Profilingkey);
} return Invocation.invoke (); }
}
From the source can be seen, as long as the browser sent over the HTTP request parameters include Profiling=true or Yes, the performance interceptor will open the Timer tool class, print out the execution of the action consumption time.
3. Struts.xml
Because the profiling interceptor is not included in the default Defaultstack, we first append it to our custom interceptor stack.
<package name= "Ajax-default" extends= "Velocity-default" > <result-types> <result-type name= "JSON" class= "Org.apache.struts2.json.JSONResult"/> </result-types> & lt;interceptors> <interceptor-stacknameinterceptor-stackname= "Ajaxinterceptorstack" > <intercepto R-refnameinterceptor-refname= "Defaultstack"/> <interceptor-ref name= "profiling"/> </interceptor -stack> </interceptors> <default-interceptor-refnamedefault-interceptor-refname= "ajaxintercept Orstack "/> <global-results> <result name=" Comajaxresult "type=" JSON "> <param Name= "Excludenullproperties" >true</param> <param name= "root" >result</param> <pa
Ram Name= "Ignorehierarchy" >false</param> </result> </global-results> </package>
4. Userview.js
You can now modify the Ajax invocation parameters, and you can begin performance tuning by appending the profiling parameter.
function Searchalluser () {
Jquery.ajax ({
type: Post),
URL: "Searchalluser.action",
processdata: True,
dataType: ' json ',
data:jquery (' #userQueryForm '). Serialize () + "&profiling=yes",
success: function (data) {
if (Data.status = 1) {
alert ("Create success");
Generatetablefromjson ("result", data.resultrows);
} else {
alert ("Create Failed");}}
);
5. Final effect
The print result is the following. In addition to the total execution time, the execution time of the action method and the rendering time of the result are listed separately.