1.1、用官方的話解釋:
Servlet是oracle公司提供的一門用於開發動態web資源的技術,屬於javaEE體系中的一種核心規範。
通俗解釋一下:就是我們開發人員所編寫的一個類,必須直接或者間接實現這個javaEE的核心規範,也就是實現Servlet介面,因為這種類產生的物件可以被瀏覽器存取到,因此稱之為Servlet,並且javaEE中規定了只有Servlet的實現類產生的物件才可以被瀏覽器存取,就是Servlet.(也就是說這個類要直接或者間接實現了Servlet介面)
package com.briup.web;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FirstWay implements Servlet {
public FirstWay() {
System.out.println("物件建立了");
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("我是init:我被呼叫了");
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("我是service,我被呼叫了");
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("我是destory:我被呼叫了");
}
}
那麼,一個滿足servlet的類已經建立好了,接下來丟擲疑問
對於整個動態web專案而言,web.xml是最先載入的組態檔,所以在web.xml的方式設定
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>firstWay</display-name>
<servlet>
<servlet-name>FirstWay</servlet-name>
<servlet-class>com.briup.web.FirstWay</servlet-class>
<!-- <load-on-startup>1</load-on-startup> -->
</servlet>
<servlet-mapping>
<servlet-name>FirstWay</servlet-name>
<url-pattern>/FirstWay</url-pattern>
</servlet-mapping>
</web-app>
解釋:
1、servlet-name:見名知意:servlet的名字,注意要與下面你設定對映的名字對應
2、serlvet-class:serlvet的全限定名
3、load-on-startup:是否在tomcat啟動的時候就建立servlet物件,傳入一個大於0的整數‘’(預設是瀏覽器第一次請求的時候建立servlet物件)
4、servlet-mapping:見名知意,設定瀏覽器的存取對映
5、servlet-name:於上面的對應
6、url-pattern:瀏覽器的存取對映(假設預設是本機的話,且tomcat的埠號為8080,那麼瀏覽器存取這個servlet的路徑為:localhost:8080/專案名/FirstWay)
有了這些基礎,讓我們存取看看;
@WebServlet(value ="對映路徑")
public Fristservlet implement Servelt {
}
通過這個註解也可以設定,是否在啟動伺服器的時候就建立物件,這裡就不演示了,
注意:(一旦使用了註解的方式告訴tomcat如果建立某個物件,就不能在web.xml裡面再對這個servlet進行存取設定了)
有了前面的解釋,直接上程式碼然後再分析
package com.briup.web;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet(value = "/secondWay")
public class SecondWayCreate extends GenericServlet {
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("呼叫了service方法");
}
}
public abstract class GenericServlet implements Servlet, ServletConfig,
可知,這是個抽線類,是servlet介面的實現類,那麼GenericServlet間接 實現了servlet介面,
與第一種方式相比:開發者不是必須將一些介面中不必要的方法實現,可以具有選擇性,減少了程式碼量。然而並沒有上面ruan用,就是裝b而已
直接上程式碼
package com.briup.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value = "/ThreeWayCreate")
public class ThreeWayCreate extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}
通過以上程式碼,可能就有小夥伴要問了
不是說servlet要直接或者間接實現servlet介面嗎,不是說瀏覽器每請求一次就要呼叫一次service方法嗎?方法在哪呢?這不是與前面理論衝突了嗎?
我們繼續看原始碼,原始碼才是道理
我在下面值列舉原始碼裡面比較核心的部分,需要理解更加深入瞭解的小夥伴,直接去看原始碼,tomcat是開源的
public abstract class HttpServlet extends GenericServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
}
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
// Invalid date header - proceed as if none was set
ifModifiedSince = -1;
}
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
/*
* Sets the Last-Modified entity header field, if it has not
* already been set and if the value is meaningful. Called before
* doGet, to ensure that headers are set before response data is
* written. A subclass might have set this header already, so we
* check.
*/
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
}
}
分析:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
// Invalid date header - proceed as if none was set
ifModifiedSince = -1;
}
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
通過傳過來的HttpRequest物件,判斷請求方式,通過請求方式,決定呼叫哪個方法(如果請求方式是post方式,那麼就會呼叫doPost(HttpRequest req,HttpRestpone Res)方法)
優點:
注意點:瀏覽器發起請求呼叫的一定是servlet種的service方法;
有任何錯誤或者見解希望各位讀者指出互相進步,相互學習。