1.创建一个类实现servlet接口并重写servlet中的抽象方法
package com.atshangqiu.servlet;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/*
servlet的生命周期
1.执行Servlet构造器方法
2.执行init初始化方法
第一第二步是在第一次访问的时候创建Servlet程序会调用
3.执行service方法
第三步每次访问都会调用
4.执行destroy销毁方法
第四步,在web工程停止的时候调用
*/
public class HelloServlet implements Servlet {
public HelloServlet() {
System.out.println("构造器方法1");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("初始化方法2");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service方法3");
//类型转换(因为他有getMethod()方法)
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//获取请求的方式
String method = httpServletRequest.getMethod();
System.out.println(method);
if("GET".equals(method)){
doget();
}
if ("POST".equals(method)){
dopost();
}
}
public void doget(){
System.out.println("get请求");
}
public void dopost(){
System.out.println("post请求");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("销毁方法4");
}
}
2.配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
version="4.0">
<!-- servlet标签给Tomcat配置Servlet程序-->
<servlet>
<!--servlet标签Servlet程序起一个别名(一般是类名) -->
<servlet-name>HelloServlet</servlet-name>
<!--servlet-class是servlet程序的全类名 -->
<servlet-class>com.atshangqiu.servlet.HelloServlet</servlet-class>
</servlet>
<!--servlet-mapping 标签给servlet程序配置访问地址 -->
<servlet-mapping>
<!--servlet-name 标签的作用是告诉服务器,我当前配置的地址给哪个Servlet程序使用 -->
<servlet-name>HelloServlet</servlet-name>
<!--url-pattern 标签配置访问地址
/斜杠在服务器解析的时候,表示地址为http://ip:port/工程路径
/hello表示地址为http://ip:port/工程路径/hello
-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
3.创建一个简单的a.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/06servlet/hello" method="post">
<input type="submit" value="提交">
</form>
</body>
</html>
4.在配置部署tomcat及有servlet-api.jar包的情况下在浏览器中运行(地址:http://localhost:8080/06servlet/a.html)并提交get或post方法的情况下运行结果如下:
5.结束tomcat服务器之后: