HttpServlet

HttpServlet的原理

 1 HttpServlet抽象类中的(部分)方法
 2 
 3 HttpServlet extends GenericServlet{
 4  void service(ServletRequest request,ServletResponse responce){
 5    *强转两个参数为http协议相关的类型。
 6    *调用本类的servic(HttpServletRequest, HttpServletResponse)方法
 7  }
 8 
 9 
10  void service(HttpServletRequest,HttpServletResponse)-->参数已经是Http协议相关的,使用起来就更加方便。
11    *它会通过request得到当前请求的请求方式,例如:GET或POST
12    *根据请求方式在调用doGet()或doPost()方法
13 
14 
15  void doGet(){...} -->重写
16  void doPost(){...} -->重写
17 
18 }

原理图:

源码:

MyHttpServlet.java

 1 package one.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 public class MyHttpServlet extends HttpServlet {
11     //**公有的请求方法
12     @Override
13     public void doPost(HttpServletRequest req, HttpServletResponse resp)
14             throws ServletException, IOException {
15         //我们只需重写该方法即可
16         System.out.println("doPost()...");
17     }
18 }

 

如果在浏览器的地址栏中输入http://localhost:8080/XJS_Servlet1/MyHttpServlet 然后请求,会出现下图:

解决方法:在WebRoot文件下创建一个login.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 </head>
 7 <body>
 8         <!-- 路径要求:“/”开头+/项目名+/servlet路径(web.xml中url-pattern) -->
 9         <form action="/XJS_Servlet1/MyHttpServlet" method="post">
10             <input type="submit" value="提交"/>
11         </form>
12 </body>
13 </html>

 

 然后中浏览器地址栏中输入http://localhost:8080/XJS_Servlet1/login.html  再点击提交按钮,以post的方式请求服务器

请求一次,执行一次doPost()方法,结果如下:

doPost()...
doPost()...

 

自己直接创建一个servlet:直接继承了HttpServlet,还重写doGet()和doPost()方法

然后Next

然后就会自动为我们再web.xml文件中配置该FServlet的路径

 

 

posted @ 2019-04-24 11:02  微微亮  阅读(146)  评论(0编辑  收藏  举报