|
|
servlet学习(第一篇) |
|
|
作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站 |
一、 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) 会话何时建立?在浏览器启动时创建。

|
|
相关文章:相关软件: |
|