目录
通过继承HttpServlet实现Servlet程序
实际开发中,一般使用继承HttpServlet类的方法去实现Servlet程序。
步骤:
1、编写一个类去继承HttpServlet类
2、根据业务需要重写doGet或doPost方法
3、到web.xml中配置Servlet程序
1、编写一个类,Alt+insert快捷键重写里一些需要的方法
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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
System.out.println("HelloServlet2的 get请求");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
System.out.println("HelloServlet2的 post请求");
}
}
到web.xml文件中配置访问路径
<servlet>
<servlet-name>HelloServlet2</servlet-name>
<servlet-class>com.servlet.HelloServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet2</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
将表单中的访问地址hello改变为hello2
运行提交后:
使用idea创建Servlet程序
选择要实现的包→Servlet程序
配置信息
勾选上用的就是3.0的注解配置
只需要在web.xml中加上路径即可(其他的已经自动生成了)
<servlet-mapping>
<servlet-name>HelloServlet3</servlet-name>
<url-pattern>/hello3</url-pattern>
</servlet-mapping>
Servlet的继承体系
doGet和dopost源码
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_get_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_post_not_supported");
this.sendMethodNotAllowed(req, resp, msg);
}
servlet方法部分源码
protected void service(HttpServletR