springboot統合FreeMarkerのテンプレートエンジンbasePathをした後のページの絶対パスを取得

プロジェクト内の静的リソースファイルを参照するか、私たちは時々、実際には、$ {basePathを}を使用AJAX要求することと、これは絶対パスを取得する方法です。


そして、basePahtそれを使用するようにプロジェクトを構成する方法springboot?

最初のステップ:カスタムインターセプタ(HandlerInterceptorを達成)

コード:

パッケージcom.slm.tools.project.config。

輸入org.springframework.web.servlet.HandlerInterceptor。
輸入org.springframework.web.servlet.ModelAndView。

インポートのjavax.servlet.http.HttpServletRequest;
インポートのjavax.servlet.http.HttpServletResponse;

/ **
* @author:SLMによって作成
* @version:v1.0の
* @description:com.slm.tools.project.config
* @date:2019年4月9日
* /
publicクラスのPathInterceptorはHandlerInterceptor {実装
@Override
国民をブールpreHandle(HttpServletRequestのHttpServletRequestを、HttpServletResponseのHttpServletResponseの、オブジェクトo)が例外をスロー{
文字列のパス= httpServletRequest.getContextPath()。
ストリング方式= httpServletRequest.getScheme()。
ストリングサーバ名= httpServletRequest.getServerName()。
int型ポート= httpServletRequest.getServerPort();
文字列basePathを=スキーム+ "://" + serverNameの+ ":" +ポート+パス。
httpServletRequest.setAttribute( "basePathを"、basePathを);
trueを返します。
}

@Override
公共ボイドpostHandle(HttpServletRequestのHttpServletRequestを、HttpServletResponseのHttpServletResponseの、オブジェクトo、のModelAndViewのModelAndViewは){例外をスロー

}

@Override
公共ボイドafterCompletion(HttpServletRequestのHttpServletRequestを、HttpServletResponseのHttpServletResponseの、物体O、例外e)は{例外をスロー

}
}

。1
2
3
4
5
6
7
8
9
10
11
12である
13である
14
15
16
17
18である
19。
20
21である
22である
23である
24
25
26である
27
28
29
30
31であり、
32
33は
34である
35
36
37 [
工程:ステップ登録カスタムインターセプタデバイス

コード:

パッケージcom.slm.tools.project.config。

輸入org.springframework.context.annotation.Configuration。
輸入org.springframework.web.servlet.config.annotation.InterceptorRegistry。
輸入org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter。

/ **
* @author:SLMによって作成
* @version:v1.0の
* @description:com.slm.tools.project.config
* @date:2019年4月9日
* /
@Configuration
パブリッククラスPathInterceptorConfig {WebMvcConfigurerAdapterを拡張
@オーバーライド
公共ボイドaddInterceptors(InterceptorRegistryレジストリ){
registry.addInterceptor(新しい新しいPathInterceptor())addPathPatterns( "/ **")を;.
}
}
。1
2
3
4
5
6
7
8
9
10
11
12である
13である
14
15
16
17
18である
。19
にこの構成であっても、完成し、その後、フロントエンドをテストするためにそれを使用します

ステップ3:テスト
私はAJAXを使用して、ここでテストしました:

関数暗号化(){
VAR TXT = $( "#1 TXT")のval();
$アヤックス({
URL: "$ {basePathを} / MD5 /暗号"、
データ型: "JSON"、
データ:{
TXT:TXT
}、
成功:機能(データを){
。$( "#の16MD5")HTML(データ.MD516);
$( "#1 16MD5Upper")HTML(data.MD516Upper);
$( "#1 32MD5")HTML(data.MD532);
$( "#1 32MD5Upper")HTML(data.MD532Upper);
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
打开页面按F12键观察。

我々は$ {} basePahtで絶対パスを取得する必要があることがわかります。
終了

おすすめ

転載: www.cnblogs.com/exmyth/p/11324824.html