Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1503170
  • 博文数量: 3500
  • 博客积分: 6000
  • 博客等级: 准将
  • 技术积分: 43870
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-03 20:31
文章分类

全部博文(3500)

文章存档

2008年(3500)

我的朋友

分类:

2008-05-04 20:10:09

一起学习
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()   ".
"); } 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(".
"); } 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,如:




    

    





Frame的src属性可以指向静态页或是servlet. 下载本文示例代码


Servlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABCServlet技巧ABC
阅读(84) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~