通过继承HttpServlet类实现servlet程序
通过继承HttpServlet类实现servlet程序
一般在实际项目开发中,都是使用继承HttpServlet类的方式去实现servlet程序
步骤如下:
1、编写一个类去继承HttpServlet类。
2、根据业务需要重写doGet()方法或doPost()方法
3、到web.xml中配置servlet程序的访问地址。
servlet程序代码:
package LWB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet2 extends HttpServlet {
//doGet()在get请求的时候调用
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("helloservlet2的doGet方法");
}
//doPost()在post请求的时候调用
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("helloservlet2的doPost方法");
}
}
web.xml配置文件:
<servlet>
<servlet-name>HelloServlet2</servlet-name>
<servlet-class>LWB.HelloServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet2</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>