2.2 配置及源码
在查看servlet源码的过程中,发现HttpServlt中请求最终都会指向错误,因此必须继承HttpServlet重写对应的请求方法。
报错代码:
首先在web.xml中配置servlet的路径及映射,如下:
继承了HttpServlet类的子类代码,直接使用父类的doGet
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("test 的 servlet");
super.doGet(req, resp);
}
响应结果:
修改web.xml中servlet类为重写了doGet方法的类
配置:
代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello Servlet!</h1>");
out.println("Method: " + request.getMethod());
out.println("Request URI: " + request.getRequestURI());
out.println("Protocol: " + request.getProtocol());
out.println("PathInfo: " + request.getPathInfo());
out.println("Remote Address: " + request.getRemoteAddr());
out.println("</body>");
### 最后
> **笔者已经把面试题和答案整理成了面试专题文档,有想获取到借鉴参考的朋友:点赞关注后,[戳这里即可免费领取](https://gitee.com/vip204888/java-p7)**
![image](https://img-blog.csdnimg.cn/img_convert/24665a3f512164a3f895b0e4f4726b90.png)
![image](https://img-blog.csdnimg.cn/img_convert/d17764a544b93f81a76f27a12d7b603d.png)
![image](https://img-blog.csdnimg.cn/img_convert/047f1898e0b3432ffaabe55912dda465.png)
![image](https://img-blog.csdnimg.cn/img_convert/90e4b9e81ed9f702356d96a16d1e575b.png)
![image](https://img-blog.csdnimg.cn/img_convert/9774a4f7ca0f235e3ac51c5afdfa2452.png)
.(img-F7OKa9yu-1628356034082)]
[外链图片转存中...(img-CnVeY0z0-1628356034084)]
[外链图片转存中...(img-dsWLsR1B-1628356034086)]
![image](https://img-blog.csdnimg.cn/img_convert/8a02592cd22916e3e750d045a5ee6d00.png)