什么是servlet及其生命周期
Serlets是java類,是為http請求做應(yīng)用服務(wù),實現(xiàn)javax。servlet。Servlet接口的java類。Web開發(fā)的時候,繼承HttpSerlet類,HttpSerlet是一個實現(xiàn)了Servlet的抽象類。專門用于處理http請求。
1進行serlet開發(fā)
1)將繼承httpservlet的HelloWorld類,進行編譯,生成的。class文件放在tomcat的安裝目錄的/webapps/ROOT/WEB-INF/classes
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*;// Extend HttpServlet class public class HelloWorld extends HttpServlet {private String message;public void init() throws ServletException {// Do required initializationmessage = "Hello World";}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// Set response content typeresponse.setContentType("text/html");// Actual logic goes here.PrintWriter out = response.getWriter();out.println("<h1>" + message + "</h1>");}public void destroy() {// do nothing.} }2)在tomcat安裝目錄的/webapps/ROOT/WEB-INF/下創(chuàng)建一個web.xml,在<web-app>...</web-app>標簽里寫
<servlet><servlet-name>HelloWorld</servlet-name><servlet-class>HelloWorld</servlet-class> </servlet><servlet-mapping><servlet-name>HelloWorld</servlet-name><url-pattern>/HelloWorld</url-pattern> </servlet-mapping>
3)啟動tomcat服務(wù)器,windows下點擊\bin\startup.bat,linux下點擊/bin/startup.sh,最后在瀏覽器輸入http://localhost:8080/HelloWorld,打印出message
2 servlet的生命周期
1)init()方法
該方法只被調(diào)用一次,當服務(wù)器開啟,servlet被加載,用戶首次調(diào)用與該servlet對應(yīng)的url時創(chuàng)建serlet,調(diào)用init().
當用戶調(diào)用serlet,每個servlet的單個實例被創(chuàng)建,用戶的每一個請求都開啟一個線程,將請求傳遞給doGet或者doPost處理。the insit()用來創(chuàng)建一些整個生命周期都要用到的東西
2)service()方法
servlet容器(tomcat服務(wù)器)會調(diào)用service()方法,處理從客戶端傳來的請求,并返回格式化的response給客戶。
服務(wù)器每次收到servlet請求,就會開啟一個線程,核對該請求時get,post,put等哪一種請求,然后調(diào)用對應(yīng)得doGet,doPost,doPut,doDelete
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { }容器調(diào)用service()方法,service()調(diào)用doGet等方法,我們不用關(guān)心service是怎么寫的,只需要復(fù)寫doGet等方法。3)doGet(),后端獲取的數(shù)據(jù)來源于瀏覽器的url
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// Servlet code }4)doPost方法,后端數(shù)據(jù)來源于表單 public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// Servlet code }5)destroy方法,結(jié)束servlet生命,讓servlet關(guān)閉數(shù)據(jù)庫連接,后臺線程,寫cookie列表或者命中數(shù)到磁盤,當destroy被調(diào)用,servlet對象就會被垃圾回收機制回收。
 
 
 
總結(jié)
以上是生活随笔為你收集整理的什么是servlet及其生命周期的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: php简历程序模板,PHP程序员工作简历
 - 下一篇: MySQL源码包编译安装