• 手动写一个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,再次运行

  • 相关阅读:
    BZOJ(2) 1041: [HAOI2008]圆上的整点
    BZOJ(1) 1003 [ZJOI2006]物流运输
    HDU 1285 确定比赛名次
    洛谷 P2951 [USACO09OPEN]捉迷藏Hide and Seek
    POJ 1201 Intervals
    2017 软件工程 个人作业——软件产品案例分析
    2017 软件工程 个人技术博客(α)
    在VS2017上对C++项目进行单元测试
    ASC47B borderless
    ASC47B borderless
  • 原文地址:https://www.cnblogs.com/jonsnow/p/6289039.html
Copyright © 2020-2023  润新知