內部原理主要一個connector,一個container;connector主要負責解析網絡請求,container負責生成一個ruquest和一個response;html
Servlet是sun公司提供的一門用於開發動態web資源的技術。
Sun公司在其API中提供了一個servlet接口,用戶若想用發一個動態web資源(即開發一個Java程序向瀏覽器輸出數據),須要完成如下2個步驟:
一、編寫一個Java類,實現servlet接口。
二、把開發好的Java類部署到web服務器中。
按照一種約定俗成的稱呼習慣,一般咱們也把實現了servlet接口的java程序,稱之爲Servletjava
1:新建一個webproject,在src下新建一個package,在package下新建一個servlet類。以下:web
FirstServlet有以下代碼:瀏覽器
package com.chengguruchun.study;服務器
import java.io.IOException;網絡
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;app
public class FirstServlet extends HttpServlet {post
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {this
response.setContentType("text/html");spa
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
這些代碼都是Eclipse自動生成的,而web.xml文件中也多了<servlet></servlet> 和<servlet-mapping></servlet-mapping>兩對標籤,這兩對標籤是配置First Servlet的,以下圖所示:
第二步:在FirstServlet doget方法中寫入以下代碼:(引入相應的包import java.io.IOException;
import java.io.PrintWriter;)
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
第三步:咱們就能夠經過瀏覽器訪問FirstServlet這個Servlet,以下圖所示:
ok了。