第一个Servlet,Hello Servlet

第一个Servlet,Hello Servlet,第1张

第一个Servlet,Hello Servlet 6:Servlet

6.1: Servlet简介

Servlet就是sun公司开发动态web的一门技术Sun在这些API中提供一个接口叫做: Servlet,如果你想开发一个Servlet程序,只需要完 成两个小步骤:。【重点】
- 1:编写一个类,实现Servlet接口
- 2:把开发好的Java类部署到web服务器中。

把实现了Servlet接口的Java程序叫做,Servlet

6.2:HelloServlet
1:构建一个Maven项目:删除里面的src 目录,学习练习就在这个里面建造Moudel, 这个空的工程就是父工程;
2:关于Maven父工程的理解:
夫工程会有:

 
        servlet-01
        servlet-02
        response
    

这里面就是你编写子工程目录,父工程管理的子工程。

3:子项目会有:继承父工程

 
        javaweb-02-study
        com.kuang
        1.0-SNAPSHOT
 

父项目中的子项目就可以使用了:

6.3:Servlet原理
Servlet是由Web服务器调用,web服务器在收到请求之后,会:

6.4:实现一个HelloServlet
1编写一个类,实现Servlet接口;

重写方法

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入了DoGet方法");
        PrintWriter writer = resp.getWriter();
        writer.print("Hello,Servlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

:把开发好的Java类部署到web服务器中。
在web.xml中配置Servlet

 
  
    hello
    com.kuang.servlet.HelloServlet
  

  
  
    hello
    /hello
  

配置TomCat

测试运行

这说明你的Servlet启动成功,TomCat成功

在注册Servler时,请求路径是hello,输入hello后,就会响应给你自己写的实体类的对象信息!

6.5:Mapping问题
1:一个Servlet可以指定一个映射路径;

 
    hello
    com.kuang.servlet.HelloServlet
  
  
  
    hello
    /hello
  

2:一个Servlet可以指定多个映射路径;


    hello
    com.kuang.servlet.HelloServlet
  
  

  hello
  /hello1


  hello
  /hello2


这里请求hello1和hello2, 都可以被映射到,,从而实现一个Servlet可以指定多个映射路径;

3:一个Servlet可以指定通用映射路径;


  hello
  /hello/*


这里就随便编写了, 表示通配符*

4:一个Servlet可以自定义请求映射路径;

  
    hello
    *.hanshuo
  

5:默认请求路径(直接进入的是Servlet,尽量不要这么写)


  hello
  /*

6:优先级的问题

指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求:当我们的配置有明确的表示应该是由谁映射,或者是谁去访问的话,就是谁去访问。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5707834.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存