Http协议和Servlet
1. Http协议
1.1 Http协议介绍
HyperText Transfer Protocol 超文本传输协议
目前网络传输中使用较多的HTTP协议版本是1.1,同样也有更高,安全性更好的Https协议
HTTP协议中使用比较多的传输方式
GET和POST
HTTP协议也是网络传输数据中非常重要的一种协议,在JavaWEB开发中,有对应的处理方式 HttpServlet 符合Http协议的Servlet程序
1.2 GET和POST区别
GET请求
通过URL统一资源定位符,借助于参数进行数据传输
1. 不安全
2. 传输数据有大小限制,数据量极小2KB
3. 传输速度较快
4. 一般用于查询操作
POST请求
通过Http协议【请求实体】来完成的
1. 较为安全
2. 传输数据大小无限制,可以用于视频,音频的传递
3. 传输效率较低
4. 一般用于修改,添加,删除操作
1.3 Http请求头
1.3.1 GET请求头
GET / HTTP/1.1
Host: www.baidu.com
Connection: keep-alive -- 保持连接状态
Cache-Control: max-age=0 -- 缓冲控制,有效时间
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36
Sec-Fetch-User: ?1
Accept: -- 支持的文件格式 text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Accept-Encoding: gzip, deflate, br -- 支持的压缩包形式
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7,zh-TW;q=0.6 -- 支持的语言
Cookie: -- Cookie 会话控制重要的部分
BIDUPSID=6FD12DC4D97AC410E92F68521466C3C7; PSTM=1572521607; BAIDUID=6FD12DC4D97AC4105596C2A2300A392A:FG=1; BD_UPN=12314753; BDUSS=3g3bE1TMUNPTkdIWjFvSEhZaVhFd09xOHNrQVJJY2NKZEdrWFpJUHF3VVhhLUpkRVFBQUFBJCQAAAAAAAAAAAEAAACSK~wVwfnT6tK2MTIzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABfeul0X3rpdY; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; MCITY=-268%3A; H_PS_PSSID=1442_21098_30210_30283_30479; H_PS_645EC=6ef9jYdhAbLRUgdg9gaeEjwED9XoaCnecMMS4PvIdAmC%2Fu9HBL1CvHaUzJIOKY9oif0k; BD_HOME=1; sug=3; sugstore=1; ORIGIN=0; bdime=0
GET 表示当前请求数据的方式
/ 请求的资源是哪一个 / 表示请求的主页index.html index.jsp...
例如: /search
HTTP/1.1 协议版本号
Host: www.baidu.com 请求服务器的主机地址,IP地址,域名,主机名
www.baidu.com ==> 39.156.66.14 网络运营商借助于DNS服务器,对域名进行解析操作,映射到对应的IP地址。相对于IP地址,域名更加便于用户记忆
1.3.2 POST请求头
POST /Day30_SL/test1 HTTP/1.1
Host: localhost:8080
cache-control: no-cache
Postman-Token: f980ff0f-159f-4c8b-8ffe-b2748a56f6c2
POST 表示当前请求方式为POST请求
/Day30_SL/test1 请求的资源为指定服务器上的/Day30_SL/test1
Host: localhost:8080 本机localhost地址映射以及Tomcat服务器8080端口号
【注意】
POST请求存在一个请求实体,实际上就是URL参数隐藏传递,在Servlet程序中可以获取到对应的参数
getParameter
getParamterMap
1.4 Http响应头
HTTP/1.1 200 OK
Bdpagetype: 2
Bdqid: 0xd1646f7f000276de
Cache-Control: private
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html;charset=utf-8
Date: Tue, 07 Jan 2020 02:56:34 GMT
Expires: Tue, 07 Jan 2020 02:56:34 GMT
Server: BWS/1.1
Set-Cookie: BDSVRTM=358; path=/
Set-Cookie: BD_HOME=1; path=/
Set-Cookie: H_PS_PSSID=1442_21098_30210_30283_30479; path=/; domain=.baidu.com
Strict-Transport-Security: max-age=172800
Traceid: 1578365794051576090615088307242849695454
X-Ua-Compatible: IE=Edge,chrome=1
Transfer-Encoding: chunked
HTTP/1.1 协议名字和版本号这里使用的是HTTP协议,版本号1.1
200 状态码 你最喜欢的 正常
OK 对应200状态码 网页当前请求无异常
Content-Type: text/html;charset=utf-8 内容类型 text/html 可视化文本的HTML文件,编码集为charset=utf-8
通过HttpServletResponse对象设置setContextType
Server: BWS/1.1 服务器名字和对应的版本号
Set-Cookie 设置Cookie信息,可以用于自动登录,数据保存,信息验证...
1.5 Http和HttpServlet
Http是一个网络数据传输协议,存在请求头和响应头
HttpServlet是符合JavaEE规范,并且符合Http协议要求的Servlet(Server applet)基类
Http请求头是带有数据传递到JavaWEB后台,对应的类HttpServletRequest,在Request中包含了Http请求头的所有内容
请求参数,请求IP地址,请求主机名,请求资源名,请求URL,请求数据长度,请求时间...
HTTP响应头是从服务器端发送数据给予客户端,对应的类HttpServletResponse,在Response类对应了HTTP响应头的所用内容
状态码,数据内容格式,响应内容,Cookie数据....
2. Servlet 【重点】
2.1 Servlet的三种创建方式
2.1.1 遵从Servlet接口
package com.qfedu.b_servlet;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/CreateServlet1")
public class CreateServlet1 implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
servletResponse.getWriter().append("Servlet Program implements interface Servlet
");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
2.1.2 继承abstract class GenericServlet
package com.qfedu.b_servlet;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/CreateServlet2")
public class CreateServlet2 extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
servletResponse.getWriter().append("Servlet Program extends abstract class GenericServlet
");
}
}
2.1.3 继承HttpServlet类[常用]
package com.qfedu.b_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;
@WebServlet("/CreateServlet3")
public class CreateServlet3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().append("Servlet Program extends class HttpServlet
");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.1.4 三种方式的对比
继承HttpServlet类完成自定义Servlet程序,是非常方便。避免了和【业务逻辑】无关紧要的操作,init,servletConfig,destroy...
interface Servlet
--| abstract class GenericServlet
----| class HttpServlet
------| 自定义Servlet程序
完成一个BaseServlet类,进一步简化Servlet操作流程,完完全全只考虑业务逻辑问题
2.2 Servlet URL匹配规则
2.2.1 web.xml方式
<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_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>URLPattenservlet-name>
<servlet-class>com.qfedu.b_servlet.URLPattenservlet-class>
servlet>
<servlet-mapping>
<servlet-name>URLPattenservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
2.2.2 @WebServlet方式
@WebServlet("/url") 最常用的方式,精确匹配
@WebServlet(value = "/url") 同上
@WebServlet(urlPatterns = {"/url", "/saolei"}) 精确匹配多种情况
@WebServlet("*.do") 模糊匹配
2.3 Servlet配置
2.3.1 web.xml方式
<servlet>
<servlet-name>ConfigServlet1servlet-name>
<servlet-class>com.qfedu.b_servlet.ConfigServlet1servlet-class>
<init-param>
<param-name>nameparam-name>
<param-value>saoleiparam-value>
init-param>
<init-param>
<param-name>ageparam-name>
<param-value>16param-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>ConfigServlet1servlet-name>
<url-pattern>/config1url-pattern>
servlet-mapping>
2.3.2 @WebServlet方式
属性名 |
类型 |
属性描述 |
name |
String |
Servlet的名字,对应servlet-name标签 |
value |
String |
Servlet程序对于的url,对应url-pattern标签,但是不能和urlPatterns共同存在 |
urlPatterns |
String[] |
Servlet程序对于的url组合,对应url-pattern标签,可以存放对应当前servlet URL对应的名字【重点】 |
loadOnStarUp |
int |
Serlvet程序的加载过程,是否服务器启动自动加载 |
initParams |
WebInitParam[] |
Servlet程序的初始化参数,数据类型是键值对方式【重点】 |
displayName |
String |
Serlvet显式的名字,对应displayname标签 |
description |
String |
Servlet的描述信息,对应description标签 |
@WebServlet(name = "ConfigServlet2",
urlPatterns = {"/config2", "/longlong"},
initParams = {@WebInitParam(name = "xingming", value = "saolei"),
@WebInitParam(name = "nianling", value = "16")},
loadOnStartup = 1)
public class ConfigServlet2 extends HttpServlet {
public ConfigServlet2() {
System.out.println("ConfigServlet2 Loading...");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletConfig servletConfig = this.getServletConfig();
System.out.println(servletConfig.getInitParameter("xingming"));
System.out.println(servletConfig.getInitParameter("nianling"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.4 Servlet从前端数据数据的方式
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎登录title>
head>
<body>
<form action="login" method="post">
姓名:<input type="text" name="name"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="提交">
form>
body>
html>
package com.qfedu.c_getdata;
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("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String password = req.getParameter("password");
System.out.println(name + ":" + password);
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().append("登陆成功
");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.4.1 解决HttpServletRequest对象中文乱码问题
req.setCharacterEncoding("utf-8");
2.4.2 解决HttpServletResponse对象中文乱码问题
resp.setContentType("text/html;charset=utf-8");