18_1手写Tomcat学习笔记

           tomcat学习笔记

1 tomcat简介

1.1 web服务器

。学习web开发,需要先安装一台web服务器(在某机器上运行web服务程序(软件),我们把这台机器称为web服务器),

然后再在web服务器中开发相应的web资源,供用户使用浏览器访问。

。疑问:学习web开发,为什么必须要安装一个web服务器?

​ web服务器究竟是什么?

常用web服务器

。JBoss是全世界开发者共同努力的成功,一个基于J2EE的开放源代码的应用服务器。

​ 因为JBoss代码遵循LGPL许可,可以在任何商业应用中免费使用它,而不用支付费用。

​ 2006年,JBoss公司被Redhat公司收购。免费。

。Weblogic是BEA公司的产品,是目前应用最广泛的Web服务器,支持J2EE规范,

​ 而且不断的完善以适应新的开发要求。这个是收费的。

。另一个常用的Web服务器是IBM的WebSphere,支持J2EE规范。

​ 。在小型的/中型的应用系统中,可以使用一个免费的Web服务器:Tomcat

​ 该服务器支持全部JSP以及Servlet规范。也是免费的。

1.2 tomcat服务器

官方地址:http://tomcat.apache.org/

1.2.1 下载

​ tar.gz文件是Linux操作系统下的安装版本

​ exe文件是Windows系统下的安装版本

​ zip文件是Windows系统下的压缩版本

1.2.2 安装

​ 使用zip包安装Tomcat 解压即可

​ 使用exe程序安装Tomcat

1.2.3 配置

​ (1)在环境变量中添加

​ JAVA_HOME= 指向你JDK的主目录 tomcat是java开发的

​ 也可以在Tomcat的启动文件bin/startup.bat文件中指定JDK版本

​ set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_311

rem ---------------------------------------------------------------------------

setlocal

rem Guess CATALINA_HOME if not defined
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_311  
set "CURRENT_DIR=%cd%"

​ (2)启动tomcat服务器

​ 到tomcat主目录下,bin/startup.bat

​ (3)验证安装是否成功

​ http://localhost:8080

​ (4)tomcat无法正常启动的原因分析:

​ a.JAVA_HOME配置错误,或者没有配置

​ b.如果你的机器已经占用了8080端口,则无法启动

​ 。你可以8080先关闭

​ netstat -anb 来查看谁占用该8080

​ 。主动改变tomcat的端口

​ 到conf/server.xml文件中修改

<Connector port="8080" URIEncoding="UTF-8" protocol="HTTP/1.1"  
                                            connectionTimeout="20000" redirectPort="8443" />

​ c.在访问tomcat的时候,一定要保证tomcat服务器是启动的。

1.2.4 tomcat目录结构

image-20220201141931062

bin:启动和关闭tomcat的bat文件

conf:配置文件

server.xml:该文件用于配置和server相关的信息,比如tomcat启动端口后,配置host,配置Context即web应用

web.xml:该文件配置与web应用(web应用就相当于一个web站点)

tomcat-users.xml:该文件用户配置tomcat的用户密码和权限

lib目录:该目录放置运行tomcat运行需要的jar包

logs目录:存放日志,当我们需要去查看日志的时候,很有用,当我们启动tomcat错误的时候,可以查询错误日志

webapps目录:该目录下,放置我们的web应用(web站点),

​ 比如:建立web1目录,下面放置我们的html文件,jsp文件,图片,

​ 则web1就被当做一个web应用管理起来。

1.2.5 如何去访问一个web应用的某个文件

image-20220201143624443

work工作目录:该目录用于存放jsp被访问后,生成的对应的那个servlet文件.class文件

1.2.6 在web服务器中安装web应用

​ 。什么是web应用

​ web应用是多个web资源的集合。简单的说,可以把web应用理解为硬盘上的一个目录,这个目录用于管理多个web资源。

​ 举例:news,blog

​ web应用通常也称为web应用程序,或web工程。

​ 。一个web应用由多个web资源或其他文件组成,包括HTML文件、CSS文件、JS文件、动态web页面、java程序、支持jar包、

​ 配置文件等。开发人员在开发web应用时,应按照下图所示的目录结构存放这些文件。

​ 否则,在把web应用交给web服务器管理时,不仅可能会使web应用无法访问,还会导致web服务器启动报错。

。Web程序的目录结构:

image-20220201144856236

现在我们要求:把hello.html文件设置成该web应用的首页,则需要把web应用格式做得更加规范:

配置的代码是web.xml文件中添加:

<welcome-file-list>
   <welcome-file>hello.html</welcome-file>
</welcome-file-list>

web-inf目下的classes目录将来是存放class文件

lib目录将来是存放jar文件

web.xml配置的是当前这个web应用的配置信息

1.2.7 配置虚拟目录

。我们把web应用放在tomcat默认的webapps目下,tomcat就会自动管理,但是大家考虑一个问题:

。因为tomcat所在磁盘(比如F盘)空间问题,我们能不能把web应用放在另外一个分区(比如:D盘),

​ 同样让tomcat去管理呢?

。配置虚拟目录在tomcat的conf目录下的server.xml的节点间添加如下代码:

<Context path="/web2" docBase="E:\web2" />

image-20220201163632107

资源目录:

image-20220201164209200

配置:

<Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">
    <Context path="/web2" docBase="E:\web2" />	   
</Host>

运行结果:

image-20220201164119192

Context的几个属性的说明:

path:访问路径

docBase: 虚拟目录路径

reloadable: 如果设为true,表示tomcat会自动更新web应用,这个开销大,

​ 建议在开发过程中可以设为true,但是一旦真的发布了,则应当设为false.

打war包,当要把web项目发给异地部署时,一般都会打成war发送给对方,对方直接放到tomcat的webapp目录下运行即可。

#项目打war包命令
jar -cvf web3.war *

#1.进入到E:\web3工程目录下
cmd E:\web3

#2.输入打war包命令
jar -cvf web3.jar *

#3.复制生成的web3.jar到tomcat的webapp目录下

#4.重启tomcat 

#5.输入路径访问
http://localhost:8080/web3/hello3.html

image-20220201170743577

访问结果:

image-20220201165841931

补充:如何不重启tomcat,就指定去reload一个web应用,

​ 方法:

​ 进入到tomcat的manager

image-20220202014242383

​ 点击reload即可。

1.2.8 虚拟主机

在一台web服务器中配置网站

。看一个企业常见需求:

​ 我们在实际访问网站的过程中,不可能使用http://localhost:8080/web应用/资源名 的方式去访问网站,

​ 实际上使用类似

​ http://www.sina.com.cn 或者

​ http://news.sina.com.cn

​ 的方式去访问网站,这个又是怎么实现的呢?

实现步骤如下:

(1)在C:\Windows\System32\drivers\etc下的hosts加域名映射

127.0.0.1     www.tangguanlin.com

image-20220201174820524

(2)在tomcat的server.xml文件添加主机名

<Host name="www.hansunping.com" appBase="d:\web3">
   <Context path="/" docBase="d:\web3" />
</Host>

(3)在d:\web3加入了一个 /WEB-INF/web.xml把hello2.html设为首页面

<welcome-file-list>
   <welcome-file>hello.html</welcome-file>
</welcome-file-list>

如果连端口都不希望带,则可以把tomcat的启动端口设为80即可。

(4)重启生效

image-20220201174909686

在一台web服务器中配置多个网站

。为了节省ip地址,我们有时需要在同一台web服务器配置多个网站,即不论是用户访问

​ www.taobao.com.cn和www.taobao.com,访问的都是同一台机器。

127.0.0.1     www.tangguanlin.com
127.0.0.1     www.tangguanlin.com.cn

image-20220201184725124

1.3 浏览器访问web站点原理

FastStoneEditor2

tomcat体系架构

img

如何设置默认的主机:

<Engine name=“Catalina” defaultHost=“localhost”>

#设置默认的主机
<Engine name="Catalina" defaultHost="localhost">
    <Host name="localhost"  appBase="webapps" >
             <Context path="/web2" docBase="E:\web3" />	  
    </Host>
</Engine>

2 手写tomcat_静态资源

1.hello.html

<h1>hello world</h1>

2.MyTomcat.java

package com.tangguanlin.view;
import java.io.*;
import java.net.*;
public class MyTomcat{

	public static void main(String[] args) throws Exception {

		ServerSocket ss = new ServerSocket(9999);
		Socket s = ss.accept();
		//提示一句话
		System.out.println("在9999上等待连接....");
		OutputStream os = s.getOutputStream();
		BufferedReader br = new BufferedReader(new FileReader("H:\\018Java Web\\hello.html"));
		String buff = "";
		while((buff = br.readLine())!=null){
			os.write(buff.getBytes());
		}
		//关闭流
		br.close();
		os.close();
		s.close();
	}
}

3.编译和运行

#编译
javac  MyTomcat.java
#运行
java MyTomcat

4.运行结果

image-20220131175713990

3 手写tomcat_动态资源

3.1 tomcat工作原理

1.服务端暴露端口,提供给客户端调用 ----技术实现:socket网络编程

2.给每一个请求分配一个线程来处理 ----技术实现:多线程编程

3.解析HTTP协议的请求,根据解析到的uri调用不同的Servlet —技术实现:http协议

4.加载和解析项目中的Servlet —技术实现:servlet规范 web.xml

客户端(浏览器):

​ 1.建立一个和服务端对应的Socket对象,指明连接服务端指定的域名和端口号

​ 2.通过Socket获取到指向服务端的输出流对象

​ 3.通过Socket获取到一个输入流

​ 4.将HTTP协议的请求部分发送到服务端

​ 5.接收来自服务端的数据并输出

​ 6.释放资源

服务端:

​ 1.创建ServletSocket对象,监听本机的8080端口

​ 2.等待来自客户端的请求获取和客户端对应的socket对象

​ 3.通过获取到的Socket对象获取输出流对象

​ 4.通过获取到的输出流对象将HTTP协议的响应部分发送到客户端

​ 5.释放资源

3.2 http get请求格式

get提交 http格式

GET /myHttpServlet?username=tangguanliin&password=123456 HTTP/1.1
Host: localhost:9999
Connection: keep-alive
Cache-Control: max-age=0
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9

3.2 http post请求格式

post提交 http请求格式

#例1
POST /adduser HTTP/1.1
Host: localhost:8030
Connection: keep-alive
Content-Length: 16
Pragma: no-cache
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
 
#Form Data
name=name&age=11
#例2
POST /search HTTP/1.1  
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, 
application/msword, application/x-silverlight, application/x-shockwave-flash, */*  
Referer: <a href="http://www.google.cn/">http://www.google.cn/</a>  
Accept-Language: zh-cn  
Accept-Encoding: gzip, deflate  
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; TheWorld)  
Host: <a href="http://www.google.cn">www.google.cn</a>  
Connection: Keep-Alive  
Cookie: PREF=ID=80a06da87be9ae3c:U=f7167333e2c3b714:NW=1:TM=1261551909:LM=1261551917:S=ybYcq2wpfefs4V9g; 
NID=31=ojj8d-IygaEtSxLgaJmqSjVhCspkviJrB6omjamNrSm8lZhKy_yMfO2M4QMRKcH1g0iQv9u-2hfBW7bUFwVh7pGaRUb0RnHcJU37y-
FxlRugatx63JLv7CWMD6UB_O_r  

hl=zh-CN&source=hp&q=domety  

3.3 http 响应格式

response 格式

#例1
#响应行
HTTP/1.1 200 ok\n
#响应头
Content-Type:text/html;charset=utf-8\n
Server:Apache-Coyote/1.1\n
\n\n
//响应体
<html>
    <head><title>我是标题</title></head>
    <body>
       <h1>I am header1</h1>
       <a href="http://www.baidu.com">链接</a>
    </body>    
</html>    
#例2
HTTP/1.1 200 OK
Date: Fri, 22 May 2009 06:07:21 GMT
Content-Type: text/html; charset=UTF-8

<html>
      <head></head>
      <body>
            <!--body goes here-->
      </body>
</html>
#例3
HTTP/1.1 200 OK
Date: Sat, 31 Dec 2005 23:59:59 GMT
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 122

<html>
<head>
   <title>Wrox Homepage</title>
</head>
<body>
   <!-- body goes here -->
</body>
</html>

3.4 手写tomcat

项目结构:

image-20220205031256228

conf.properties

aa=com.tangguanlin.mytomcat.AAServlet
bb=com.tangguanlin.mytomcat.BBServlet

HttpServletRequest.java

package com.tangguanlin.mytomcat.model;
/**
 * 说明:HttpServletRequest对象
 * 作者:汤观林
 * 日期:2022年02月05日 12时
 */
public class HttpServletRequest {

    private String requestURL;
    private String requestURI;
    private String queryString;

    private String remoteAddr;
    private String remotePort;

    private String username;
    private String password;

    public HttpServletRequest() {
    }

    public HttpServletRequest(String requestURL, String requestURI, String queryString, String remoteAddr, String remotePort, String username, String password) {
        this.requestURL = requestURL;
        this.requestURI = requestURI;
        this.queryString = queryString;
        this.remoteAddr = remoteAddr;
        this.remotePort = remotePort;
        this.username = username;
        this.password = password;
    }

    public String getRequestURL() {
        return requestURL;
    }

    public void setRequestURL(String requestURL) {
        this.requestURL = requestURL;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public void setRequestURI(String requestURI) {
        this.requestURI = requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public void setQueryString(String queryString) {
        this.queryString = queryString;
    }

    public String getRemoteAddr() {
        return remoteAddr;
    }

    public void setRemoteAddr(String remoteAddr) {
        this.remoteAddr = remoteAddr;
    }

    public String getRemotePort() {
        return remotePort;
    }

    public void setRemotePort(String remotePort) {
        this.remotePort = remotePort;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

HttpServletResponse.java

package com.tangguanlin.mytomcat.model;
/**
 * 说明:HttpServletResponse对象
 * 作者:汤观林
 * 日期:2022年02月05日 12时
 */
public class HttpServletResponse {

    private String status;

    private String contentType;

    private String username;

    private String password;

    public HttpServletResponse() {
    }

    public HttpServletResponse(String status, String contentType, String username, String password) {
        this.status = status;
        this.contentType = contentType;
        this.username = username;
        this.password = password;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

MyServlet.java

package com.tangguanlin.mytomcat;
import com.tangguanlin.mytomcat.model.HttpServletRequest;
import com.tangguanlin.mytomcat.model.HttpServletResponse;
import java.io.IOException;
/**
 * 说明:MyServlet接口
 * 作者:汤观林
 * 日期:2022年02月04日 22时
 */
public interface MyServlet {

    public void init();
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException;
    public void destroy();
}

AAServlet.java

package com.tangguanlin.mytomcat;
import com.tangguanlin.mytomcat.model.HttpServletRequest;
import com.tangguanlin.mytomcat.model.HttpServletResponse;
import java.io.IOException;
/**
 * 说明:
 * 作者:汤观林
 * 日期:2022年02月04日 23时
 */
public class AAServlet implements MyServlet {
    @Override
    public void init() {
        System.out.println("aaServlet...init...");
    }

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {


        System.out.println("aaservlet...request url:"+request.getRequestURL());
        System.out.println("aaservlet...request uri:"+request.getRequestURI());
        System.out.println("aaservlet...request 参数:"+request.getQueryString());
        System.out.println("aaservlet...request 客户端IP:"+request.getRemoteAddr());
        System.out.println("aaservlet...request 客户端端口:"+request.getRemotePort());

        System.out.println("aaservlet...request参数:"+request.getUsername());
        System.out.println("aaservlet...request参数:"+request.getPassword());

        response.setUsername(request.getUsername());
        response.setPassword(request.getPassword());

       /* System.out.println("aaServlet...service...");
        os.write("I am AAServlet!".getBytes());

        StringBuffer bf = new StringBuffer();
        bf.append("<html>");
        bf.append("<head><title>我是标题</title></head>");
        bf.append("<body>");
        bf.append("<h1>I am header1</h1>");
        bf.append("<a href=\"http://www.baidu.com\">链接</a>");
        bf.append("</body>");
        bf.append("</html>");
        os.write(bf.toString().getBytes());
        os.flush();*/
    }

    @Override
    public void destroy() {
        System.out.println("aaServlet...destroy...");
    }
}

BBServlet.java

package com.tangguanlin.mytomcat;
import com.tangguanlin.mytomcat.model.HttpServletRequest;
import com.tangguanlin.mytomcat.model.HttpServletResponse;
import java.io.IOException;
/**
 * 说明:
 * 作者:汤观林
 * 日期:2022年02月04日 23时
 */
public class BBServlet implements MyServlet{
    @Override
    public void init() {
        System.out.println("bbServlet...init...");
    }

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("bbServlet...service...");

        System.out.println("bbservlet...request url:"+request.getRequestURL());
        System.out.println("bbservlet...request uri:"+request.getRequestURI());
        System.out.println("bbservlet...request 参数:"+request.getQueryString());
        System.out.println("bbservlet...request 客户端IP:"+request.getRemoteAddr());
        System.out.println("bbservlet...request 客户端端口:"+request.getRemotePort());

        System.out.println("bbservlet...request 用户名:"+request.getUsername());
        System.out.println("bbservlet...request 密码:"+request.getPassword());

        response.setUsername(request.getUsername());
        response.setPassword(request.getPassword());

        /*os.write("I am BBServlet!".getBytes());
        os.flush();*/
    }

    @Override
    public void destroy() {
        System.out.println("bbServlet...destroy...");
    }
}

TomcatServlet.java

package com.tangguanlin.mytomcat;
import com.tangguanlin.mytomcat.model.HttpServletRequest;
import com.tangguanlin.mytomcat.model.HttpServletResponse;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
/**
 * 说明:MyTomcat
 * 作者:汤观林
 * 日期:2022年02月04日 23时
 */
public class TomcatServlet {

    //定义静态变量,用于存放本次请求的静态页面名称
    private static  String url = "";

    //定义一个静态类型Map,存放服务端conf.properties中的配置信息
    private static  Map<String,String> map = new HashMap<>();


    static {
        //服务器启动之前将配置参数中的信息 加载到map中
        //1.创建一个Properties对象
        Properties properties = new Properties();

        try {
            //2.加载webcontent目录下的conf.properties文件
            properties.load(new FileInputStream("WebContent\\conf.properties"));

            //3.将配置文件中的数据读取到map中
            Set<Object> set = properties.keySet();
            Iterator<Object> iterator = set.iterator();
            while (iterator.hasNext()){
                String key = (String)iterator.next();
                String value = properties.getProperty(key);
                map.put(key,value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        System.out.println(map);
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;
        try {
            // 1.创建ServletSocket对象,监听本机的8080端口
            ServerSocket serverSocket = new ServerSocket(9999);
            while (true){
                //2.等待来自客户端的请求获取和客户端对应的socket对象
                socket = serverSocket.accept();

                 is = socket.getInputStream();
                //3.通过获取到的Socket对象获取输出流对象
                os = socket.getOutputStream();

                //将http协议的响应行和响应头发送给客户端
                os.write("HTTP/1.1 200 ok\n".getBytes());
                os.write("Server: Apache\n".getBytes());
                os.write("Content-type: text/html;charset=utf-8\n".getBytes());
                os.write("\n".getBytes());

                HttpServletRequest request = parse(is);
                HttpServletResponse response = new HttpServletResponse();

                //判断本地请求的是静态的html页面,还是运行在服务端的一段Java程序
                if(url!=null){
                    if(url.indexOf(".")!=-1){
                        //静态资源文件
                        sendStaticResource(is,os);
                    }else{
                        //动态资源
                        sendDynamicResource(request,response);
                    }
                }
                os.write("<html>".getBytes());
                os.write("<head>".getBytes());
                os.write("2022年北京冬奥会".getBytes());
                os.write("</head>".getBytes());
                os.write("<br/>".getBytes());
                os.write("<body>".getBytes());
                os.write("用户信息:\n".getBytes());
                os.write("<br/>".getBytes());
                os.write(("用户名:"+response.getUsername()).getBytes());
                os.write("<br/>".getBytes());
                os.write(("密  码:"+response.getPassword()).getBytes());
                os.write("<br/>".getBytes());
                os.write("</body>".getBytes());
                os.write("</html>".getBytes());
                os.write("<br/>".getBytes());
                os.write(("username="+response.getUsername()+"&password="+response.getPassword()).getBytes());
                //5.释放资源
                is.close();
                os.close();
                socket.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }

    //获取http协议的请求部分,截取客户端要访问的资源名称,将这个资源名称复制给url
    private static HttpServletRequest parse(InputStream is) throws IOException {

        HttpServletRequest request = new HttpServletRequest();

        Map<String,String> httpMap = new HashMap<String,String>();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String httpRequest = null;
        String line = null;
        while((line=br.readLine())!=null&&!"".equals(line)){
            if(!"".equals(line)){
                System.out.println(line);
                if(line.indexOf(":")!=-1){
                    String[] split = line.split(":");
                    if("Host".equals(split[0])){
                        request.setRemoteAddr(split[1]);
                        request.setRemotePort(split[1]);
                    }
                    httpMap.put(split[0], split[1]);
                }else{
                    httpRequest = line;
                }
            }
        }
        System.out.println("httpRequest="+httpRequest);
        System.out.println("httpMap="+httpMap);

        //存放前端页面 的字段值
        Map<String,String> paramMap = new HashMap<>();

        // /bb?username=tangguanlin&password=123
        String[] split = httpRequest.split(" ");
        String method = split[0];
        String urltemp = split[1];
        String[] split1 = urltemp.split("\\?");
        String urltemp2 =split1[0];
        request.setRequestURI(urltemp2);
        url = urltemp2.substring(1,urltemp2.length());
        System.out.println(url);
        String param =split1[1];
        request.setQueryString(param);
        String[] objArr = param.split("&");
        for(String str:objArr){
            String[] key_value = str.split("=");
            if("username".equals(key_value[0])){
                request.setUsername(key_value[1]);
            }
            if("password".equals(key_value[0])){
                request.setPassword(key_value[1]);
        }
            paramMap.put(key_value[0],key_value[1]);
        }

        request.setRequestURL("http://"+request.getRemoteAddr()+":"+request.getRemotePort()+urltemp);

        System.out.println("前端字段的值为"+paramMap);
        System.out.println("request"+request);

        return  request;
    }

    //发送静态资源文件
    private static void sendStaticResource(InputStream is,OutputStream os) {

    }

    //发送动态资源文件
    private static void sendDynamicResource(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{


        //判断map中是否存在一个key,这个key是否和本次待请求的资源路径一致
        if(map.containsKey(url)){
            //如果包含指定的key,获取到map中对应的value值
            String className = map.get(url);

            //通过反射,将对应的java程序加载到内存
            Class clazz = Class.forName(className);
            MyServlet myServlet = (MyServlet)clazz.newInstance();

            //执行init方法
            myServlet.init();

            //执行service方法
            myServlet.service(httpServletRequest,httpServletResponse);
        }
    }
}

请求:

http://localhost:9999/aa?username=tangguanlin&password=123

运行结果:

image-20220205134636089

请求:http://localhost:9999/bb?username=tangguanlin&password=123

运行结果:

image-20220205031838284

后台打印的字段信息:

GET /aa?username=tangguanlin&password=123 HTTP/1.1
Host: localhost:9999
Connection: keep-alive
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
httpRequest=GET /aa?username=tangguanlin&password=123 HTTP/1.1
httpMap={Accept= text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9, Connection= keep-alive, User-Agent= Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36, Sec-Fetch-Site= none, Sec-Fetch-Dest= document, Host= localhost, Accept-Encoding= gzip, deflate, br, Sec-Fetch-Mode= navigate, sec-ch-ua= " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97", sec-ch-ua-mobile= ?0, Upgrade-Insecure-Requests= 1, sec-ch-ua-platform= "Windows", Sec-Fetch-User= ?1, Accept-Language= zh-CN,zh;q=0.9}
aa
前端字段的值为{password=123, username=tangguanlin}
requestHttpServletRequest{requestURL='http:// localhost: localhost/aa?username=tangguanlin&password=123', requestURI='/aa', queryString='username=tangguanlin&password=123', remoteAddr=' localhost', remotePort=' localhost', username='tangguanlin', password='123'}
aaServlet...init...
aaservlet...request url:http:// localhost: localhost/aa?username=tangguanlin&password=123
aaservlet...request uri:/aa
aaservlet...request 参数:username=tangguanlin&password=123
aaservlet...request 客户端IP: localhost
aaservlet...request 客户端端口: localhost
aaservlet...request参数:tangguanlin
aaservlet...request参数:123
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值