ホームページ Java &#&チュートリアル Java の Struts で AJAX を呼び出し、インターセプターを使用して最適化するかどうかを決定します。

Java の Struts で AJAX を呼び出し、インターセプターを使用して最適化するかどうかを決定します。

Jan 09, 2017 pm 02:22 PM

Strut2 は、AJAX 呼び出しであるかどうかを決定します
1. AJAX と従来のフォーム フォーム
実際には、どちらも通常、HTTP を介した POST リクエストです。違いは、ブラウザがフォームを送信した後、サーバーが完全な HTML ページを返すことを期待していることです。 AJAX 呼び出しは XMLHttpRequest オブジェクトによって発行されます (ブラウザーによって異なる場合があります)。特に、JSON、XML などの要件はありません。ブラウザに戻った後の使い方もJSスクリプト自体によって決まります。

2. リクエストが AJAX かどうか
それでは、サーバー側では、HTTP リクエストが AJAX 呼び出しであるかどうかを判断するにはどうすればよいでしょうか?これには、HTTP ヘッダーを確認する必要があります。

ヘッダーのx-request-withで判断できます。ブラウザーによって AJAX リクエストが異なるオブジェクトに送信されますが、AJAX リクエストの送信に jQuery が使用されている場合、jQuery が内部的に ajax を実装するときに識別子が追加されます。 jQuery のソース コードは次のようになります: xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
したがって、プロジェクトのフロントエンド ページが jQuery を通じて AJAX リクエストを送信する場合、この判断は安全です。

以下は、HTTP リクエストによって伝送されるヘッダー情報です。

通常のフォーム送信

===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 呼び出し (IE)

===MimeHeaders ===
x-requested-with = XMLHttpRequest
accept-language = zh-cn
referer =http://localhost: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 = 57
connection = Keep-Alive
cache-control = no-cache
ログイン後にコピー


3. Action で HTTP リクエスト ヘッダーを取得します
Action クラスで、ServletRequestAware インターフェイスを介して HttpServletRequest オブジェクトを取得し、処理を完了します。 getHeader メソッド 必要なヘッダー情報。

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对象,用来判断请求是否是AJAX调用
   */
  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 パフォーマンス チューニング インターセプター
仕事でいくつかの小さな要件を実装する必要がある場合、最初に簡単な調査を行って、使用しているオープンソース フレームワークに必要な機能が既にあるかどうかを確認するとよいでしょう。車輪を再発明する必要はありません。
パフォーマンス テストを例として、Struts2 フレームワークにこの機能があるかどうかを調査する方法を見てみましょう。

1. struts-default.xml

Struts2 の多くのコア機能は内部インターセプターに基づいて実装されているため、最初にパフォーマンス チューニングに関連するインターセプターがあるかどうかを確認する必要があります。これには、strut2-core-2.3.1.2.jar 内のデフォルト構成ファイル struts-default.xml を確認する必要があります。

<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.apache.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" class="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.apache.struts2.interceptor.CheckboxInterceptor" />
      <interceptor name="profiling" class="org.apache.struts2.interceptor.ProfilingActivationInterceptor" />
      <interceptor name="roles" class="org.apache.struts2.interceptor.RolesInterceptor" />
      <interceptor name="annotationWorkflow" class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor" />
      <interceptor name="multiselect" class="org.apache.struts2.interceptor.MultiselectInterceptor" />
ログイン後にコピー

Struts2 は、多くのインターセプターが組み込まれた宝箱のようなものです。プロファイリングがおそらく私たちのニーズを満たすインターセプターであることがわかります。それでは、ソース コードを開いて確認してください。

2. ProfilingActivationInterceptor

org.apache.struts2.interceptor.ProfilingActivationInterceptor.java

public class ProfilingActivationInterceptor extendsAbstractInterceptor {
   
  private String 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();
   
  }
   
}
ログイン後にコピー


ブラウザによって送信された HTTP リクエストパラメータに profiling=true が含まれている限りまたははい。パフォーマンス インターセプターはタイマー ツール クラスを開き、アクションの実行時間を出力します。

3. struts.xml

プロファイリング インターセプターはデフォルトの defaultStack に含まれていないため、最初にカスタム インターセプター スタックに追加する必要があります。

<package name="ajax-default" extends="velocity-default">
    <result-types>
      <result-type name="json" class="org.apache.struts2.json.JSONResult"/>
    </result-types>
      
    <interceptors>
      <interceptor-stacknameinterceptor-stackname="ajaxInterceptorStack">
      <interceptor-refnameinterceptor-refname="defaultStack" />
      <interceptor-ref name="profiling"/>
      </interceptor-stack>
    </interceptors>
      
    <default-interceptor-refnamedefault-interceptor-refname="ajaxInterceptorStack" />
      
    <global-results>
      <result name="comAjaxResult" type="json">
        <param name="excludeNullProperties">true</param>
        <param name="root">result</param>
        <param name="ignoreHierarchy">false</param>
      </result>
    </global-results>
  </package>
ログイン後にコピー

4. userview.js

これで、AJAX 呼び出しパラメーターを変更し、プロファイリング パラメーターを追加して、パフォーマンス チューニングを開始できます。

function searchAllUser(){
  jQuery.ajax({
    type:"post",
    url: "searchAllUser.action",
    processData:true,
    dataType:&#39;json&#39;,
    data:jQuery("#userQueryForm").serialize() + "&profiling=yes",
    success:function(data) {
    if (data.status == 1) {
       alert("创建成功");
       generateTableFromJson("result", data.resultRows);
    } else {
       alert("创建失败");
    }
    }
  });
}
ログイン後にコピー


5. 最終的な効果

印刷結果は以下の通りです。合計実行時間に加えて、Action メソッドの実行時間と Result のレンダリング時間が個別にリストされます。

Java の Struts で AJAX を呼び出し、インターセプターを使用して最適化するかどうかを決定します。


Java の Struts で AJAX を呼び出すかどうかの決定とインターセプターを使用した最適化に関するその他の関連記事については、PHP 中国語 Web サイトに注目してください。


このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

会社のセキュリティソフトウェアはアプリケーションの実行に失敗していますか?それをトラブルシューティングと解決する方法は? 会社のセキュリティソフトウェアはアプリケーションの実行に失敗していますか?それをトラブルシューティングと解決する方法は? Apr 19, 2025 pm 04:51 PM

一部のアプリケーションが適切に機能しないようにする会社のセキュリティソフトウェアのトラブルシューティングとソリューション。多くの企業は、内部ネットワークセキュリティを確保するためにセキュリティソフトウェアを展開します。 ...

MapsTructを使用したシステムドッキングのフィールドマッピングの問題を簡素化する方法は? MapsTructを使用したシステムドッキングのフィールドマッピングの問題を簡素化する方法は? Apr 19, 2025 pm 06:21 PM

システムドッキングでのフィールドマッピング処理は、システムドッキングを実行する際に難しい問題に遭遇することがよくあります。システムのインターフェイスフィールドを効果的にマッピングする方法A ...

エンティティクラス変数名をエレガントに取得して、データベースクエリ条件を構築する方法は? エンティティクラス変数名をエレガントに取得して、データベースクエリ条件を構築する方法は? Apr 19, 2025 pm 11:42 PM

データベース操作にMyBatis-Plusまたはその他のORMフレームワークを使用する場合、エンティティクラスの属性名に基づいてクエリ条件を構築する必要があることがよくあります。あなたが毎回手動で...

Intellijのアイデアは、ログを出力せずにSpring Bootプロジェクトのポート番号をどのように識別しますか? Intellijのアイデアは、ログを出力せずにSpring Bootプロジェクトのポート番号をどのように識別しますか? Apr 19, 2025 pm 11:45 PM

intellijideaultimatiateバージョンを使用してスプリングを開始します...

名前を数値に変換してソートを実装し、グループの一貫性を維持するにはどうすればよいですか? 名前を数値に変換してソートを実装し、グループの一貫性を維持するにはどうすればよいですか? Apr 19, 2025 pm 11:30 PM

多くのアプリケーションシナリオでソートを実装するために名前を数値に変換するソリューションでは、ユーザーはグループ、特に1つでソートする必要がある場合があります...

Javaオブジェクトを配列に安全に変換する方法は? Javaオブジェクトを配列に安全に変換する方法は? Apr 19, 2025 pm 11:33 PM

Javaオブジェクトと配列の変換:リスクの詳細な議論と鋳造タイプ変換の正しい方法多くのJava初心者は、オブジェクトのアレイへの変換に遭遇します...

データベースクエリにTKMYBATISを使用するときに、エンティティクラスの変数名の構築クエリ条件をエレガントに取得する方法は? データベースクエリにTKMYBATISを使用するときに、エンティティクラスの変数名の構築クエリ条件をエレガントに取得する方法は? Apr 19, 2025 pm 09:51 PM

データベースクエリにTKMYBATISを使用する場合、クエリ条件を構築するためにエンティティクラスの変数名を優雅に取得する方法は一般的な問題です。この記事はピン留めします...

Redisキャッシュソリューションを使用して、製品ランキングリストの要件を効率的に実現する方法は? Redisキャッシュソリューションを使用して、製品ランキングリストの要件を効率的に実現する方法は? Apr 19, 2025 pm 11:36 PM

Redisキャッシュソリューションは、製品ランキングリストの要件をどのように実現しますか?開発プロセス中に、多くの場合、ランキングの要件に対処する必要があります。

See all articles