在三个请求中,HttpServlet用的最多,最简单的,继承javax.servlet.http.HttpServlet类,类名说明了他与http协议有关,他有俩种用的最多的请求方式,doGet()和DoPost()
- httpservlet类下有一个方法service()方法
protected void service(HttpServletRequest request,HttpServletReponse reponse)
throws ServletException,IOException{
}
-servlet接口中的生命周期方法
public void service(ServletRequest request,ServletReponse reponse)
throws ServletException,IOException{
}
我们不需要重写public void service(ServletRequest request,ServletReponse reponse)
throws ServletException,IOException{
}这个方法,因为tomcat会自动将ServletRequest request,ServletReponse reponse转化成HttpServletRequest request,HttpServletReponse reponse(强转成与http有关的类型),tomcat调用生命周期方法,然后强制转化成http类型,然后调用这个含有http类型的方法


类
package baoming;
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 CServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
System.out.println("doPost()....");
}
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/LxServlet/CServlet" method="post">
<input type="submit" value="提交">
</form>
</body>
</html>
xml
<?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_4_0.xsd"
version="4.0">
<display-name>LxServlet</display-name>
<welcome-file-list>
<!--<welcome-file>index.jsp</welcome-file>-->
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LxServlet</servlet-name>
<servlet-class>baoming.LxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LxServlet</servlet-name>
<url-pattern>/LxServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>CServlet</servlet-name>
<servlet-class>baoming.CServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CServlet</servlet-name>
<url-pattern>/CServlet</url-pattern>
</servlet-mapping>
</web-app>
页面


网友评论