servlet技巧abc
1.利用stringbuffer提高速度.
servlets经常需要显示html标记,我们很自然想到println()和string串联起来,
但是string是很慢的,但是我们用stringbuffer它快很多.
比较这两例:
用string,
for (int i=0; i<100; i++) { out.println("data for " + i + " is " + method1() + " , " + method2() + ".<br>"); } out.close();
|
用stringbuffer,可发这样:
stringbuffer buf = new stringbuffer(); for (int i=0; i<100; i++) { buf.append("data for ").append(i).append(" is ").append(method1()); buf.append(" , ").append(method2()).append(".<br>"); } response.setcontentlength(buf.length()); out.println(buf.tostring()); out.close();
|
我们用stringbuffer实现我个问题减少了对像的创建个数,
所以它比out.println()更有效.
2.利用http status codes显示出错信息.
比如我们常用类似下面的处理
public void openfile( string filename ) { try { someothermethodtoopenafile( filename ); } catch( filenotfoundexception e ) { out.println( "sorry... file not found." ); } }
|
为了得用status codes,我们可以这样得用http出错信息:
/* 'response' variable is an object of the httpservletresponse class. */ public void openfile( string filename ) { try { someothermethodtoopenafile( filename ); } catch( filenotfoundexception e ) { response.senderror( response.sc_not_found ); } }
|
3.在frame调用servlet动态生成页面.
在静态页内包含frame,使"src"指向你希望的servlet,如:
<frameset rows="20%,*" cols="80%,*"> <frame name="frame1" src="/servlet/someservlet"> <frame name="frame2" src="/servlet/anotherservlet"> </frameset>
|
frame的src属性可以指向静态页或是servlet.