Servlet

Servlet 簡介
Java Servlet是和平臺無關的服務器端組件,它運行在Servlet容器中。Servlet容器負責Servlet和客戶的通信以及調用Servlet的方法,Servlet和客戶的通信采用“請求/響應”的模式。

Servlet可完成如下功能:
創建并返回基于客戶請求的動態HTML頁面。
與其它服務器資源(如數據庫或基于Java的應用程序)進行通信。


Servlet本質上就是一個運行在Servlet容器中的Java類,現在充當Servlet容器的就是安裝的Tomcat

第一個Servlet——HelloWorld
1.創建一個Java類實現Servlet接口,并實現其中所有的方法;

package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Created by ttc on 2018/3/6.
 */
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("HelloServlet");
    }
}

@WebServlet("/hello")
表示的是為helloServlet映射一個訪問路徑/hello,我們在瀏覽器上輸入http://localhost:8080/hello,代碼執行程序流會進入到HelloServlet 的doGet方法。

3.運行Tomcat,在瀏覽器中輸入http://localhost:8080/hello,可以發現控制臺輸出了一些內容,首先是構造器,然后是init,再然后是service,然后每次刷新,每次都只出現了service,然后關閉服務,發現出現destory。

Servlet的生命周期

package servlet;

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

/**
 * Created by ttc on 2018/3/6.
 */
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("service");
        HttpServletRequest request = (HttpServletRequest)req;
        System.out.println(request.getMethod());
        super.service(req, res);
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        System.out.println("init");
        super.init();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
    }
}

①服務器加載Servlet,服務器啟動之后,但不是創建Servlet

②創建Servlet實例
--只有第一次請求Servlet時,創建Servlet實例,調用構造器也就是和類名一樣的構造方法,沒寫的話自動生成

③初始化init()
--只被調用一次,在創建好實例后立即被調用,用于初始化當前Servlet

④service()處理用戶請求
--可以被多次調用,每次請求都會調用service方法,實際用于響應請求的,根據用戶請求的類型(get或者post),調用doGet或者doPost方法。

⑤destory()銷毀
--只被調用一次,在當前Servlet所在的WEB應用被卸載前調用,用于釋放當前Servlet所占用的資源


load-on-startup

可以指定Servlet被創建的時機

package servlet;

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

/**
 * Created by ttc on 2018/3/6.
 */
@WebServlet(value = "/hello",loadOnStartup = 1)
public class HelloServlet extends HttpServlet {
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("service");
        HttpServletRequest request = (HttpServletRequest)req;
        System.out.println(request.getMethod());
        super.service(req, res);
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        System.out.println("init");
        super.init();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
    }
}

在加載完Servlet后直接就創建了Servlet實例,并進行了初始化,在此期間我們并沒有提出請求。
如果配置了多個Servlet, load-on-startup的值越小越先啟動(包括0,負數不會被啟動,還是需要發出請求才創建實例并初始化);


Servlet映射細節

在Servlet映射到的URL中也可以使用 * 通配符,但是只能有兩種固定的格式:
一種格式是“* .擴展名”

@WebServlet(value = "*.do")
public class HelloServlet extends HttpServlet
 {
}

另一種格式是以正斜杠(/)開頭并以“/ * ”結尾。

@WebServlet(value = "/*")
public class HelloServlet extends HttpServlet
 {
}

注意:既帶 / 又帶 * 的,又帶擴展名的,是不合法的(例如:/.do)。*
urlPatterns = "/" 比urlPatterns = ".do"的優先級高

HTTP簡介

WEB瀏覽器與WEB服務器之間的一問一答的交互過程必須遵循一定的規則,這個規則就是HTTP協議。
HTTP是 hypertext transfer protocol(超文本傳輸協議)的簡寫,它是 TCP/IP 協議集中的一個應用層協議,用于定義WEB瀏覽器與WEB服務器之間交換數據的過程以及數據本身的格式。

HTTP 的會話方式

四個步驟:

瀏覽器與WEB服務器的連接過程是短暫的,每次連接只處理一個請求和響應。對每一個頁面的訪問,瀏覽器與WEB服務器都要建立一次單獨的連接。
瀏覽器到WEB服務器之間的所有通訊都是完全獨立分開的請求和響應對。

HTTP請求消息(了解即可)

請求消息的結構:
一個請求行、若干消息頭、以及實體內容,其中的一些消息頭和實體內容都是可選的,消息頭和實體內容之間要用空行隔開。

HTTP響應消息(了解即可)

響應消息的結構:
一個狀態行、若干消息頭、以及實體內容 ,其中的一些消息頭和實體內容都是可選的,消息頭和實體內容之間要用空行隔開。
這里舉個小實例:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

    <form action="/loginServlet" method="post">
        user:<input type="text" name="user">
        password:<input type="password" name="password">
        <input  type="submit" value="Submit">
    </form>

</body>
</html>

運行服務器,在瀏覽器中打開這個網頁,開發者工具,提交表單,提示404(申請資源不存在),在chrome network中查看請求及響應消息。

POST和GET請求

post請求方式我們可以看到請求參數在請求體里面
將請求方式改為get后再運行觀察

<form action="/loginServlet" method="get">
        user:<input type="text" name="user">
        password:<input type="password" name="password">
        <input  type="submit" value="Submit">
</form>

可以觀察到地址欄是這樣的:http://localhost:8080/loginServlet?user=123&password=123
get請求把請求參數附著在url后面,中間以"?”分割。

使用GET方式傳遞參數

①在瀏覽器地址欄中輸入某個URL地址或單擊網頁上的一個超鏈接時,瀏覽器發出的HTTP請求消息的請求方式為GET。
②如果網頁中的<form>表單元素的method屬性被設置為了“GET”,瀏覽器提交這個FORM表單時生成的HTTP請求消息的請求方式也為GET。
③使用GET請求方式給WEB服務器傳遞參數的格式:
http://www.neusoft.net/counter.jsp?name=yzn&password=123
④使用GET方式傳送的數據量一般限制在1KB以下。

使用POST方式傳遞參數

①POST請求方式主要用于向WEB服務器端程序提交FORM表單中的數據。
②POST方式將各個表單字段元素及其數據作為HTTP消息的實體內容發送給WEB服務器,傳送的數據量要比使用GET方式傳送的數據量大得多。
3.如果網頁中的<form>表單元素的method屬性被設置為了“POST”,瀏覽器提交這個FORM表單時生成的HTTP請求消息的請求方式也為POST。


如何在Servlet中獲取信息

這里我們可以新建一個Servlet。

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet { 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post");
    }

}

其中,方法的參數HttpServletRequest requestHttpServletResponse response封裝了請求和響應信息

一.如何獲取請求信息

HttpServletRequest常用的方法:
String getParameter(String name)
--根據請求參數的名字,返回參數值,特別常用

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user = request.getParameter("user");
        String password = request.getParameter("password");
        System.out.println(user+"   "+password);
}


String[] getParameterValues(String name)
--根據請求參數的名字,返回請求參數對應的字符串數組(例如:一組復選框-->名字是一樣的)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String intrests[] = request.getParameterValues("hobby");
        for(String str:intrests) {
            System.out.println(str);
        }
}

獲取請求的URI
獲取請求方式

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getMethod();
        System.out.println(method);

        String servletPath = request.getServletPath();
        System.out.println(servletPath);
}

解決請求中的中文亂碼問題:

request.setCharacterEncoding("utf-8");

二.如何返回響應信息

HttpServletResponse常用的方法:
①getWriter()方法
--返回PrintWriter對象,調用這個對象的println()方法可以將信息直接打印在客戶的瀏覽器上

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

        PrintWriter out = response.getWriter();
        out.println("hello...");

}

解決回應中的中文亂碼問題

//1.設置response的編碼為utf-8
response.setCharacterEncoding("utf-8");
//2.通知瀏覽器,以UTF-8的編碼打開
response.setContentType("text/html;charset=UTF-8");

練習

定義一個login.html,里面定義一個表單,表單中包含2個請求字段user,password,發送請求到loginServlet,再創建一個LoginServlet,在其中獲取請求的user,password,比對其是否是zhangsan,123,若一致,響應Hello:xxx;若不一致,響應Sorry:xxx;xxx為user

<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="login.html">login</a>
  </body>
</html>
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "loginServlet",urlPatterns = "/login")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter printWriter =response.getWriter();
        if(username.equals("zhangsan")&&password.equals("123")){
            printWriter.println("hello"+username);
        }
        else {
            printWriter.println("sorry"+username);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" action="login">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit">
</form>
</body>
</html>

上面的輸入中文會亂碼,改進措施

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,546評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,570評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,505評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,017評論 1 313
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,786評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,219評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,287評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,438評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,971評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,796評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,995評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,540評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,230評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,918評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,697評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容