public class ServletDemo implements Servlet{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(“Hello Servlet”);
}
}
在我们开发过程中,实现Servlet的方法有3种,分别是实现Servlet接口、继承GenericServlet类和继承HttpServlet类,
GenericServlet:将Servlet接口中其他的方法做了默认空实现,只将service()方法作为抽象,HttpServlet是对http协议的一种封装,我们可以定义类继承HttpServlet,然后复写doGet/doPost方法。`(在实际应用
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
中,继承HttpServlet应用居多)`
如果我们想要发送一个动态web资源(即开发一个Java程序向浏览器输出数据),需要完成:编写一个Java类,实现servlet接口,把开发好的Java类部署到web服务器中这两步。
- 搭建步骤:
1. 创建JavaEE项目
2. 定义一个类,实现Servlet接口(public class ServletDemo1 implements Servlet)
3. 实现接口中的抽象方法
4. web.xml中配置Servlet
定义MyServlet类,通过继承HttpServlet类来实现Servlet接口
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//…
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//…
}
}
配置web.xml文件,访问路径为/servlet
servlet
cn.ly.web.servlet.MyServlet
servlet
/servlet
- 执行原理:
1. 当服务器接受到客户端浏览器的请求后,会解析请求URL路径,获取访问的Servlet的资源路径
2. 查找web.xml文件,是否有对应的标签体内容。
3. 如果有,则在找到对应的全类名
4. tomcat会将字节码文件加载进内存,并且创建其对象
5. 调用其方法
注意:Servlet3.0之后,我们可以通过使用注解来代替web.xml配置,我们只需要在MyServlet类种的上方添加一个@WebServlet("/servlet")即可(适用于单个Servlet的配置)
@WebServlet相关配置
urlpartten:Servlet访问路径,一个Servlet可以定义多个访问路径 : @WebServlet({"/a1","/a2","/a3"})
路径定义规则:
- 1. /xxx:路径匹配
- 2. /xxx/xxx:多层路径,目录结构
- 3. *.do:扩展名匹配
WebServlet的相关属性
| 属性名 | 描述 |
| — | — |
| urlPatterns | Servlet的访问URL |
| value | Servlet的访问URL |
| description | Servlet的描述信息 |
| displayName | Servlet的显示名称 |
| initParams | Servlet的初始化参数 |
| name | Servlet的名称 |
| asyncSupported | 声明Servlet是否支持异步操作模式 |