转自:https://blog.csdn.net/m0_38039437/article/details/75264012
一、HttpServlet简介
1、HttpServlet是GenericServlet的子类,又是在GenericServlet的基础上做了增强。
2、HttpServlet方法
二、HTTP实现doGet或doPost请求项目介绍
1、通过实现doGet请求和doPost请求实例来了解内部的工作原理。
2、doGet请求和doPost请求实例代码介绍:
A:创建一个Servlet类继承HttpServlet类
B:在index.jsp页面创建一个超链接请求
3、doGet请求和doPost请求实例实施介绍:
A、创建一个webproject项目。
B、创建一个Servlet类的名称为HttpServ继承HttpServlet类同时覆写doGet方法和doPost方法。
1、
2、
3、配置web.xml文件
4、创建Servlet代码展示
package httpserve;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpServ extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("发送get请求。。。。。。。。。。。");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/html;charset=UTF-8");
System.out.println("发送post方法。。。。。。。。。。");
}
}
5、web.xml配置文件代码展示
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>HttpServ</servlet-name>
<servlet-class>httpserve.HttpServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HttpServ</servlet-name>
<url-pattern>/http</url-pattern>
</servlet-mapping>
</web-app>
C、在index.jsp页面创建一个超链接请求
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page. <br>
<a href="http://localhost:8080/test06/http">get请求1</a><br/>
<!-- 对于一个html页面来说,如果没有以http开始,则默认的前面会加上
协议类型://目前这个页面所在的服务器:目前端口/目前项目/你给的这个名称 -->
<a href="http">get请求2</a><hr/>
<form method = "post" action="http">
<input type="submit" value="提交"/>
</form>
</body>
</html>