servlet学习(第一篇)

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

一、 servlet包

web开发使用javax.servlet.*和javax.servlet.http.*两个程序包的类和接口。其中javax.servlet包中只有一个GenericServlet类,被HttpServlet继承。其他的都属于javax.servlet.http

声明servlet类aaServlet

public class aaServlet extends HttpServlet{

}

二、sevlet的生命周期

1,加载与初始化。

init()方法

servlet在结束之前只能执行一次init()方法。init方法在浏览器请求servlet或web server启动时加载运行。

public void init()throws ServletException{

}

public void init(ServletConfig conf)throws ServletException{

super.init(conf);//init方法带ServletConfig参数时必须有此句代码

//此处写一些初始化操作。如连接数据库等。

}

2,servlet执行(经常使用doPost,doGet方法)

用service()处理客户请求。经常的用法是:不用service()方法,用doPost,doGet方法来处理请求。其他的方法还有doTrace(),doOptions().doHead()方法,因Trace,Options.Head信息已经在doPost,doGet方法中包括,不必使用,doPut(),doDelete()方法在web app不经常使用

3,结束

用destroy()方法回收。

public void destroy(){

}

public void destroy(){

super.dedtroy(conf);

}

三,HttpSession中还有常用的doPost(),doGet().和service()方法一样,这些方法需要用HttpServletRequest和HttpServletResponse对象作参数,抛出ServletException和IOException异常。

四,HttpServletRequest常用的方法:

getRealPath,getInputStream,getContentType,getContentLengh...

得到服务器的根目录

String path=request.getRealPath(".");

取得输入流

DataInputStream din=new DataInputStream(request.getInputStream());

五,HttpServletResponse对象常用的方法:

sendRedirect,getWriter,setContentType,getOutputStream.

设置文件类型

private static final String CONTENT_TYPE="text/html;charset=GB2312";

response.setContentType(CONTENT_TYPE);

输出html文件头部信息:

PrintWriter out=response.getWriter();

out.close();

httpSession封装了会话的细节,用HttpServletRequest对象的getSession()方法获得会话对象,当使用getSession(false),不存在会话时返回null.getSession()等价与getSession(true)

会话何时建立?在浏览器启动时创建。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航