鎷︽埅鍣ㄥ拰杩囨护鍣ㄧ殑鍖哄埆
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了鎷︽埅鍣ㄥ拰杩囨护鍣ㄧ殑鍖哄埆相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/image' title='image'>image
png 鍥剧墖 mamicode action 闈㈠悜 src 渚濊禆 妗嗘灦1.杩囨护鍣細
渚濊禆浜巗ervlet瀹瑰櫒銆傚湪瀹炵幇涓婂熀浜庡嚱鏁板洖璋冿紝鍙互瀵瑰嚑涔庢墍鏈夎姹傝繘琛岃繃婊わ紝浣嗘槸缂虹偣鏄竴涓繃婊ゅ櫒瀹炰緥鍙兘鍦ㄥ鍣ㄥ垵濮嬪寲鏃惰皟鐢ㄤ竴娆°€備娇鐢ㄨ繃婊ゅ櫒鐨勭洰鐨勬槸鐢ㄦ潵鍋氫竴浜涜繃婊ゆ搷浣滐紝鑾峰彇鎴戜滑鎯宠鑾峰彇鐨勬暟鎹紝姣斿锛氬湪杩囨护鍣ㄤ腑淇敼瀛楃缂栫爜锛涘湪杩囨护鍣ㄤ腑淇敼HttpServletRequest鐨勪竴浜涘弬鏁帮紝鍖呮嫭锛氳繃婊や綆淇楁枃瀛椼€佸嵄闄╁瓧绗︾瓑
2.鎷︽埅鍣細
渚濊禆浜巜eb妗嗘灦锛屽湪SpringMVC涓氨鏄緷璧栦簬SpringMVC妗嗘灦銆傚湪瀹炵幇涓婂熀浜?a href="https://link.jianshu.com?t=http%3A%2F%2Fwww.07net01.com%2Ftags-Java-0.html" rel="nofollow" target="_blank">Java鐨勫弽灏勬満鍒讹紝灞炰簬闈㈠悜鍒囬潰缂栫▼锛圓OP锛夌殑涓€绉嶈繍鐢ㄣ€傜敱浜庢嫤鎴櫒鏄熀浜巜eb妗嗘灦鐨勮皟鐢紝鍥犳鍙互浣跨敤Spring鐨勪緷璧栨敞鍏ワ紙DI锛夎繘琛屼竴浜涗笟鍔℃搷浣滐紝鍚屾椂涓€涓嫤鎴櫒瀹炰緥鍦ㄤ竴涓猚ontroller鐢熷懡鍛ㄦ湡涔嬪唴鍙互澶氭璋冪敤銆備絾鏄己鐐规槸鍙兘瀵筩ontroller璇锋眰杩涜鎷︽埅锛屽鍏朵粬鐨勪竴浜涙瘮濡傜洿鎺ヨ闂潤鎬佽祫婧愮殑璇锋眰鍒欐病鍔炴硶杩涜鎷︽埅澶勭悊
3.杩囨护鍣ㄥ拰鎷︽埅鍣ㄧ殑鍖哄埆锛?/p>
鈶犳嫤鎴櫒鏄熀浜巎ava鐨勫弽灏勬満鍒剁殑锛岃€岃繃婊ゅ櫒鏄熀浜庡嚱鏁板洖璋冦€?/strong>
鈶℃嫤鎴櫒涓嶄緷璧栦笌servlet瀹瑰櫒锛岃繃婊ゅ櫒渚濊禆涓巗ervlet瀹瑰櫒銆?/p>
鈶㈡嫤鎴櫒鍙兘瀵筧ction璇锋眰璧蜂綔鐢紝鑰岃繃婊ゅ櫒鍒欏彲浠ュ鍑犱箮鎵€鏈夌殑璇锋眰璧蜂綔鐢ㄣ€?/p>
鈶f嫤鎴櫒鍙互璁块棶action涓婁笅鏂囥€佸€兼爤閲岀殑瀵硅薄锛岃€岃繃婊ゅ櫒涓嶈兘璁块棶銆?/p>
鈶ゅ湪action鐨勭敓鍛藉懆鏈熶腑锛屾嫤鎴櫒鍙互澶氭琚皟鐢紝鑰岃繃婊ゅ櫒鍙兘鍦ㄥ鍣ㄥ垵濮嬪寲鏃惰璋冪敤涓€娆°€?/p>
鈶ユ嫤鎴櫒鍙互鑾峰彇IOC瀹瑰櫒涓殑鍚勪釜bean锛岃€岃繃婊ゅ櫒灏变笉琛岋紝杩欑偣寰堥噸瑕侊紝鍦ㄦ嫤鎴櫒閲屾敞鍏ヤ竴涓猻ervice锛屽彲浠ヨ皟鐢ㄤ笟鍔¢€昏緫銆?/strong>
杩囨护鍣?/strong>
@Override
1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException { 2 3 System.out.println("before..."); 4 5 chain.doFilter(request, response); 6 7 System.out.println("after..."); 8 9 }
chain.doFilter(request, response);杩欎釜鏂规硶鐨勮皟鐢ㄤ綔涓哄垎姘村箔銆備簨瀹炰笂璋冪敤Servlet鐨刣oService()鏂规硶鏄湪chain.doFilter(request, response);杩欎釜鏂规硶涓繘琛岀殑銆?/p>
鎷︽埅鍣?/strong>
鎷︽埅鍣ㄦ槸琚寘瑁瑰湪杩囨护鍣ㄤ箣涓殑銆?/p>
1 @Override 2 3 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception { 4 5 System.out.println("preHandle"); 6 7 returntrue; 8 9 } 10 11 @Override 12 13 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception { 14 15 System.out.println("postHandle"); 16 17 } 18 19 @Override 20 21 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception { 22 23 System.out.println("afterCompletion"); 24 25 }
a.preHandle()杩欎釜鏂规硶鏄湪杩囨护鍣ㄧ殑chain.doFilter(request, response)鏂规硶鐨勫墠涓€姝ユ墽琛岋紝涔熷氨鏄湪 [System.out.println("before...")][chain.doFilter(request, response)]涔嬮棿鎵ц銆?/p>
銆€銆€b.preHandle()鏂规硶涔嬪悗锛屽湪return ModelAndView涔嬪墠杩涜锛屽彲浠ユ搷鎺ontroller鐨凪odelAndView鍐呭銆?/p>
銆€銆€c.afterCompletion()鏂规硶鏄湪杩囨护鍣ㄨ繑鍥炵粰鍓嶇鍓嶄竴姝ユ墽琛岋紝涔熷氨鏄湪[chain.doFilter(request, response)][System.out.println("after...")]涔嬮棿鎵ц銆?/p>
銆€銆€SpringMVC鐨勬満鍒舵槸鐢卞悓涓€涓猄ervlet鏉ュ垎鍙戣姹傜粰涓嶅悓鐨凜ontroller锛屽叾瀹炶繖涓€姝ユ槸鍦⊿ervlet鐨剆ervice()鏂规硶涓墽琛岀殑銆傛墍浠ヨ繃婊ゅ櫒銆佹嫤鎴櫒銆乻ervice()鏂规硶锛宒ispatc()鏂规硶鐨勬墽琛岄『搴忓簲璇ユ槸杩欐牱鐨勶紝澶ц嚧鐢讳簡涓浘锛氬叾瀹為潪甯稿ソ娴嬭瘯锛岃嚜宸卞啓涓€涓繃婊ゅ櫒锛屼竴涓嫤鎴櫒锛岀劧鍚庡湪杩欎簺鏂规硶涓兘鍔犱釜鏂偣锛屼竴璺疐8涓嬪幓灏卞緱鍑轰簡缁撹銆?/p>
以上是关于鎷︽埅鍣ㄥ拰杩囨护鍣ㄧ殑鍖哄埆的主要内容,如果未能解决你的问题,请参考以下文章