Servlet & JSP学习笔记之简介

前言

对于Java程序而言:

  • JVM >> 操作系统
  • class文件 >> 可执行文件

Web容器

Web容器可以抽象为运行Sevrlet&JSP的服务器,这个服务器是跑在JVM之上的。
Web容器位于HTTP服务器的上层,在HTTP协议以及JAVA对象中相互转化。

Servlet & JSP

JSP > .java源文件 > .class文件

Servlet运行原理

Servlet运行主要经过三个过程:

1. 创建Servlet对象

Web容器将HTTP报文转换成Servlet对象

Servlet & JSP学习笔记之简介_第1张图片
image.png

2. 调用相关方法

Servlet & JSP学习笔记之简介_第2张图片
image.png

Servlet主要是通过service方法来响应HTTP请求, 通过判断请求的Method来调用相应的响应函数. 响应函数在这个抽象类中并没有具体的实现, 需要子类继承来实现.

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
# get 方法需要判断资源是否有缓存, 而且为了兼容旧版本协议做了两次判断
        if(method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if(lastModified == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
                    ifModifiedSince = -1L;
                }

                if(ifModifiedSince < lastModified / 1000L * 1000L) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if(method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if(method.equals("POST")) {
            this.doPost(req, resp);
        } else if(method.equals("PUT")) {
            this.doPut(req, resp);
        } else if(method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if(method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if(method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }

    }

3. 销毁对象

将Servlet对象转化为HTTP报文,并销毁该对象

Servlet & JSP学习笔记之简介_第3张图片
image.png

URL Mapping

在Servlet3.0之后可以使用注解的方式配置URL, 而不用配置XML文件.

@WebServlet("/hello.view")
public class HelloServlet extends javax.servlet.http.HttpServlet {
    public HelloServlet() {
    }

或者可以使用web.xml 配置文件





    
        helloServlet
        cn.boolin.HelloServlet
    
    
        helloServlet
        /test1
    

文件结构

Servlet & JSP学习笔记之简介_第4张图片
image.png

参考书目:

  • 林信良 (2012-05-01). JSP & Servlet学习笔记(第2版) (Kindle Location 535). 清华大学出版社. Kindle Edition.

你可能感兴趣的:(Servlet & JSP学习笔记之简介)