继承HttpServlet实现Servlet程序

通过继承HttpServlet实现Servlet程序

servlet通常通过HTTP接受和响应来自Web客户端的请求。要实现此接口编写一个扩展javax.servlet.GenericServlet的一般servlet,或者编写一个扩展javax.servlet.http.HttpServlet的HTTPservlet,来实现servlet程序。

1.编写一个类去继承HttpServlet类

package com.sammery.Servlet;

import javax.servlet.http.HttpServlet;

/**
 * @Author: SammeryD
 * @Discryption: 通过继承HttpServlet实现Servlet程序
 * @Date: Created in 11:37 2020/8/16
 */
public class HelloServlet extends HttpServlet {
}

2.根据业务需要重写doGet或doPost方法

package com.sammery.Servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: SammeryD
 * @Discryption: 通过继承HttpServlet实现Servlet程序
 * @Date: Created in 11:37 2020/8/16
 */
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet 的doGet方法");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet 的doPost方法");
    }
}

3.到web.xml中配置Servlet程序


<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>
        
        <servlet-name>HelloServletservlet-name>
        
        <servlet-class>com.sammery.Servlet.HelloServletservlet-class>
    servlet>

    
    <servlet-mapping>
        
        <servlet-name>HelloServletservlet-name>
        
        <url-pattern>/hellourl-pattern>
    servlet-mapping>
web-app>

4.建立一个html页面来访问服务器


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
	
    <form action="http://localhost:8080/HelloServlet/hello" method="POST">
        <input type="submit" >
    form>
body>
html>

5.启动tomcat服务器 HTML页面method方法依次为POST 、GET

继承HttpServlet实现Servlet程序_第1张图片
继承HttpServlet实现Servlet程序_第2张图片

你可能感兴趣的:(servlet,servlet,tomcat,java)