1. 程式人生 > 實用技巧 >淺談JavaWeb-Servlet

淺談JavaWeb-Servlet

Servlet

Servlet是一種動態開發web的一種技術

實現Servlet介面的java程式叫做Servlet

1,父專案中jar包,子專案(moudle)中可以使用

2,編寫一個Servlet程式,實現Servlet介面,我們直接可以繼承HTTPServlet

public class MyServelt extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer=resp.getWriter();  //響應流
        writer.println("你好");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

HttpServlet原理

最開始定義了一個

Servlet介面 定義了一個 void service(ServletRequest var1, ServletResponse var2)

GenericServlet實現了Servlet介面,但是並沒有具體實現service方法,

​ public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

HttpServlet 繼承了 抽象GenericServlet 類,根據不同Get/Post等選擇不同的doGet()方法,或

doPost()方法

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                this.doGet(req, resp);
            } else {
            

3,修改web.xml檔案

為什麼需要對映,我們寫的是java程式,要通過瀏覽器訪問,所以瀏覽器要連線web伺服器,我們需要到web伺服器中註冊我們寫的Servlet,並指出瀏覽器能夠訪問的路徑

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <!--註冊Servlet-->
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.MyServelt</servlet-class>
  </servlet>
  <!--Servlet請求路徑-->
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/huanghongtao</url-pattern>
  </servlet-mapping>