-----------------siwuxie095
在 LoginServlet 中,右键->Open Type Hierarchy(或 使用快捷键:F4)
在Type Hierarchy 视图中显示了 LoginServlet 的继承关系,点击 HttpServlet
在下方,可以看到 HttpServlet 有许多以 do 开头的方法,用来处理不同的HTTP 请求
HTTP 请求的类型(HTTP METHOD):
OPTIONS
用于返回服务器支持的 HTTP 方法
POST
用于将指定的资源提交到服务器进行处理
GET
用于从指定的资源请求数据
PUT
用于上传指定的资源
DELETE
用于删除指定的资源
HEAD
与 GET 相同,但返回的只是 HTTP 的报头,不会返回文档的主体
TRACE
用于返回TRACE请求的所有头信息
一般在浏览器中输入网址访问资源都是通过GET 方法
在表单提交时,可以通过 method 属性指定提交方式为GET 或 POST,
默认的提交方式是 GET。对于 HTTP 的几种提交方式,基本上只会用到
GET 和 POST
GET 与 POST 的区别:
操作
GET
POST
刷新
不会重复提交
重复提交
数据长度
2048 个字符
无限制
数据类型
ASCII 字符
无限制
可见性
URL 中可见
URL 中不可见
安全性
低
高
在 Servlet 中分别处理 Get 请求和 POST 请求,将 LoginServlet.java 改为:
package com.siwuxie095.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// LoginServlet 继承自 HttpServlet
public class LoginServlet extends HttpServlet {
/**
* 用于序列化和反序列化的 ID
*/
private static finallong serialVersionUID = -7740192486028671728L;
// /**
// * 先覆盖父类 HttpServlet 的service()方法,
// * 右键->Source->Override/Implement methods
// * 选择 HttpServlet 的 service()
// * 在 service() 中编写业务处理逻辑
// */
// @Override
// protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String userName=req.getParameter("uname");
// String password=req.getParameter("upwd");
// System.out.println("用户名:"+userName);
// System.out.println("密码:"+password);
// }
//覆盖父类 HttpServlet 的 doGet() 方法
@Override
protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("===== doGet =====");
//在 doGet() 方法里调用 doPost() 方法
//这样,GET请求和POST请求可以共用一套处理逻辑
doPost(req, resp);
}
//覆盖父类 HttpServlet 的 doPost() 方法
@Override
protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("===== doPost =====");
String userName=req.getParameter("uname");
String password=req.getParameter("upwd");
System.out.println("用户名:"+userName);
System.out.println("密码:"+password);
}
}
访问:localhost:8080/MyServlet/login.jsp,分别输入siwuxie095 和 8888
如果使用GET 方式提交,则跳转的 URL 为:
localhost:8080/MyServlet/loginServlet?uname=siwuxie095&upwd=8888
如果使用POST 方式提交,则跳转的 URL 为:
localhost:8080/MyServlet/loginServlet
LoginServlet 能够区分不同的请求类型,分别进入 doGet() 或 doPost() 方法
这是因为在父类HttpServlet 的 service() 方法中,能够根据请求的类型,分别
调用对应的 doGet()、doPost() 等方法
「使用快捷键:Ctrl+O,打开 Outline 视图,找到 service() 方法」
而这些方法的实现,是在具体的子类中进行实现的
HttpServlet 这样的设计是一种非常常用的设计模式:模板方法模式
即在一个方法中定义一个算法的骨架,然后将某些步骤推迟到子类中去实现
「模板方法允许子类重新定义算法的某些步骤,而不改变方法的结构」
打开Outline 视图(大纲视图)的方法:
(1)右键->Quick Outline(快捷键:Ctrl+O)
(2)Window->Show View->Outline
【made by siwuxie095】
