Java Web:Servlet原理

一、什么是Servlet

是一种Web服务器端编程技术。
是实现了特殊接口的Java类。
由支持Servlet的Web服务器调用和启动运行。
一个Servlet负责对应的一个或一组URL访问请求,并返回相应的响应内容。
在这里插入图片描述

二、Servlet和http请求

1、http请求格式

在这里插入图片描述

2、http请求方式

在这里插入图片描述
get请求和post请求区别:

  1. get请求参数是会显示到地址栏的,post不显示。
  2. get请求不安全,post请求安全。
  3. get请求参数长度限制,post不限制。

3、http状态响应吗

在这里插入图片描述
在这里插入图片描述

三、Servlet服务

1、servlet和Tomcat请求关系:

在这里插入图片描述

2、简单撸一个Tomcat

package com.bobo;

import java.io.InputStream;

public class MyRequest {
    //客户端请求类型
    private String requestType;
    //客户端请求URL
    private String requestUrl;

    public MyRequest(InputStream inputStream) throws Exception {
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        String text = new String(bytes, 0, len);
        String firstLine = text.split("\n")[0];
        String[] firstTextArray = firstLine.split(" ");
        this.requestType = firstTextArray[0];
        this.requestUrl = firstTextArray[1];
    }

    public String getRequestType() {
        return requestType;
    }

    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    public String getRequestUrl() {
        return requestUrl;
    }

    public void setRequestUrl(String requestUrl) {
        this.requestUrl = requestUrl;
    }
}

package com.bobo;

import java.io.OutputStream;

public class MyResponse {
    private OutputStream outputStream;

    public MyResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void write(String str) throws Exception{
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("HTTP/1.0 200 ok\n")
                .append("Context-type:text/html\n")
                .append("\r\n")
                .append("<html>")
                .append("<body>")
                .append("<h1>"+str+"</h1>")
                .append("</body>")
                .append("</html>");
        outputStream.write(stringBuilder.toString().getBytes());
        outputStream.flush();
        outputStream.close();
    }
}

package com.bobo;

public abstract class MyHttpServlet {

    private static final String REQUEST_GET="GET";
    private static final String REQUEST_POST="POST";

    public abstract void doGet(MyRequest request,MyResponse response) throws Exception;
    public abstract void doPost(MyRequest request,MyResponse response) throws Exception;

    public void service(MyRequest request,MyResponse response) throws Exception{
        if (REQUEST_GET.equals(request.getRequestType())){
            doGet(request,response);
        }else {
            doPost(request,response);
        }
    }
}

package com.bobo;

public class MyServlet extends MyHttpServlet {
    @Override
    public void doGet(MyRequest request, MyResponse response) throws Exception {
        response.write("MyTomcat Get");
    }

    @Override
    public void doPost(MyRequest request, MyResponse response) throws Exception {
        response.write("MyTomcat Post");
    }
}

package com.bobo;

import java.util.HashMap;

public class MyMapping {
    public static HashMap<String,String> mapping=new HashMap<>();
    static {
        mapping.put("/myTomcat","com.bobo.MyServlet");
   }
   public static HashMap<String,String> getMapping(){
        return mapping;
   }
}

package com.bobo;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyService {
    public static void startService(int port) throws Exception{
        //服务器端套接字
        ServerSocket serverSocket=new ServerSocket(port);
        //客户端套接字
        Socket socket=null;
        while (true){
            socket=serverSocket.accept();

            //输入输出流
            InputStream inputStream=socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream();

            //初始化请求响应类
            MyRequest myRequest=new MyRequest(inputStream);
            MyResponse myResponse=new MyResponse(outputStream);

            //找到合适的applet
            String classString = MyMapping.getMapping().get(myRequest.getRequestUrl());
            System.out.println(classString);
            if (classString!=null){
                Class<MyHttpServlet> clazz=(Class<MyHttpServlet>) Class.forName(classString);
                MyHttpServlet myHttpServlet=clazz.newInstance();
                myHttpServlet.service(myRequest,myResponse);
            }
        }
    }

    public static void main(String[] args) {
        try {
            startService(10087);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

四、Servlet访问流程

url:http://localhost:8080/firstweb/first

组成:

服务器地址:端口/虚拟项目名/servlet的别名
uri:虚拟项目名/servlet别名

过程:浏览器发送请求到服务器,服务器根据请求URL地址中的URI信息在webapps目录下找到对应的项目文件夹,然后再web.xml中检索对应的servlet,找到后调用并执行servlet。

在这里插入图片描述
servlet从第一次请求时创建,到关闭服务器时销毁,中间多次请求只会存在一个servlet在内存中。当在web.xml中配置了1,在开启tomcat时就会创建servlet实例。

  • Service方法:不管是get还是post请求方式,如果service方法存在,则优先执行service方法。
  • doGet方法:在没有service的情况下,如果是get请求,调用doGet方法。
  • doPost方法:在没有service的情况下,如果是post请求,调用diPost方法。
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃透Java

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值