Servlet從入門到精通(超級詳細!)
概述
Servlet(Server Applet)是Java Servlet的簡稱,稱為小服務程序或服務連接器,用Java編寫的服務器端程序,具有獨立于平臺和協議的特性,主要功能在于交互式地瀏覽和生成數據,生成 動態(tài)Web內容。這個過程為:
1,客戶端發(fā)送請求至服務器端
2,服務器將請求信息發(fā)送至 Servlet
3,Servlet 生成響應內容并將其傳給服務器。響應內容動態(tài)生成,通常取決于客戶端的請求
4,服務器將響應返回給客戶端
Servlet 看起來像是通常的 Java 程序。Servlet 需要導入特定的屬于 Java Servlet API 的包。
Servlet有三種實現方式:實現Servlet接口, 繼承抽象類GenericServlet, 繼承HttpServlet
入門案例
創(chuàng)建Servlet程序
選中src-右鍵-New-Create New Servlet-輸入Servlet類的名字和包名-ok
package cn.tedu.test;
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;
@WebServlet(name = "MyServlet")
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//向瀏覽器響應指定內容
response.getWriter().write("hello servlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);//調用doPost()
}
}注解方式配置Servlet程序
1,直接在Servlet類上加一個注解就可以了
//Servlet程序想要別瀏覽器訪問,使用@WebServlet規(guī)定了瀏覽器的訪問方式
@WebServlet("/hello/Servlet1")
2,打開瀏覽器直接訪問這個Servlet就可以了
http://localhost:8080/hello/Servlet1
配置文件方式配置Servlet程序(提供web.xml)
在Servlet3.0版本中,被@WebServlet注解代替,如:@WebServlet("/myservlet")括號中,就可以規(guī)定訪問方式
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--這是Servlet程序的核心配置文件,IDEA不會自動幫我們配置,只能自己來配置的,主要是規(guī)定瀏覽器的訪問方式-->
<servlet>
<servlet-name>myservlet</servlet-name>
<!--Servlet類的全路徑-->
<servlet-class>cn.tedu.test.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<!--規(guī)定了瀏覽器的訪問方式-->
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
</web-app>
測試

你寫個HTML網頁測試也可以的
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <form action="http://localhost:8080/cgbservletjava01_war_exploded/a/b/x" method="post"> <input type="text" name="username"> <br> <input type="submit" value="提交"> </form> </body> </html>
Servlet的繼承結構

Servlet的生命周期
Servlet 生命周期可被定義為從創(chuàng)建直到毀滅的整個過程。以下是 Servlet 重要階段遵循的過程:
1,初始化階段 調用init()方法
2,響應客戶請求階段 調用service()方法
3,終止階段 調用destroy()方法
最后,Servlet 是由 JVM 的垃圾回收器進行垃圾回收的。

init() 方法
init 方法被設計成只調用一次。它在第一次創(chuàng)建 Servlet 時被調用,在后續(xù)每次用戶請求時不再調用。因此,它是用于一次性初始化,Servlet 創(chuàng)建于用戶第一次調用對應于該 Servlet 的 URL 時,但是您也可以指定 Servlet 在服務器第一次啟動時被加載。
當用戶調用一個 Servlet 時,就會創(chuàng)建一個 Servlet 實例,每一個用戶請求都會產生一個新的線程,適當的時候移交給 doGet 或 doPost 方法。init() 方法簡單地創(chuàng)建或加載一些數據,這些數據將被用于 Servlet 的整個生命周期。
service() 方法
它是Servlet的核心,每當一個客戶請求一個HttpServlet對象,該對象的Service()方法就要調用,而且傳遞給這個方法一個“請求”(ServletRequest)對象和一個“響應”(ServletResponse)對象作為參數。在HttpServlet中已存在Service()方法。
service() 方法會檢查 HTTP 請求類型(GET、POST、PUT、DELETE 等),并在適當的時候調用 doGet、doPost、doPut,doDelete 等方法,service() 方法由容器調用,您只需要根據來自客戶端的請求類型來重寫 doGet() 或 doPost() 即可。
doGet() 和 doPost() 方法是每次服務請求中最常用的方法。
doGet() 方法
GET 請求來自于一個 URL 的正常請求,或者來自于一個未指定 METHOD 的 HTML 表單,它由 doGet() 方法處理。
doPost() 方法
POST 請求來自于一個特別指定了 METHOD 為 POST 的 HTML 表單,它由 doPost() 方法處理。
destroy() 方法
destroy() 方法只會被調用一次,在 Servlet 生命周期結束時被調用。destroy() 方法可以讓您的 Servlet 關閉數據庫連接、停止后臺線程、把 Cookie 列表或點擊計數器寫入到磁盤,并執(zhí)行其他類似的清理活動。在調用 destroy() 方法之后,servlet 對象被標記為垃圾回收。
Request
概述
Request對象用來解析請求參數,當瀏覽器訪問服務器時,攜帶著一些請求參數,可以通過Servlet提供的Request對象提供的API來解析請求參數
請求對象有兩個:
ServletRequest httpServletRequest
常用的方法:
getParameter("參數名")--根據參數名獲取參數的值
getParameterValues()--獲取到所有參數的值并存入數組
setCharacterEncoding()--設置請求的字符編碼方式
getCharacterEncoding()--返回字符編碼方式
setAttribute(String,Object) 存儲此請求中的屬性
getAttribute(String name) 返回指定屬性的屬性值
測試
前端HTML程序
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <a href="http://localhost:8080/cgbservletjava01_war_exploded/FormServlet?name=張三&addr=北京">點我提交get數據</a> <form action="http://localhost:8080/cgbservletjava01_war_exploded/FormServlet" method="post"> 用戶名: <input type="text" name="username"> <br /> 愛好: <input type="checkbox" name="hobby" value="籃球"/>籃球 <input type="checkbox" name="hobby" value="足球"/>足球 <input type="checkbox" name="hobby" value="乒乓球"/>乒乓球 <br /> <input type="submit" value="提交"> </form> </body> </html>
后端java程序
package cn.tedu.req;
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.util.Arrays;
@WebServlet(name = "FormServlet")
public class FormServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//請求參數中,包含中文時,post必須配置
// request.setCharacterEncoding("utf-8");
//獲取請求參數
//方式1:根據參數名獲取一個值
String name = request.getParameter("username");
System.out.println("name = " + name);
//方式2:根據參數名獲取所有值,并返回數組
String[] likes = request.getParameterValues("hobby");
System.out.println("hobby = " + Arrays.toString(likes));
//給瀏覽器做出響應
response.getWriter().print("dopost..success!");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String addr = request.getParameter("addr");
System.out.println("doget..."+name+addr);
}
}請求轉發(fā)
概述
請求轉發(fā)是服務器內部資源的一種跳轉方式,即當瀏覽器發(fā)送請求訪問服務器中的某一個資源時,該資源將請求轉交給另外一個資源進行處理的過程,就叫做請求轉發(fā),具有以下特點:
1,請求轉發(fā)整個過程是一次請求、一次響應
2,請求轉發(fā)前后,瀏覽器地址欄地址不會發(fā)生變化(瀏覽器–訪問–>A–轉發(fā)–>B,地址欄地址始終指向A的地址)
3,請求轉發(fā)前后的request對象是同一個
4,轉發(fā)前后的兩個資源必須屬于同一個Web應用,否則將無法進行轉發(fā)
5,使用代碼: request.getRequestDispatcher(訪問目的資源的路徑).forward(request,response);
6,也可以使用 setAttribute()/getAttribute()來驗證

測試過程

Response
概述
Response是代表Http響應信息的對象,其中將會封裝服務器要發(fā)送給瀏覽器的響應信息,將response對象作為參數傳遞給service方法,在service方法處理請求的過程中,可以將要發(fā)送給瀏覽器的數據,先寫入response對象中,在service方法執(zhí)行完后,服務器負責從response對象中獲取到響應信息,再按照http響應信息的格式組織成響應消息,發(fā)送給瀏覽器。
常用的方法:
setContentType("參數名")--設置響應的字符編碼方式
sendRedirect()--完成重定向
getOutputStream()--獲取字節(jié)輸出流
getWriter()--獲取字符輸出流
setHeader("Access-Control-Allow-Origin", "*"); --專門用來解決跨域問題
測試
package cn.tedu.resp;
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;
@WebServlet(name = "RespServlet")
public class RespServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//響應數據中包含中文,會亂碼,用以下代碼指定編碼,緩沖字符輸出流內部有一個緩沖區(qū),這個緩沖區(qū)的默認字符集是ISO-8859-1
response.setContentType("text/html;charset=utf-8");
//給瀏覽器響應數據
response.getWriter().write("你好123");
}
}
重定向
概述
當瀏覽器向服務器發(fā)送請求訪問某一個資源A時,資源A在響應時通知瀏覽器需要再進一步請求才能獲取到對應的資源,瀏覽器再次向服務器發(fā)送請求訪問資源B,最終是由資源B響應瀏覽器要獲取的數據,這個過程叫做重定向,具有以下特點:
1,重定向前后是兩次請求、兩次響應
2,重定向前后,瀏覽器地址欄地址會發(fā)生變化(因為兩次請求都是通過瀏覽器發(fā)起,瀏覽器知道這個跳轉過程,因此地址欄地址會發(fā)生變化)。
3,重定向前后的request對象不是同一個 (因此重定向前后是兩次請求,服務器根據兩次請求會創(chuàng)建兩個request對象,因此request對象不是同一個)
4,重定向前后的兩個資源可以來自不同的Web應用,甚至可以是來自不同的虛擬主機或者服務器。
5,使用代碼: response.sendRedirect(“重定向到資源的路徑”);

測試
觀察,一開始是訪問A資源,服務器內部重定向后,地址欄已經變成了B資源的訪問方式了.是兩次請求兩次響應
package cn.tedu.resp;
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;
@WebServlet(name = "RedirectServlet")
public class RedirectServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//重定向的地址,可以隨意設置,不是必須在同一工程中
//response.sendRedirect("http://localhost:8080/cgbservletjava01_war_exploded/RespServlet");
response.sendRedirect("https://www.baidu.com/");
}
}擴展:在web工程里使用Servlet程序 在IDEA里創(chuàng)建一個web工程
File-New-Project-選Java Enterprise并勾選右側的Web Application-next-輸入工程名稱-Finish
整理web工程目錄結構

修改資源輸出位置

修改jar包存放位置


配置Tomcat服務器
略,詳情見Tomcat服務器的內容
擴展案例
創(chuàng)建前端網頁
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<link rel="stylesheet" >
</head>
<body>
<div id="app">
<el-button type="danger" @click="get()">點我</el-button>
<el-input v-model="name"></el-input>
<el-input v-model="id"></el-input>
</div>
<script>
new Vue({
el:"#app",
data(){
return{
name:'',
id:''
}
},
methods:{
get(){
// axios.get("http://localhost:8080/axios/t3?id=10&name=jack").then(
axios.get("http://localhost:8080/axios/t3",{
params:{
id:10,
name:'jack'
}
}).then(
a=>{
console.log(a);
console.log(a.data);
this.id=a.data.id;
this.name=a.data.name;
}
)
}
}
})
</script>
</body>
</html>創(chuàng)建Servlet程序
package cn.tedu.cgb2110boot03.test;
import com.alibaba.fastjson.JSON;
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;
@WebServlet("/axios/t3")
public class ServletT3 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(111);
response.setHeader("Access-Control-Allow-Origin", "*");
String id = request.getParameter("id");
String name = request.getParameter("name");
// {"id":"10","name":"jack"}
// "{\"id\":\"10\",\"name\":\"jack\"}"
String json="{\"id\":\""+id+"\",\"name\":\""+name+"\"}";
response.getWriter().write(json);
}
}總結
到此這篇關于Servlet從入門到精通的文章就介紹到這了,更多相關Servlet入門內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java并發(fā)包中CountDownLatch和線程池的使用詳解
這篇文章主要介紹了java并發(fā)包中CountDownLatch和線程池的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
MyBatis映射文件中parameterType與resultType的用法詳解
MyBatis中的ParameterType指的是SQL語句中的參數類型,即傳入SQL語句中的參數的類型,下面這篇文章主要給大家介紹了關于MyBatis映射文件中parameterType與resultType用法的相關資料,需要的朋友可以參考下2023-04-04
Java8新特性之再見Permgen_動力節(jié)點Java學院整理
這篇文章主要介紹了Java8新特性之再見Permgen的相關知識,非常不錯,具有參考借鑒價值,需要的的朋友參考下吧2017-06-06
詳解Java編程中包package的內容與包對象的規(guī)范
這篇文章主要介紹了Java編程中包package的內容與包對象的規(guī)范,是Java入門學習中的基礎知識,需要的朋友可以參考下2015-12-12

