zoukankan      html  css  js  c++  java
  • 手动写一个Servlet

    一、做一个类,派生自HttpServlet

    1.导两个包

    javax.servlet.*;

    javax.servlet.http.*

    2.重写两个方法doGet,doPost

    打开tomcat中的servlet-api.jar包,复制这两个方法的实现。

    package com.itnba.maya.servlet;
    import java.io.IOException;
    
    import javax.servlet.*;//导入包
    import javax.servlet.http.*;//导入包
    
    
    public class TestServlet extends HttpServlet{//类的派生
        public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{//重写方法
            String s=request.getParameter("id");
            response.getWriter().write("this is first servlet"+"	"+s);
        }
        public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException{//重写方法
            doGet(request, response);
        }
    
    }

    二、设置web.xml配置文件

    找到tomcat/conf/web.xml,把根和相关的元素复制过去
    <servlet></servlet>
    <servlet-mapping></servlet-mapping>
    调整元素的内容。

    <?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_3_1.xsd"
      version="3.1">
    
    
        <servlet>
            <servlet-name>first</servlet-name>
            <servlet-class>com.itnba.maya.servlet.TestServlet</servlet-class>
        </servlet>
        <servlet-mapping>//映射servlet
            <servlet-name>first</servlet-name>
            <url-pattern>/ttt</url-pattern>
        </servlet-mapping>
        
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
    
    </web-app>

    执行结果

    在地址栏中输入ttt?id=hello,再次运行

  • 相关阅读:
    Leetcode Array 4 Median of Two Sorted Arrays
    vscode Python Pylint(代码检测插件)
    Leetcode Array 1 twoSum
    mysql 配置 安装和 root password 更改
    vscode 编译调试c/c++的环境配置
    chm文件打不开的解决办法
    A + B Problem II
    欢天喜地七仙女——代码规范与计划
    欢天喜地七仙女——项目系统设计与数据库设计
    欢天喜地七仙女——团队Gitee实战训练
  • 原文地址:https://www.cnblogs.com/jonsnow/p/6289039.html
Copyright © 2011-2022 走看看