JSP&Servlet学习笔记----第1/2章

时间:2022-04-29 17:23:57

HTML(HyperText Markup Language):超文本标记语言

HTTP(HyperText Transfer Protocol):超文本传输协议

URL(Uniform Resource Locator):统一资源定位符,以文字的方式来说明因特网上的资源如何取得。

URN(Uniform Resource Name):代表某个资源独一无二的名称,如图书的ISBN。

URI(Uniform Resource Identifier):URL和URN是URI的子集。

一个简单的html范例程序:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML范例</title>
</head>
<body>
<form method="get" action="hello.do" name="sample">
姓名:
<input type="text" name="name">
<br />
<button>发送</button>
</form>
</body>
</html>
HTML学习资源: http://www.w3school.com.cn/html/index.asp

HTTP:指架构在TCP/IP之上应用层的一种协议。它的两个特点:

1、无状态(stateless)通信协议。(无记忆性)

2、基于请求(request)/响应(response)模型。

客户端对服务器发出一个取得资源的请求,服务器将要求的资源响应给客户端,每次的联机只作一次请求/响应,是一种很简单的通信协议,没有请求就没有响应。

在HTTP 协议下,服务器是个健忘的家伙,服务器响应客户端之后,就不会记得客户端的信息,更不会去维护与客户端有关的状态,因此HTTP又称为无状态的通信协议。

浏览器在使用http发送请求,最重要的就是GET和POST。

GET:就是向服务器取得指定的资源。JSP&Servlet学习笔记----第1/2章

POST请求:就是请求时发布(POST)信息给服务器。JSP&Servlet学习笔记----第1/2章

对于两者如何进行选择?

1、get方式请求参数长度是有限的,过长的或者如文件上传应该使用post请求。

2、get请求参数会出现在地址栏。

3、get请求纯粹是为了取得资源,而不改变服务器上的资源的状态。而post相反。

对于java,JVM(java virtual machine)是java程序唯一认得的操作系统,其可执行文件为.class文件。

对于JSP/Servlet,Web容器是JSP/Servlet唯一认得的http服务器。

URL编解码:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* Created by N3verL4nd on 2017/1/2.
*/


public class HelloWorld
{
public static void main(String[] args) throws UnsupportedEncodingException {
System.out.println(URLEncoder.encode("http://www.baidu.com", "UTF-8"));
System.out.println(URLDecoder.decode("%3A", "UTF-8"));
}
}
URL编码针对的字符是UTF-8编码的8个位数值。

对于ascii字符使用1个字节,非ascii如中文使用3个字节。

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* Created by N3verL4nd on 2017/1/2.
*/
public class HelloWorld
{
public static void main(String[] args) throws UnsupportedEncodingException {
System.out.println(URLEncoder.encode("我", "UTF-8"));
System.out.println(URLDecoder.decode("%E6%88%91", "UTF-8"));
}
}
HTTP规范下的URL编码,并不限使用UTF-8,例如在一个BIG5网页中,若窗体使用get发送中文,则是使用BIG5编码的参数。

System.out.println(URLEncoder.encode("", "BIG5"));

第一个Servlet程序(打印http header):

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;
import java.util.Enumeration;

/**
* Created by N3verL4nd on 2017/1/4.
*/
@WebServlet(name = "testServlet",urlPatterns = {"/test.do"})
public class testServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>TEST</title>");
out.println("</head>");
out.println("<body>");

out.println("<h1>Hello World</h1>");

out.println("</body>");
out.println("</html>");
out.close();
}
}

/test.do
/Servlet
/Servlet/test.do host:localhost:8080
connection:keep-alive
upgrade-insecure-requests:1
user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
accept-encoding:gzip, deflate, sdch, br
accept-language:zh-CN,zh;q=0.8
cookie:JSESSIONID=CDD8329D5BB881383911AC4CFAB4A159; Idea-e643fc73=b918ddfe-f8fa-43a0-b608-e1670a29b80a

@WebServlet(name = "testServlet",urlPatterns = {"/test.do"})
这表示该Servlet名称为testServlet,当请求的URL是/test.do,如http://localhost:8080/Servlet/test.do就会由testServlet处理。
HttpServletRequest

代表请求对象,封装了HTTP请求信息。

HttpServletResponse
代表对客户端的响应。

Servlet的编译(需servlet-api.jar。位于D:\Tomcat\apache-tomcat-9.0.0.M15\lib):

JSP&Servlet学习笔记----第1/2章

JSP&Servlet学习笔记----第1/2章

一个简易的Servlet程序对应的文件目录结构如下:

E:\MyDocument\Desktop\jspRun\web\WEB-INF>tree /f
文件夹 PATH 列表
卷序列号为 025427CF 32D1:7CF3
E:.
│  web.xml

├─classes
│      testServlet.class

└─lib


E:\MyDocument\Desktop\jspRun\web\WEB-INF>
部署: JSP&Servlet学习笔记----第1/2章

将web.war拷贝到webapps目录下(D:\Tomcat\apache-tomcat-9.0.0.M15\webapps )

运行bin目录下的startup.bat

JSP&Servlet学习笔记----第1/2章

servlet、genericservlet、httpservlet之间的关系:

JSP&Servlet学习笔记----第1/2章

package javax.servlet;
import java.io.IOException;
public interface Servlet {
public void init(ServletConfig config) throws ServletException;
public ServletConfig getServletConfig();
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
public String getServletInfo();
public void destroy();
}
package javax.servlet;import java.io.IOException;import java.util.Enumeration;public abstract class GenericServlet implements Servlet, ServletConfig,        java.io.Serializable {    private static final long serialVersionUID = 1L;    private transient ServletConfig config;    public GenericServlet() {        // NOOP    }    @Override    public void destroy() {        // NOOP by default    }    @Override    public String getInitParameter(String name) {        return getServletConfig().getInitParameter(name);    }    @Override    public Enumeration<String> getInitParameterNames() {        return getServletConfig().getInitParameterNames();    }    @Override    public ServletConfig getServletConfig() {        return config;    }    @Override    public ServletContext getServletContext() {        return getServletConfig().getServletContext();    }    @Override    public String getServletInfo() {        return "";    }    @Override    public void init(ServletConfig config) throws ServletException {        this.config = config;        this.init();    }    public void init() throws ServletException {        // NOOP by default    }    public void log(String msg) {        getServletContext().log(getServletName() + ": " + msg);    }    public void log(String message, Throwable t) {        getServletContext().log(getServletName() + ": " + message, t);    }    @Override    public abstract void service(ServletRequest req, ServletResponse res)            throws ServletException, IOException;    @Override    public String getServletName() {        return config.getServletName();    }}
package javax.servlet.http;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.lang.reflect.Method;import java.text.MessageFormat;import java.util.Enumeration;import java.util.ResourceBundle;import javax.servlet.DispatcherType;import javax.servlet.GenericServlet;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public abstract class HttpServlet extends GenericServlet {    private static final long serialVersionUID = 1L;    private static final String METHOD_DELETE = "DELETE";    private static final String METHOD_HEAD = "HEAD";    private static final String METHOD_GET = "GET";    private static final String METHOD_OPTIONS = "OPTIONS";    private static final String METHOD_POST = "POST";    private static final String METHOD_PUT = "PUT";    private static final String METHOD_TRACE = "TRACE";    private static final String HEADER_IFMODSINCE = "If-Modified-Since";    private static final String HEADER_LASTMOD = "Last-Modified";    private static final String LSTRING_FILE =        "javax.servlet.http.LocalStrings";    private static final ResourceBundle lStrings =        ResourceBundle.getBundle(LSTRING_FILE);    public HttpServlet() {        // NOOP    }    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 long getLastModified(HttpServletRequest req) {        return -1;    }    protected void doHead(HttpServletRequest req, HttpServletResponse resp)        throws ServletException, IOException {        if (DispatcherType.INCLUDE.equals(req.getDispatcherType())) {            doGet(req, resp);        } else {            NoBodyResponse response = new NoBodyResponse(resp);            doGet(req, response);            response.setContentLength();        }    }    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);        }    }    ...}
Servlet接口:定义了Servlet应当有的基本行为,所有的Servlet程序都必须实现Servlet接口(GenericServlet或者HttpServlet)。

GenericServlet:实现了Servlet接口,没有规范任何与HTTP相关的方法,而是由继承它的HttpServlet来定义。

HttpServlet的service方法流程:

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);
}
}
当请求到来时,容器会调用Servlet的service()方法。