一. 实现Servlet接口(service()方法)
二. 继承HttpServlet类(覆写doGet()和doPost()方法)
一. 实现Servlet接口(service()方法)
1 在src下新建一个HelloServlet.java文件
2 编写Servlet代码
package com.itheima.servlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class HelloServlet implements Servlet {
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
System.out.println("helloServlet...");
}
@Override
public void destroy() {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
}
}
3 配置Servlet(web.xml)
HelloServlet
com.itheima.servlet.HelloServlet
HelloServlet
/HelloServlet
4 在地址栏输入http://localhost:8080/ServletTest01/HelloServlet
二. 继承HttpServlet类(覆写doGet()和doPost()方法)
1 在src下新建一个HiServlet.java文件
2 编写servlet代码(覆写doGet()和doPost()方法)
package com.itheima.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HiServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
System.out.println("get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
System.out.println("post...");
}
}
3 配置Servlet(web.xml)
HiServlet
com.itheima.servlet.HiServlet
HiServlet
/HiServlet
4 在地址栏输入http://localhost:8080/ServletTest01/HiServlet