1. 程式人生 > >Servlet入門

Servlet入門

tin div per cto tom vax import truct date

package cn.itcast.Aservlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 */
@WebServlet("/Aservlet")
public class Aservlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Aservlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendError(200); response.setDateHeader("expires", 1000*60*60*24); response.setIntHeader("Conten-Length", 492); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package cn.itcast.Aservlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
//servlet中的方法大多數不由我們調用而是服務器,並且對象也是由服務器創建
public class Bservlet implements Servlet {
    ServletConfig conf;
//生命周期方法,Servlet即將結束時Tomcat自動調用,只運行一次,目的釋放非內存資源比如關閉IO流等;
    @Override
    public void destroy() {
        System.out.println("destroy");

    }
//獲取servlet配置信息
    @Override
    public ServletConfig getServletConfig() {
        
        return conf;
    }
//獲取servlet的信息
    @Override
    public String getServletInfo() {
        
        return "快樂的servlet";
    }
//生命周期方法,出生時自動運行,tomcat調用只運行一次
    @Override
    public void init(ServletConfig conf) throws ServletException {
        this.conf=conf;

    }
//生命周期方法,tomcat調用
    @Override
    public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
        

    }

}

Servlet入門