浣滆咃細niumd錛岃漿杞借娉ㄦ槑鍑哄錛岃阿璋?nbsp;
鍙戣〃鏃墮棿錛?010 騫?nbsp;03 鏈?nbsp;17 鏃?nbsp;
鍘熸枃閾炬帴錛?a mce_href="/admin/blogs/618449">http://ari.iteye.com/admin/blogs/618449
涓銆丼pring JDBC 姒傝堪
Spring 鎻愪緵浜嗕竴涓己鏈夊姏鐨勬ā鏉跨被JdbcTemplate綆鍖朖DBC鎿嶄綔錛孌ataSource,JdbcTemplate閮藉彲浠ヤ互Bean鐨勬柟寮忓畾涔夊湪鎯硏ml閰嶇疆鏂囦歡錛孞dbcTemplate鍒涘緩鍙渶娉ㄥ叆涓涓狣ataSource錛屽簲鐢ㄧ▼搴廌ao灞傚彧闇瑕佺戶鎵縅dbcDaoSupport, 鎴栬呮敞鍏dbcTemplate錛屼究鍙互鑾峰彇JdbcTemplate錛孞dbcTemplate鏄竴涓嚎紼嬪畨鍏ㄧ殑綾伙紝澶氫釜Dao鍙互娉ㄥ叆涓涓狫dbcTemplate錛?/p>
<!-- Oracle鏁版嵁婧? --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@oracle.devcake.co.uk:1521:INTL"/> <property name="username" value="sa"/> <property name="password" value=""/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!-- set娉ㄥ叆鏂瑰紡鑾峰彇jdbcTemplate --> <bean id="customerDao" class="JdbcCustomerDao" > <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> <!-- 娉ㄥ叆dataSource錛宑ustomerDao閫氳繃緇ф壙JdbcDaoSupport ,浣跨敤this.getJdbcTemplate()鑾峰彇JdbcTemplate --> <bean id="customerDao" class="JdbcCustomerDao" > <property name="dataSource" ref="dataSource"/> </bean>
鐒跺悗灝唈dbcTemplate瀵硅薄娉ㄥ叆鑷畾涔夌殑Dao銆佹垨鑰呯戶鎵縅dbcDaoSupport錛屼緥濡傦細
public class JdbcCustomerDao extends JdbcDaoSupport implements CustomerDao { } public class JdbcCustomerDao implements CustomerDao { private JdbcTemplate jdbcTemplate public void setJdbcTemplate()JdbcTemplate jdbcTemplate{ this.jdbcTemplate=jdbcTemplate } }
浜屻?nbsp;JdbcTemplate 鎻愪緵浠ヤ笅涓昏鏂規硶綆鍖朖DBC鎿嶄綔錛?/strong>
2.1銆丩ist query(String sql,Ojbect[] args,RowMapper rowMapper)
璇存槑錛氬父鐢ㄧ殑鏌ヨ錛宻ql寰呮墽琛岀殑sql璇彞錛宎rgs鏄痵ql璇彞鐨勫弬鏁幫紝rowMapper璐熻矗灝嗘瘡涓琛岃褰曡漿鍖栦負java瀵硅薄瀛樻斁鍦╨ist錛屽茍鏈緇堣繑鍥烇紝渚嬪錛?/p>
public List<Book> queryByAuthor(String author) { String sql = "select * from book where author=?"; Collection c = getJdoTemplate().find(sql, new Object[] { author },new BookRowMapper()); List<Book> books = new ArrayList<Book>(); books.addAll(c); return books; } class BookRowMapper implements RowMapper{ public Object mapRow(ResultSet res, int index) throws SQLException { Book book = new Book(); book.setId(rs.getInt("id")); //鐪佺暐set return book錛? } }
鏇存柊銆佸垹闄ゃ佸叾浠栨煡璇㈡搷浣滅被浼鹼紝涓句緥濡備笅錛岃緇嗙粏鑺傝鍙傝僺pring api錛?/p>
//榪斿洖鍊間負涓涓暱鏁村艦 public long getAverageAge() { return getJdbcTemplate().queryForLong("SELECT AVG(age) FROM employee"); } //榪斿洖涓涓暣鏁? public int getTotalNumberOfEmployees() { return getJdbcTemplate().queryForInt("SELECT COUNT(0) FROM employees"); } //鏇存柊鎿嶄綔 this.jdbcTemplate.update( "insert into t_actor (first_name, surname) values (?, ?)", new Object[] {"Leonor", "Watling"});
2.2銆乻pring 2.5鏂板姛鑳斤紝鍙︾被鐨刯dbc ORM錛欱eanPropertyRowMapper
涓婇潰鎴戜滑媯绱㈡椂蹇呴』瀹炵幇RowMapper錛屽皢緇撴灉闆嗚漿鍖栦負java瀵硅薄銆係pring2.5 綆鍖栦簡榪欎竴鎿嶄綔錛屼嬌寰楁垜浠笉蹇呭啀瀹炵幇RowMapper錛屽疄鐜版鍔熻兘鐨勪咯涓濂囦笢涓滀究鏄細ParameterizedRowMapper錛孭arameterizedBeanPropertyRowMapper錛岃矊浼奸氳繃java鍙嶅皠鏈哄埗瀹炵幇浜嗗皢resultset瀛楁鏄犲皠鍒癹ava瀵硅薄錛屼絾鏄暟鎹〃鐨勫垪蹇呴』鍜宩ava瀵硅薄鐨勫睘鎬у搴旓紝娌℃湁鐮旂┒婧愮爜錛屾湁鐐圭被浼間簬apache 鐨凚eanUtil錛屼笉鐭ヤ負浣曡繖閮ㄥ垎鍦╯pring寮鍙戝弬鑰冩墜鍐屾病鏈夛紝闅鵑亾涓嶆槸緇忓吀銆?/p>
//浣跨敤ParameterizedBeanPropertyRowMapper @SuppressWarnings({"unchecked"}) public List<Customer> getAll() { return getJdbcTemplate().query("select * from t_customer", ParameterizedBeanPropertyRowMapper.newInstance(Customer.class)); } //浣跨敤BeanPropertyRowMapper @SuppressWarnings({"unchecked"}) public List<Customer> getAll() { return getJdbcTemplate().query("select * from t_customer", new BeanPropertyRowMapper(Customer.class)); }
娉ㄦ剰錛歅arameterizedBeanPropertyRowMapper鏄疊eanPropertyRowMapper瀛愮被銆傚彟澶栬〃鐨勫瓧孌靛悕縐板繀欏誨拰瀹炰綋綾葷殑鎴愬憳鍙橀噺鍚嶇О涓鑷達紱
2.3銆乻pring涔婮DBC鎵歸噺鎿嶄綔
jdbcTemplate.batchUpdate(final String[] sql) 錛孉PI瑙i噴錛欼ssue multiple SQL updates on a single JDBC Statement using batching錛岀炕璇戣繃鏉ュぇ鑷翠負錛氳В鍐沖涓猻ql鐨勬彃鍏ャ佹洿鏂般佸垹闄ゆ搷浣滃湪涓涓猄tatement涓傛ц兘涓鑸?/span>
jdbcTemplate.batchUpdate(String sql, final BatchPreparedStatementSetter pss),綾諱技浜嶫DBC鐨凱reparedStatement錛屾ц兘杈冧笂鐫鏈夋墍鎻愰珮銆?/span>
鎴戜滑涓句緥璇存槑濡備綍浣跨敤錛岀ず渚嬪涓?
final int count = 2000; final List<String> firstNames = new ArrayList<String>(count); final List<String> lastNames = new ArrayList<String>(count); for (int i = 0; i < count; i++) { firstNames.add("First Name " + i); lastNames.add("Last Name " + i); } jdbcTemplate.batchUpdate( "insert into customer (id, first_name, last_name, last_login, comments) values (?, ?, ?, ?, ?)", new BatchPreparedStatementSetter() { //涓簆repared statement璁劇疆鍙傛暟銆傝繖涓柟娉曞皢鍦ㄦ暣涓繃紼嬩腑琚皟鐢ㄧ殑嬈℃暟 public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setLong(1, i + 10); ps.setString(2, firstNames.get(i)); ps.setString(3, lastNames.get(i)); ps.setNull(4, Types.TIMESTAMP); ps.setNull(5, Types.CLOB); } //榪斿洖鏇存柊鐨勭粨鏋滈泦鏉℃暟 public int getBatchSize() { return count; } }); }
BatchSqlUpdate綾繪槸SqlUpdate 鐨勫瓙綾伙紝閫傜敤浜庢彃鍏ャ佸垹闄ゃ佹洿鏂版壒閲忔搷浣滐紝鍐呴儴浣跨敤PreparedStatement錛屾墍浠ユ晥鐜囧緢楂橈紝鎵歸噺璇彞杈懼埌璁懼畾鐨刡atchSize錛屾垨鑰呮墜鍔ㄨ皟鐢╢lush鎵嶄細鎵ц鎵歸噺鎿嶄綔銆傛敞鎰忥細姝ょ被鏄潪綰跨▼瀹夊叏鐨勶紝蹇呴』涓烘瘡涓嬌鐢ㄨ呭垱寤轟竴涓疄渚嬶紝鎴栬呭湪鍚屼竴涓嚎紼嬩腑浣跨敤鍓嶈皟鐢╮eset銆?/span>
涓嬮潰鎴戜滑涓句緥璇存槑濡備綍浣跨敤BatchSqlUpdate錛屾潵鎵ц鎵歸噺鎿嶄綔銆傜ず渚嬪涓嬶細
class BatchInsert extends BatchSqlUpdate { private static final String SQL = "insert into t_customer (id, first_name, last_name, last_login, " + "comments) values (?, ?, ?, ?, null)"; BatchInsert(DataSource dataSource) { super(dataSource, SQL); declareParameter(new SqlParameter(Types.INTEGER)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.TIMESTAMP)); setBatchSize(10); } }
int count = 5000; for (int i = 0; i < count; i++) { batchInsert.update(new Object[] { i + 100L, "a" + i, "b" + i, null }); }
鑷蟲錛宻pring JDBC涓昏鐨勫簲鐢ㄥ熀鏈笂閮界畝鍗曠綏鍒椾竴鐣紝鎵鏈変唬鐮佸潎涓烘枃绔犱婦渚嬶紝涓嶆槸寰堜弗璋紝浠呬負婕旂ず姣忎竴縐嶇敤娉曪紝鎶涚爾寮曠帀錛屽笇鏈涙湁鐙壒瑙佽В鐨勬媿鐮栵紝鏈夐棶棰樼殑璇鋒寚鏄庨棶棰樻墍鍦?璋㈣阿
欏圭洰涓湁涓笟鍔″鐞嗙被澶у皬117K錛屼唬鐮?700琛岋紝鐪嬫綾誨樊鐐歸浄姝繪垜錛屽浠婂瑕佸鍔犱笟鍔¢昏緫澶х害20涓惂錛屾綾誨鏋滈殢鐫欏圭洰宸ョ▼鐨勪簩鏈熴佷笁鏈熷嬈℃坊鍔犻昏緫榪熸棭鏈変竴澶╁ぇ灝忚揪鍒癕錛屽櫌銆乵ygod銆傜粏蹇冪爺璇誨墠浜虹殑宸ヤ綔鎬葷粨錛屽彂鐜板叾涓湁鐐瑰彲鏀歸犵殑铔涗笣椹抗(鏈漢寰堢銆佸埆絎戞垜鎵嶅彂鐜板浣曟敼閫?銆?/p>
涓嬮潰鎴戜滑瀵逛笟鍔℃祦紼嬨佷互鍙婃秹鍙婄殑鐩稿叧綾昏繘琛屼粙緇嶏紝Msg浠h〃鎺ュ彈鍒板鎴風鐨勪竴涓秷鎭姤鏂囷紝娑堟伅鎶ユ枃緇撴瀯錛氭秷鎭ご+娑堟伅浣擄紝娑堟伅澶村弬鏁板浐瀹氥佹秷鎭綋鍙傛暟涓嶅畾錛屼笅闈㈡槸涓涓畝鍗曠殑綾誨浘錛岃繖鍙槸涓涓ā鎷熷満鏅紝****Req浠h〃鍚勬埛绔姹傜被錛?span lang="EN-US">***Rsp浠h〃榪斿洖緇欏鎴風鐨勫弬鏁扮被銆傚疄闄呮瘮姝ゅ鏉傦紝涓烘弿榪伴棶棰樻垜浠畝鍗曟憳闄ゅ嚑涓被浠嬬粛錛屽埆闂垜涓轟綍榪欎箞璁捐緇ф壙銆傜被鍥?span lang="EN-US">msg涓?span lang="EN-US">msgHead鏄粍鍚堝叧緋諱篃璁哥敾閿欎簡銆佷笉褰撲箣澶勮鎸囧嚭錛屽嬁鎭惰鍚戜激錛?/span>
澶勭悊璇鋒眰Handler綾葷殑浠g爜閫昏緫濡備笅錛?/p>
//綾諱腑涓昏鏂規硶濡備笅 public void execute(Object object) { Message message = (Message)object; int opcode = message.getOpcode(); int connectId = message.getConnectId(); //娑堟伅澶村凡緇忚В鏋愶紝鑾峰彇娑堟伅浣擄紝鍗沖瓙綾誨睘鎬у瓧鑺傛暟緇? byte[] bytes = message.getBytes(); if (opcode == MsgInfo.ADD_RING) { // 璁㈣喘褰╅搩 orderRing(connectId, bytes); } else if (opcode == MsgInfo.PRESENT_RING) { // 璧犻佸僵閾? presentRing(connectId, bytes); } else if (opcode == MsgInfo.DEL_RING) { // 鍒犻櫎涓漢閾冮煶 delPersonalRing(connectId, bytes); } //姝ゅ鐪佺暐n涓猠lse if } //鍏朵粬鍒犻櫎銆佽禒閫佷笌鐪佺暐鐨別lse if涓殑澶勭悊閫昏緫涓庝箣鍩烘湰鐩稿悓 private void orderRing(int connectId, byte[] bytes) { //澶勭悊鏂規硶鍒嗕負鍥涙錛屽叿浣撲唬鐮佺渷鐣? //1銆佽В鏋愬瓧鑺傛暟緇勪負璁㈣喘閾冮煶綾? //2銆佸鐞嗚璐叧緋? //3銆佸鐞嗙粨鏋滃皝瑁呬負璁㈣喘鍝嶅簲綾? //4銆佸彂閫佸洖瀹㈡埛绔? } //鐪佺暐presentRing銆乨elPersonalRing絳変竴緋誨垪鍏朵粬鏂規硶錛屾墍鏈夌殑澶勭悊鏂規硶鍙傛暟鐩稿悓……
閴翠簬姝ゃ佹兂鍒頒嬌鐢ㄥ懡浠ゆā寮忔敼閫犳綾伙紝濡傛灉涓嶄簡瑙e懡浠ゆā寮忚闃呰鐩稿叧涔︾睄錛屽ぇ璇濊璁℃ā寮忔垨璁捐涓庢ā寮忥紝榪欓噷鎴戜滑浠呯粰鍑哄ぇ鑷寸殑瀹氫簬涓庣被鍥俱?/p>
浣曡皳鍛戒護妯″紡錛氬皢涓涓姹傚皝瑁呬負涓涓璞★紝浠庤屾槸浣犲彲鐢ㄤ笉鍚岀殑璇鋒眰瀵瑰鎴風鍙傛暟鍖栵紝瀵硅姹傛帓闃熸垨璁板綍鏃ュ織錛屼互鍙婃敮鎸佸彲鎾ら攢鐨勬搷浣溿?/p>
Shit銆佽繖鍙ヨ瘽寰堥毦鐞嗚В鍝︼紝閭e氨鍏堝埆鐞嗚В浜嗭紝鎴戜滑鐪嬩笅鍛戒護妯″紡鐨勭被鍥撅紝鐒跺悗浠嬬粛濡備綍浣跨敤鍛戒護妯″紡鏀歸犱笂闈㈢殑elseif銆?/p>
綾誨浘鍏堢渷鐣ワ紝涓婄彮鍋風┖鍐欑殑錛?/p>
涓嬮潰榪涘叆姝i錛屽Handler灝忔墜鏈紑濮嬶紝涓昏鑰冭檻濡備笅錛?/p>
1銆?/span>鎻愮偧鏂規硶
灝嗘瘡涓?span lang="EN-US">if璇彞鍧椾腑鐨勯昏緫鎻愬彇涓轟竴涓柟娉曪紝榪欓噷鎴戜滑鐨?span lang="EN-US">handler宸茬粡瀹炵幇錛屽氨鏄細orderRing銆?span mce_style="font-family: 'Courier New'; color: black; font-size: 10pt;" style="font-family: 'Courier New'; color: black; font-size: 10pt; ">presentRing銆?span mce_style="font-family: 'Courier New'; color: black; font-size: 10pt;" style="font-family: 'Courier New'; color: black; font-size: 10pt; ">delPersonalRing銆?#8230;…銆?/p>
2銆?/span>鎻愮偧綾?/strong>
灝嗘瘡涓笟鍔″鐞嗘柟娉曟彁鍙栦負浠ュ悇綾伙紝鐒跺悗瀵瑰叿浣撶被榪涜鎶借薄錛屾彁鍙栫埗綾繪垨鑰呮帴鍙o紱浠g爜濡備笅錛?/p>
public Abstract class Command{ public void execute() 锝? public class OrderRingCommand extends Command { private Handler hander; public OrderRingCommand(Handler hander){ this.hander = hander; } public void execute(int connectId, byte[] bytes){ //1銆佽В鏋愬瓧鑺傛暟緇勪負璁㈣喘閾冮煶綾? //2銆佸鍔犺璐叧緋? //3銆佸鐞嗙粨鏋滃皝瑁呬負璁㈣喘鍝嶅簲綾? //4銆佸彂閫佸洖瀹㈡埛绔? } /** * 1銆佽В鏋愬瓧鑺傛暟緇勪負璁㈣喘閾冮煶綾? */ public void method1(){ } /** * 2銆佸鐞嗚璐叧緋? */ public void method2(){ } /** * 3銆佸鐞嗙粨鏋滃皝瑁呬負璁㈣喘鍝嶅簲綾? */ public void method3(){ } /** * 4銆佺粨鏋滃彂閫佸洖瀹㈡埛绔? */ public void method4(){ } } public class DelRingCommand extends Command { private Handler hander; public DelRingCommand(Handler hander){ this.hander = hander; } public void execute(int connectId, byte[] bytes){ //1銆佽В鏋愬瓧鑺傛暟緇勪負璁㈣喘閾冮煶綾? //2銆佸垹闄よ喘鍏崇郴 //3銆佸鐞嗙粨鏋滃皝瑁呬負璁㈣喘鍝嶅簲綾? //4銆佸彂閫佸洖瀹㈡埛绔? } //鎻愬彇鏂規硶 }
3銆?/span>鍛戒護妯″紡鏀歸犳浛鎹?/strong>elseif錛?/strong>
Map<Integer, Command> map = new HashMap<Integer,Command>(); static{ map.put(MsgInfo.ADD_RING, new OrderRingCommand()); //鐪佸嵈鍏朵粬錛岃繖閲屼粎涓烘紨紺猴紝瀹為檯欏圭洰涓疄渚嬪寲綾婚氳繃spring瀹瑰櫒鎴栬呭叾浠栨柟娉? } public void execute(Object object) { Message message = (Message)object; int opcode = message.getOpcode(); int connectId = message.getConnectId(); //娑堟伅澶村凡緇忚В鏋愶紝鑾峰彇娑堟伅浣擄紝鍗沖瓙綾誨睘鎬у瓧鑺傛暟緇? byte[] bytes = message.getBytes(); map.get(opcode).execute(connectId,bytes); }
鍛戒護妯″紡鏇挎崲else if浠g爜鍧忓懗閬撶殑閲嶆瀯緇撴潫錛屼紬澶氱殑if鏉′歡鍧楃儫娑堜簯鏁o紝鍙栬屼唬涔嬬殑鏄竴涓釜綺劇畝鐨勭被錛宒oc鐗堟湰鍦ㄩ檮浠朵腑
涓銆乀hreadLocal姒傝堪
瀛︿範JDK涓殑綾伙紝棣栧厛鐪嬩笅JDK API瀵規綾葷殑鎻忚堪錛屾弿榪板涓嬶細
API琛ㄨ揪浜嗕笅闈㈠嚑縐嶈鐐癸細
1銆乀hreadLocal涓嶆槸綰跨▼錛屾槸綰跨▼鐨勪竴涓彉閲忥紝浣犲彲浠ュ厛綆鍗曠悊瑙d負綰跨▼綾葷殑灞炴у彉閲忋?/p>
2銆乀hreadLocal 鍦ㄧ被涓氬父瀹氫箟涓洪潤鎬佺被鍙橀噺銆?/p>
3銆佹瘡涓嚎紼嬫湁鑷繁鐨勪竴涓猅hreadLocal錛屽畠鏄彉閲忕殑涓涓?#8216;鎷瘋礉’錛屼慨鏀瑰畠涓嶅獎鍝嶅叾浠栫嚎紼嬨?/p>
鏃㈢劧瀹氫箟涓虹被鍙橀噺錛屼負浣曚負姣忎釜綰跨▼緇存姢涓涓壇鏈紙濮戜笖鎴愪負‘鎷瘋礉’瀹規槗鐞嗚В錛夛紝璁╂瘡涓嚎紼嬬嫭绔嬭闂紵澶氱嚎紼嬬紪紼嬬殑緇忛獙鍛婅瘔鎴戜滑錛屽浜庣嚎紼嬪叡浜祫婧愶紙浣犲彲浠ョ悊瑙d負灞炴э級錛岃祫婧愭槸鍚﹁鎵鏈夌嚎紼嬪叡浜紝涔熷氨鏄榪欎釜璧勬簮琚竴涓嚎紼嬩慨鏀規槸鍚﹀獎鍝嶅彟涓涓嚎紼嬬殑榪愯錛屽鏋滃獎鍝嶆垜浠渶瑕佷嬌鐢╯ynchronized鍚屾錛岃綰跨▼欏哄簭璁塊棶銆?/p>
ThreadLocal閫傜敤浜庤祫婧愬叡浜絾涓嶉渶瑕佺淮鎶ょ姸鎬佺殑鎯呭喌錛屼篃灝辨槸涓涓嚎紼嬪璧勬簮鐨勪慨鏀癸紝涓嶅獎鍝嶅彟涓涓嚎紼嬬殑榪愯錛涜繖縐嶈璁℃槸‘絀洪棿鎹㈡椂闂?#8217;錛宻ynchronized欏哄簭鎵ц鏄?strong>‘鏃墮棿鎹㈠彇絀洪棿’銆?/p>
浜屻乀hreadLocal鏂規硶浠嬬粛
T |
get() 榪斿洖姝ょ嚎紼嬪眬閮ㄥ彉閲忕殑褰撳墠綰跨▼鍓湰涓殑鍊箋?/td> |
protected T |
initialValue() 榪斿洖姝ょ嚎紼嬪眬閮ㄥ彉閲忕殑褰撳墠綰跨▼鐨?#8220;鍒濆鍊?#8221;銆?/td> |
void |
remove() 縐婚櫎姝ょ嚎紼嬪眬閮ㄥ彉閲忓綋鍓嶇嚎紼嬬殑鍊箋?/td> |
void |
set(T value) 灝嗘綰跨▼灞閮ㄥ彉閲忕殑褰撳墠綰跨▼鍓湰涓殑鍊艱緗負鎸囧畾鍊箋?/td> |
涓夈佹繁鍏ユ簮鐮?/strong>
ThreadLocal鏈変竴涓猅hreadLocalMap闈欐佸唴閮ㄧ被錛屼綘鍙互綆鍗曠悊瑙d負涓涓狹AP錛岃繖涓?#8216;Map’涓烘瘡涓嚎紼嬪鍒朵竴涓彉閲忕殑‘鎷瘋礉’瀛樺偍鍏朵腑銆?/p>
褰撶嚎紼嬭皟鐢═hreadLocal.get()鏂規硶鑾峰彇鍙橀噺鏃?棣栧厛鑾峰彇褰撳墠綰跨▼寮曠敤錛屼互姝や負key鍘昏幏鍙栧搷搴旂殑ThreadLocalMap錛屽鏋滄‘Map’涓嶅瓨鍦ㄥ垯鍒濆鍖栦竴涓紝鍚﹀垯榪斿洖鍏朵腑鐨勫彉閲忥紝浠g爜濡備笅錛?/p>
public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) return (T)e.value; } return setInitialValue(); }
璋冪敤get鏂規硶濡傛灉姝ap涓嶅瓨鍦ㄩ鍏堝垵濮嬪寲錛屽垱寤烘map錛屽皢綰跨▼涓簁ey錛屽垵濮嬪寲鐨剉laue瀛樺叆鍏朵腑錛屾敞鎰忔澶勭殑initialValue錛屾垜浠彲浠ヨ鐩栨鏂規硶錛屽湪棣栨璋冪敤鏃跺垵濮嬪寲涓涓傚綋鐨勫箋俿etInitialValue浠g爜濡備笅錛?/p>
private T setInitialValue() { T value = initialValue(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); return value; }
set鏂規硶鐩稿姣旇緝綆鍗曞鏋滅悊瑙d互涓婁咯涓柟娉曪紝鑾峰彇褰撳墠綰跨▼鐨勫紩鐢紝浠巑ap涓幏鍙栬綰跨▼瀵瑰簲鐨刴ap錛屽鏋渕ap瀛樺湪鏇存柊緙撳瓨鍊鹼紝鍚﹀垯鍒涘緩騫跺瓨鍌紝浠g爜濡備笅錛?/p>
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
瀵逛簬ThreadLocal鍦ㄤ綍澶勫瓨鍌ㄥ彉閲忓壇鏈紝鎴戜滑鐪媑etMap鏂規硶錛氳幏鍙栫殑鏄綋鍓嶇嚎紼嬬殑ThreadLocal綾誨瀷鐨則hreadLocals灞炴с傛樉鐒跺彉閲忓壇鏈瓨鍌ㄥ湪姣忎竴涓嚎紼嬩腑銆?/p>
/** * 鑾峰彇綰跨▼鐨凾hreadLocalMap 灞炴у疄渚? */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
涓婇潰鎴戜滑鐭ラ亾鍙橀噺鍓湰瀛樻斁浜庝綍澶勶紝榪欓噷鎴戜滑綆鍗曡涓嬪浣曡java鐨勫瀮鍦炬敹闆嗘満鍒舵敹闆嗭紝褰撴垜浠笉鍦ㄤ嬌鐢ㄦ槸璋冪敤set(null)錛屾鏃朵笉鍦ㄥ皢寮曠敤鎸囧悜璇?#8216;map’錛岃岀嚎紼嬮鍑烘椂浼氭墽琛岃祫婧愬洖鏀舵搷浣滐紝灝嗙敵璇風殑璧勬簮榪涜鍥炴敹錛屽叾瀹炲氨鏄皢灞炴х殑寮曠敤璁劇疆涓簄ull銆傝繖鏃跺凡緇忎笉鍦ㄦ湁浠諱綍寮曠敤鎸囧悜璇ap錛屾晠鑰屼細琚瀮鍦炬敹闆嗐?/p>
鍥涖乀hreadLocal搴旂敤紺轟緥
鍦ㄦ垜鐨勫彟涓綃囨枃绔狅紝瀵筎hreadLocal鐨勪嬌鐢ㄥ仛浜嗕竴涓疄渚嬶紝姝ょず渚嬩篃鍙互鐢ㄤ綔鐢熶駭鐜錛岃鍙傝錛?a mce_href="/blog/757641">http://ari.iteye.com/blog/757641
濡傛湁闂璇風暀璦璁ㄨ錛岃阿璋?/p>
鏈枃鍊熻姳鐚經錛屽紩鐢═im Cull鐨勫崥鏂?#8220;SimpleDateFormat: Performance Pig”浠嬬粛涓婽hreadLocal鐨勭畝鍗曚嬌鐢紝鍚屾椂涔熷SimpleDateFormat鐨勪嬌鐢ㄦ湁涓繁鍏ョ殑浜嗚В銆?/p>
澶ц嚧鎰忔濓細Tim Cull紕板埌涓涓猄impleDateFormat甯︽潵鐨勪弗閲嶇殑鎬ц兘闂錛岃闂涓昏鏈塖impleDateFormat寮曞彂錛屽垱寤轟竴涓猄impleDateFormat瀹炰緥鐨勫紑閿姣旇緝鏄傝吹錛岃В鏋愬瓧絎︿覆鏃墮棿鏃墮綣佸垱寤虹敓鍛藉懆鏈熺煭鏆傜殑瀹炰緥瀵艱嚧鎬ц兘浣庝笅銆傚嵆浣垮皢SimpleDateFormat瀹氫箟涓洪潤鎬佺被鍙橀噺錛岃矊浼艱兘瑙e喅榪欎釜闂錛屼絾鏄疭impleDateFormat鏄潪綰跨▼瀹夊叏鐨勶紝鍚屾牱瀛樺湪闂錛屽鏋滅敤‘synchronized’綰跨▼鍚屾鍚屾牱闈復闂錛屽悓姝ュ鑷存ц兘涓嬮檷錛堢嚎紼嬩箣闂村簭鍒楀寲鐨勮幏鍙朣impleDateFormat瀹炰緥錛夈?/p>
Tim Cull浣跨敤Threadlocal瑙e喅浜嗘闂錛屽浜庢瘡涓嚎紼婼impleDateFormat涓嶅瓨鍦ㄥ獎鍝嶄粬浠箣闂村崗浣滅殑鐘舵侊紝涓烘瘡涓嚎紼嬪垱寤轟竴涓猄impleDateFormat鍙橀噺鐨勬嫹璐濇垨鑰呭彨鍋氬壇鏈紝浠g爜濡備笅錛?/p>
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 浣跨敤ThreadLocal浠ョ┖闂存崲鏃墮棿瑙e喅SimpleDateFormat綰跨▼瀹夊叏闂銆? * @author * */ public class DateUtil { private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; @SuppressWarnings("rawtypes") private static ThreadLocal threadLocal = new ThreadLocal() { protected synchronized Object initialValue() { return new SimpleDateFormat(DATE_FORMAT); } }; public static DateFormat getDateFormat() { return (DateFormat) threadLocal.get(); } public static Date parse(String textDate) throws ParseException { return getDateFormat().parse(textDate); } }
鍒涘緩涓涓猅hreadLocal綾誨彉閲忥紝榪欓噷鍒涘緩鏃剁敤浜嗕竴涓尶鍚嶇被錛岃鐩栦簡initialValue鏂規硶錛屼富瑕佷綔鐢ㄦ槸鍒涘緩鏃跺垵濮嬪寲瀹炰緥銆備篃鍙互閲囩敤涓嬮潰鏂瑰紡鍒涘緩錛?/p>
//絎竴嬈¤皟鐢╣et灝嗚繑鍥瀗ull private static ThreadLocal threadLocal = new ThreadLocal()錛? //鑾峰彇綰跨▼鐨勫彉閲忓壇鏈紝濡傛灉涓嶈鐩杋nitialValue錛岀涓嬈et榪斿洖null錛屾晠闇瑕佸垵濮嬪寲涓涓猄impleDateFormat錛屽茍set鍒皌hreadLocal涓? public static DateFormat getDateFormat() { DateFormat df = (DateFormat) threadLocal.get(); if(df==null){ df = new SimpleDateFormat(DATE_FORMAT) threadLocal.set(df); } return df; }
鎴戜滑鐪嬩笅鎴戜滑瑕嗙洊鐨刬nitialValue鏂規硶錛?/p>
protected T initialValue() { return null;//鐩存帴榪斿洖null }
浣滆咃細niumd
blog錛?a mce_href="/">http://ari.iteye.com
涓銆佹榪?/strong>
Struts2鐨勬牳蹇冩槸涓涓狥ilter錛孉ction鍙互鑴辯web瀹瑰櫒錛岄偅涔堟槸浠涔堣http璇鋒眰鍜宎ction鍏寵仈鍦ㄤ竴璧風殑錛屼笅闈㈡垜浠繁鍏ユ簮鐮佹潵鍒嗘瀽涓婼truts2鏄浣曞伐浣滅殑銆?/p>
閴翠簬甯歌鎯呭喌瀹樻柟鎺ㄨ崘浣跨敤StrutsPrepareAndExecuteFilter鏇夸唬FilterDispatcher錛屾垜浠鏂囧皢鍓栨瀽StrutsPrepareAndExecuteFilter錛屽叾鍦ㄥ伐紼嬩腑浣滀負涓涓狥ilter閰嶇疆鍦╳eb.xml涓紝閰嶇疆濡備笅錛?/p>
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
浜屻佹簮鐮佸睘鎬ф柟娉曠畝浠?/strong>
涓嬮潰鎴戜滑鐮旂┒涓婼trutsPrepareAndExecuteFilter婧愮爜錛岀被鐨勪富瑕佷俊鎭涓嬶細
灞炴ф憳瑕?/strong> | |
---|---|
protected List<Pattern> |
excludedPatterns |
protected ExecuteOperations |
execute |
protected PrepareOperations |
prepare |
StrutsPrepareAndExecuteFilter涓庢櫘閫氱殑Filter騫舵棤鍖哄埆錛屾柟娉曢櫎緇ф壙鑷狥ilter澶栵紝浠呮湁涓涓洖璋冩柟娉曪紝絎笁閮ㄥ垎鎴戜滑灝嗘寜鐓ilter鏂規硶璋冪敤欏哄簭錛岀敱init鈥?gt;doFilter鈥?gt;destroy欏哄簭鍦板垎鏋愭簮鐮併?/p>
鏂規硶鎽樿 | |
---|---|
void |
destroy() 緇ф壙鑷狥ilter錛岀敤浜庤祫婧愰噴鏀?/td> |
void |
doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 緇ф壙鑷狥ilter錛屾墽琛屾柟娉?/td> |
void |
init(FilterConfig filterConfig) 緇ф壙鑷狥ilter錛屽垵濮嬪寲鍙傛暟 |
protected void |
postInit(Dispatcher dispatcher, FilterConfig filterConfig) Callback for post initialization錛堜竴涓┖鐨勬柟娉曪紝鐢ㄤ簬鏂規硶鍥炶皟鍒濆鍖栵級 |
涓夈佹簮鐮佸墫鏋?nbsp;
1銆乮nit鏂規硶
init鏄疐ilter絎竴涓繍琛岀殑鏂規硶錛屾垜浠湅涓媠truts2鐨勬牳蹇僃ilter鍦ㄨ皟鐢╥nit鏂規硶鍒濆鍖栨椂鍋氬摢浜涘伐浣滐細
public void init(FilterConfig filterConfig) throws ServletException { InitOperations init = new InitOperations(); try { //灝佽filterConfig錛屽叾涓湁涓富瑕佹柟娉昰etInitParameterNames灝嗗弬鏁板悕瀛椾互String鏍煎紡瀛樺偍鍦↙ist涓? FilterHostConfig config = new FilterHostConfig(filterConfig); // 鍒濆鍖杝truts鍐呴儴鏃ュ織 init.initLogging(config); //鍒涘緩dispatcher 錛屽茍鍒濆鍖栵紝榪欓儴鍒嗕笅闈㈡垜浠噸鐐瑰垎鏋愶紝鍒濆鍖栨椂鍔犺澆閭d簺璧勬簮 Dispatcher dispatcher = init.initDispatcher(config); init.initStaticContentLoader(config, dispatcher); //鍒濆鍖栫被灞炴э細prepare 銆乪xecute prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher); execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher); this.excludedPatterns = init.buildExcludedPatternsList(dispatcher); //鍥炶皟絀虹殑postInit鏂規硶 postInit(dispatcher, filterConfig); } finally { init.cleanup(); } }
棣栧厛鐪嬩笅FilterHostConfig 錛屾簮鐮佸涓嬶細
public class FilterHostConfig implements HostConfig { private FilterConfig config; /** *鏋勯犲嚱鏁? */ public FilterHostConfig(FilterConfig config) { this.config = config; } /** * 鏍規嵁init-param閰嶇疆鐨刾aram-name鑾峰彇param-value鐨勫? */ public String getInitParameter(String key) { return config.getInitParameter(key); } /** * 榪斿洖鍒濆鍖栧弬鏁板悕鐨凩ist */ public Iterator<String> getInitParameterNames() { return MakeIterator.convert(config.getInitParameterNames()); } public ServletContext getServletContext() { return config.getServletContext(); } }
鍙湁鐭煭鐨勫嚑琛屼唬鐮侊紝getInitParameterNames鏄繖涓被鐨勬牳蹇冿紝灝咶ilter鍒濆鍖栧弬鏁板悕縐版湁鏋氫婦綾誨瀷杞負Iterator銆傛綾葷殑涓昏浣滀負鏄filterConfig 灝佽銆?/p>
閲嶇偣鏉ヤ簡錛屽垱寤哄茍鍒濆鍖朌ispatcher
public Dispatcher initDispatcher( HostConfig filterConfig ) { Dispatcher dispatcher = createDispatcher(filterConfig); dispatcher.init(); return dispatcher; }
鍒涘緩Dispatcher錛屼細璇誨彇 filterConfig 涓殑閰嶇疆淇℃伅錛屽皢閰嶇疆淇℃伅瑙f瀽鍑烘潵錛屽皝瑁呮垚涓轟竴涓狹ap錛岀劧鍚庢牴緇漵ervlet涓婁笅鏂囧拰鍙傛暟Map鏋勯燚ispatcher 錛?/p>
private Dispatcher createDispatcher( HostConfig filterConfig ) { Map<String, String> params = new HashMap<String, String>(); for ( Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); ) { String name = (String) e.next(); String value = filterConfig.getInitParameter(name); params.put(name, value); } return new Dispatcher(filterConfig.getServletContext(), params); }
Dispatcher鍒濆鍖栵紝鍔犺澆struts2鐨勭浉鍏抽厤緗枃浠訛紝灝嗘寜鐓ч『搴忛愪竴鍔犺澆錛歞efault.properties錛宻truts-default.xml,struts-plugin.xml,struts.xml錛?#8230;…
/** *鍒濆鍖栬繃紼嬩腑渚濇鍔犺澆濡備笅閰嶇疆鏂囦歡 */ public void init() { if (configurationManager == null) { configurationManager = new ConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME); } try { //鍔犺澆org/apache/struts2/default.properties init_DefaultProperties(); // [1] //鍔犺澆struts-default.xml,struts-plugin.xml,struts.xml init_TraditionalXmlConfigurations(); // [2] init_LegacyStrutsProperties(); // [3] //鐢ㄦ埛鑷繁瀹炵幇鐨凜onfigurationProviders綾? init_CustomConfigurationProviders(); // [5] //Filter鐨勫垵濮嬪寲鍙傛暟 init_FilterInitParameters() ; // [6] init_AliasStandardObjects() ; // [7] Container container = init_PreloadConfiguration(); container.inject(this); init_CheckConfigurationReloading(container); init_CheckWebLogicWorkaround(container); if (!dispatcherListeners.isEmpty()) { for (DispatcherListener l : dispatcherListeners) { l.dispatcherInitialized(this); } } } catch (Exception ex) { if (LOG.isErrorEnabled()) LOG.error("Dispatcher initialization failed", ex); throw new StrutsException(ex); } }
鍒濆鍖杁efault.properties錛屽叿浣撶殑鍒濆鍖栨搷浣滃湪DefaultPropertiesProvider綾諱腑
private void init_DefaultProperties() { configurationManager.addConfigurationProvider(new DefaultPropertiesProvider()); }
涓嬮潰鎴戜滑鐪嬩笅DefaultPropertiesProvider綾繪簮鐮侊細
public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { Settings defaultSettings = null; try { defaultSettings = new PropertiesSettings("org/apache/struts2/default"); } catch (Exception e) { throw new ConfigurationException("Could not find or error in org/apache/struts2/default.properties", e); } loadSettings(props, defaultSettings); }
鍏朵粬鐨勬垜浠啀嬈$渷鐣ワ紝澶у鍙互嫻忚涓嬪悇涓垵濮嬪寲鎿嶄綔閮藉姞杞戒簡閭d簺鏂囦歡
3銆乨oFilter鏂規硶
doFilter鏄繃婊ゅ櫒鐨勬墽琛屾柟娉曪紝瀹冩嫤鎴彁浜ょ殑HttpServletRequest璇鋒眰錛孒ttpServletResponse鍝嶅簲錛屼綔涓簊trtus2鐨勬牳蹇冩嫤鎴櫒錛屽湪doFilter閲岄潰鍒板簳鍋氫簡鍝簺宸ヤ綔錛屾垜浠皢閫愯瑙h鍏舵簮鐮侊紝婧愮爜濡備笅錛?/p>
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { //鐖剁被鍚戝瓙綾昏漿錛氬己杞負http璇鋒眰銆佸搷搴? HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; try { //璁劇疆緙栫爜鍜屽浗闄呭寲 prepare.setEncodingAndLocale(request, response); //鍒涘緩Action涓婁笅鏂囷紙閲嶇偣錛? prepare.createActionContext(request, response); prepare.assignDispatcherToThread(); if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) { chain.doFilter(request, response); } else { request = prepare.wrapRequest(request); ActionMapping mapping = prepare.findActionMapping(request, response, true); if (mapping == null) { boolean handled = execute.executeStaticResourceRequest(request, response); if (!handled) { chain.doFilter(request, response); } } else { execute.executeAction(request, response, mapping); } } } finally { prepare.cleanupRequest(request); } }
setEncodingAndLocale璋冪敤浜哾ispatcher鏂規硶鐨刾repare鏂規硶錛?/p>
/** * Sets the request encoding and locale on the response */ public void setEncodingAndLocale(HttpServletRequest request, HttpServletResponse response) { dispatcher.prepare(request, response); }
涓嬮潰鎴戜滑鐪嬩笅prepare鏂規硶錛岃繖涓柟娉曞緢綆鍗曞彧鏄緗簡encoding 銆乴ocale 錛屽仛鐨勫彧鏄竴浜涜緟鍔╃殑宸ヤ綔錛?/p>
public void prepare(HttpServletRequest request, HttpServletResponse response) { String encoding = null; if (defaultEncoding != null) { encoding = defaultEncoding; } Locale locale = null; if (defaultLocale != null) { locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale()); } if (encoding != null) { try { request.setCharacterEncoding(encoding); } catch (Exception e) { LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e); } } if (locale != null) { response.setLocale(locale); } if (paramsWorkaroundEnabled) { request.getParameter("foo"); // simply read any parameter (existing or not) to "prime" the request } }
Action涓婁笅鏂囧垱寤猴紙閲嶇偣錛?/strong>
ActionContext鏄竴涓鍣紝榪欎釜瀹規槗涓昏瀛樺偍request銆乻ession銆乤pplication銆乸arameters絳夌浉鍏充俊鎭?ActionContext鏄竴涓嚎紼嬬殑鏈湴鍙橀噺錛岃繖鎰忓懗鐫涓嶅悓鐨刟ction涔嬮棿涓嶄細鍏變韓ActionContext錛屾墍浠ヤ篃涓嶇敤鑰冭檻綰跨▼瀹夊叏闂銆傚叾瀹炶川鏄竴涓狹ap錛宬ey鏄爣紺簉equest銆乻ession銆?#8230;…鐨勫瓧絎︿覆錛屽兼槸鍏跺搴旂殑瀵硅薄錛?/p>
static ThreadLocal actionContext = new ThreadLocal(); Map<String, Object> context;
涓嬮潰鎴戜滑鐪嬩笅濡備綍鍒涘緩action涓婁笅鏂囩殑錛屼唬鐮佸涓嬶細
/** *鍒涘緩Action涓婁笅鏂囷紝鍒濆鍖杢hread local */ public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response) { ActionContext ctx; Integer counter = 1; Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER); if (oldCounter != null) { counter = oldCounter + 1; } //娉ㄦ剰姝ゅ鏄粠ThreadLocal涓幏鍙栨ActionContext鍙橀噺 ActionContext oldContext = ActionContext.getContext(); if (oldContext != null) { // detected existing context, so we are probably in a forward ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap())); } else { ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack(); stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext)); //stack.getContext()榪斿洖鐨勬槸涓涓狹ap<String錛孫bject>錛屾牴鎹Map鏋勯犱竴涓狝ctionContext ctx = new ActionContext(stack.getContext()); } request.setAttribute(CLEANUP_RECURSION_COUNTER, counter); //灝咥ctionContext瀛樺ThreadLocal ActionContext.setContext(ctx); return ctx; }
涓婇潰浠g爜涓璬ispatcher.createContextMap錛屽浣曞皝瑁呯浉鍏沖弬鏁幫細
public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping, ServletContext context) { // request map wrapping the http request objects Map requestMap = new RequestMap(request); // parameters map wrapping the http parameters. ActionMapping parameters are now handled and applied separately Map params = new HashMap(request.getParameterMap()); // session map wrapping the http session Map session = new SessionMap(request); // application map wrapping the ServletContext Map application = new ApplicationMap(context); //requestMap銆乸arams銆乻ession絳塎ap灝佽鎴愪負涓涓笂涓嬫枃Map錛岄愪釜璋冪敤浜唌ap.put(Map p). Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context); if (mapping != null) { extraContext.put(ServletActionContext.ACTION_MAPPING, mapping); } return extraContext; }
鎴戜滑綆鍗曠湅涓婻equestMap錛屽叾浠栫殑鐪佺暐銆俁equestMap綾誨疄鐜頒簡鎶借薄Map錛屾晠鍏舵湰韜槸涓涓狹ap錛屼富瑕佹柟娉曞疄鐜幫細
//map鐨刧et瀹炵幇 public Object get(Object key) { return request.getAttribute(key.toString()); } //map鐨刾ut瀹炵幇 public Object put(Object key, Object value) { Object oldValue = get(key); entries = null; request.setAttribute(key.toString(), value); return oldValue; }
涓嬮潰鏄簮鐮佸睍紺轟簡濡備綍鎵цAction鎺у埗鍣細
public void executeAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException { dispatcher.serviceAction(request, response, servletContext, mapping); } public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionMapping mapping) throws ServletException { //灝佽鎵ц鐨勪笂涓嬫枃鐜錛屼富瑕佽鐩稿叧淇℃伅瀛樺偍鍏ap Map<String, Object> extraContext = createContextMap(request, response, mapping, context); // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY); boolean nullStack = stack == null; if (nullStack) { ActionContext ctx = ActionContext.getContext(); if (ctx != null) { stack = ctx.getValueStack(); } } if (stack != null) { extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack)); } String timerKey = "Handling request from Dispatcher"; try { UtilTimerStack.push(timerKey); //鑾峰彇鍛藉悕絀洪棿 String namespace = mapping.getNamespace(); //鑾峰彇action閰嶇疆鐨刵ame灞炴? String name = mapping.getName(); //鑾峰彇action閰嶇疆鐨刴ethod灞炴? String method = mapping.getMethod(); Configuration config = configurationManager.getConfiguration(); //鏍規嵁鎵ц涓婁笅鏂囧弬鏁幫紝鍛藉悕絀洪棿錛屽悕縐扮瓑鍒涘緩鐢ㄦ埛鑷畾涔堿ction鐨勪唬鐞嗗璞? ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy( namespace, name, method, extraContext, true, false); request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack()); // if the ActionMapping says to go straight to a result, do it! //鎵цexecute鏂規硶錛屽茍杞悜緇撴灉 if (mapping.getResult() != null) { Result result = mapping.getResult(); result.execute(proxy.getInvocation()); } else { proxy.execute(); } // If there was a previous value stack then set it back onto the request if (!nullStack) { request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack); } } catch (ConfigurationException e) { // WW-2874 Only log error if in devMode if(devMode) { String reqStr = request.getRequestURI(); if (request.getQueryString() != null) { reqStr = reqStr + "?" + request.getQueryString(); } LOG.error("Could not find action or result\n" + reqStr, e); } else { LOG.warn("Could not find action or result", e); } sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e); } catch (Exception e) { sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { UtilTimerStack.pop(timerKey); } }
鏂囦腑瀵瑰浣曡В鏋怱truts.xml錛屽浣曞皢URL涓巃ction鏄犲皠鍖歸厤涓哄垎鏋愶紝鏈夐渶瑕佺殑鎴戝悗緇ˉ鍏紝鍥犱負StrutsXmlConfigurationProvider緇ф壙XmlConfigurationProvider錛屽茍鍦╮egister鏂規硶鍥炶皟鐖剁被鐨剅egister錛屾湁鍏磋叮鐨勫彲浠ユ繁鍏ラ槄璇諱笅涓媂mlConfigurationProvider婧愮爜錛?/p>
public void register(ContainerBuilder containerBuilder, LocatableProperties props) throws ConfigurationException { if (servletContext != null && !containerBuilder.contains(ServletContext.class)) { containerBuilder.factory(ServletContext.class, new Factory<ServletContext>() { public ServletContext create(Context context) throws Exception { return servletContext; } }); } //璋冪敤鐖剁被鐨剅egister錛屽叧閿偣鎵鍦? super.register(containerBuilder, props); }
struts2-core-2.2.1.jar鍖呬腑struts-2.1.7.dtd瀵逛簬Action鐨勫畾涔夊涓嬶細
<!ELEMENT action (param|result|interceptor-ref|exception-mapping)*> <!ATTLIST action name CDATA #REQUIRED class CDATA #IMPLIED method CDATA #IMPLIED converter CDATA #IMPLIED >
浠庝笂榪癉TD涓彲瑙丄ction鍏冪礌鍙互鍚湁name 銆乧lass 銆乵ethod 銆乧onverter 灞炴с?/p>
XmlConfigurationProvider瑙f瀽struts.xml閰嶇疆鐨凙ction鍏冪礌錛?/p>
protected void addAction(Element actionElement, PackageConfig.Builder packageContext) throws ConfigurationException { String name = actionElement.getAttribute("name"); String className = actionElement.getAttribute("class"); String methodName = actionElement.getAttribute("method"); Location location = DomHelper.getLocationObject(actionElement); if (location == null) { LOG.warn("location null for " + className); } //methodName should be null if it's not set methodName = (methodName.trim().length() > 0) ? methodName.trim() : null; // if there isnt a class name specified for an <action/> then try to // use the default-class-ref from the <package/> if (StringUtils.isEmpty(className)) { // if there is a package default-class-ref use that, otherwise use action support /* if (StringUtils.isNotEmpty(packageContext.getDefaultClassRef())) { className = packageContext.getDefaultClassRef(); } else { className = ActionSupport.class.getName(); }*/ } else { if (!verifyAction(className, name, location)) { if (LOG.isErrorEnabled()) LOG.error("Unable to verify action [#0] with class [#1], from [#2]", name, className, location.toString()); return; } } Map<String, ResultConfig> results; try { results = buildResults(actionElement, packageContext); } catch (ConfigurationException e) { throw new ConfigurationException("Error building results for action " + name + " in namespace " + packageContext.getNamespace(), e, actionElement); } List<InterceptorMapping> interceptorList = buildInterceptorList(actionElement, packageContext); List<ExceptionMappingConfig> exceptionMappings = buildExceptionMappings(actionElement, packageContext); ActionConfig actionConfig = new ActionConfig.Builder(packageContext.getName(), name, className) .methodName(methodName) .addResultConfigs(results) .addInterceptors(interceptorList) .addExceptionMappings(exceptionMappings) .addParams(XmlHelper.getParams(actionElement)) .location(location) .build(); packageContext.addActionConfig(name, actionConfig); if (LOG.isDebugEnabled()) { LOG.debug("Loaded " + (StringUtils.isNotEmpty(packageContext.getNamespace()) ? (packageContext.getNamespace() + "/") : "") + name + " in '" + packageContext.getName() + "' package:" + actionConfig); } }
宸ヤ綔涓笉娑夊強Struts2錛屾湰鍛ㄥ伐浣滄湁涓?澶╃殑絀烘。鏈燂紝紼嶅井鐪嬩簡涓媠truts2鐨勬枃妗o紝鍐欎簡涓猟emo錛屼粠婧愮爜鐨勮搴︾爺絀朵簡涓嬭繍琛屽師鐞嗭紝濡傛湁鍒嗘瀽涓嶅綋璇鋒寚鍑猴紝鎴戝悗緇愭瀹屽杽鏇存錛屽ぇ瀹跺叡鍚屾彁楂樸?/p>