创建一个web项目
创建一个类,继承HttpServlet:
package com.demo.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet类:
* 1.让新建的类继承HttpServlet(把Servlet类交给服务器实例化)
* 2.在web.xml中配置servlet 和servlet-mapping
* 客户端提交请求的方式
* GET:不安全,提交数据显示到地址栏上
* POST:安全,提交的数据封装到form中的header中
* 3.父类中的service方法分发处理调用doGet和doPost方法
* 4.Servlet生命周期
* 实例化(web容器) -> 调用init -> 调用service -> 销毁(destroy,服务器正常关闭时调用)
* @author Administrator
*
*/
public class MyServlet extends HttpServlet{
public MyServlet() {
System.out.println("xxx");
}
//控制表单提交方式的分发处理操作
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("service");
//获取客户端提交的请求方式
String method = req.getMethod();
if ("GET".equalsIgnoreCase(method)) {
doGet(req, resp);
} else if ("POST".equalsIgnoreCase(method)) {
doPost(req, resp);
}
}
@Override
public void init() throws ServletException {
System.out.println("初始化Servlet");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("GET");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("POST");
}
@Override
public void destroy() {
System.out.println("销毁");
}
}
在web.xml中配置Servlet 和Servlet映射
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletDetail</display-name>
<!-- Servlet配置 -->
<servlet>
<servlet-name>MyServlet</servlet-name>
<!--
//服务器端使用反射创建类的实例
Tomcat端 -> JVM:Class.forName("com.demo.servlet.MyServlet").newInstance();
-->
<servlet-class>com.demo.servlet.MyServlet</servlet-class>
</servlet>
<!-- Servlet映射 -->
<servlet-mapping>
<!-- 与Servlet配置中的servlet-name配对 -->
<servlet-name>MyServlet</servlet-name>
<!--
映射路径
<form action="testServlet" method="post">
-->
<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
</web-app>