JavaWeb知识核心--Servlet体系结构
![体系结构](https://i-blog.csdnimg.cn/blog_migrate/e281f4d615773a5f243622d47003f7d6.png#pic_center)
Servlet --接口
Servlet --接口
GenericServlet --抽象类
HttpServlet --抽象类
GenericServlet
里面只有一个service方法作为抽象,因为里面其他方法已经默认做了空实现
其他方法可选择性实现
package com.web.servlet;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class ServletDemo2 extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
}
}
HttpServlet
因为要判断get和post方式,很麻烦,因此sun公司帮我们实现了这个判断-HttpServlet
HttpServlet:对http协议的封装,简化操作
步骤
- 定义类继承HttpServlet
- 复写doGet() / doPost()方法
package com.web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/s3")
public class ServletDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doget...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost...");
}
}
Servlet相关配置
urlpartten
-
Servlet访问路径
注解里面可以定义多个路径
@WebServlet(urlPatterns = {"/s3","/s31","/s32"}) -
路径定义规则
1. /xxx 2. /xxx/xxx :多层路径,目录结构 @WebServlet(urlPatterns = "/user/s1") @WebServlet(urlPatterns = "/user/*") @WebServlet(urlPatterns = "/*") //*代表任意路径,通配符 3. *.do @WebServlet(urlPatterns = "*.do") // 路劲前面不能加/,否则报错,访问为xxx.do //后缀名可以为任意的