一、做一个类,派生自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"+"\t"+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,再次运行