Tomcat和HTTP协议(一)

需求:假如D://hello.html文件希望可以共享,每个客户端都可以访问到。

解决方案:网络编程  TCP/IP 
    1)创建ServerSocket对象
    2)accept()--阻塞式方法。一旦监听到客户端连接,就放行了,每个客户端就可以连接起来了。  每个客户端需要创建Socket对象
    3)ServerSocket对象.getOutputStream()。

SOCKET之间通讯:底层支持它们之间进行数据共享(通过内部web服务器软件实现)。

数据如何共享?Server(服务器端):安装特定的服务器软件

(如:websphere-IBM公司-支持JavaEE,收费
           IIS-微软公司:和net语言兼容性好
           weblogic-BEA公司,支持JavaEE,收费
            tomcat:不完全支持JavaEE,免费)
web应用服务器软件:其实是容器。容器的作用:将Servlet:对象创建/jsp-->翻译为Java文件。

容器:Tomcat/Jboss/netty/Jetty......

一、Tomcat简介

1.tomcat的目录(主要)

1.webapp:存放网站信息(内容都是以目录形式存在的)
    默认访问ROOT(tomcat_home)
            index.jsp(欢迎页)
    ROOT/docs/......
        WEB-INF
            classes:存放字节码文件的。
            lib:存放jar包。
            网站的配置信息web.xml(配置servlet/初始化参数)
        Html/css/js可以放到根目录下。
2.conf:tomcat配置目录
    web.xml(定义全局参数/servlet默认配置:defaultServlet)
    server.xml:服务器配置:更改端口
3.work:里面存放jsp文件---->hello.jsp-->_hello_jsp.java--->class文件
4.bin:执行目录

2.Tomcat官网

Tomcat-management(管理tomcat用户权限)
tomcat热部署(面试会问):需要用户管理起来,定义用户规则。

3.访问tomcat(启动了)

http://localhost:8080   localhost:本地默认域名(127.0.0.1 )  tomcat默认端口:8080   qq:5555     mysql:3306

这个网址会自动跳转到首页(首页的html文件在当前项目的路径下),如果想打开自己写的页面,则需要继承

4.配置首页

配置首页:web.xml文件中配置  http://localhost:8080/静态文件名

<!--配置欢迎页   只要本地项目有下面的三种文件的一种即可-->
<welcome-file-list>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

5.如何区分静态资源和动态资源

静态资源:Html/css/js/.jpg/gif.....
区分方法:通过它的源码是否发生变化来区分

6.创建Maven的web工程的目录结构

有两种方式:(1)在创建的时候,选择模板maven-archetype-webapp。

过程比较缓慢,要求网络较好!!

(2)手动开发一个servlet,注意补全目录!!  下面是目录结构:

项目名称(创建maven工程web模板,但是不使用模板)
src
	main-->主程序Java代码
            java:具体的代码
	    resources-->资源文件的配置目录(sprigmvc.xml/spring.xml/sqlMapConfig.xml)
	    webapp:(**目录,必须创建)
		html/css/js
		jsp(目录)
		--->xx.jsp
		WEB-INF(**目录,必须有)
			web.xml(**)--->网站的配置信息
	test
		java:单元测试程序代码
		resource:测试时使用到的配置文件

7.手动开发一个Servlet

1)在pom.xml---->打war包<packaging>war</packaging>
2)补全目录结构
src
    main
        java
        Resources
            webapp
                WEB-INF
                    web.xml
3)创建一个Servlet(必须导入servlet-api.jar)

4)定义一个类  extends HttpServlet类,并覆写doGet()--执行get()提交和doPost()--执行post()提交。

5)使用maven--->打包--->tomcat进行执行。

8.Servlet的执行过程

    1)http://localhost: 8080/hello--->在网站配置信息web.xml中是否存在一个映射路径  url-pattern:/hello
    2)如果找到,就会找到对应的Servlet名称:HelloServlet,在配置信息中找是否存在同名的Servlet,如果存在,
获取反射文件,
    3)访问Servlet-class----->通过反射获取到HelloServlet.class类对象
    4)反射机制获取到里面无参构造/成员方法---->tomcat解析里面内容
    5)使用HttpServletResponse响应给用户内容。
    6)如果在web.xml文件中没有找到对应的映射路径,在webapp根目录下找静态资源Hello.html文件。找不到-->404错误

二、HTTP协议

1.请求行

请求行:GET /myFirstServlet HTTP/1.1  
HOST:localhost:8080
请求信息包含内容:请求头:请求头的内容
请求行由三部分组成:提交方式、uri和http协议的版本。
提交方式:method:GET/POST
uri:/myFirstServlet 
http协议的版本:HTTP/1.1(反复请求)     http/1.0(只能请求一次)
统一资源定位符url:http://localhost:8080/myFirstServlet  uri:/myFirstServlet (url是uri的一个子集)
HOST:请求头(当前本地的提交方式)

2.HTTP协议

需求:一个html页面有三张图片,访问该页面,共有几次HTTP请求?4次
src/href:加载资源文件,请求一次。分别访问了html,jpg,jpg,jpg,共四次。

3.获取请求的基本信息

        String method=request.getMethod();//获取请求方式
	String uri=request.getRequestURI();//获取URI
	request.getProtocol();//获取协议版本
	request.getHeader("host");//获取指定的请求头信息

        request.getHeader("user-agent");//不区分大小写,返回值是一堆字符串:拼接  Trident:IE浏览器的类型 Chrome:谷歌  Firefox:火狐
package com.xunpu.b_request;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 获取请求行信息内容
 */
public class RequestDemo1 extends HttpServlet {
    /**
     * 1)tomcat服务器获取到浏览器的请求数据
     * 2)tomcat服务器将请求数据封装到了HttpServletRequest对象中
     * 3)tomcat调用了service方法,业务具体覆盖doGet()和doPost()。
     *
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("调用了doGet()");
        // 获取请求行信息
        //1.1请求方式

        String method=request.getMethod();
        System.out.println(method);
        //1.2请求uri
        String uri=request.getRequestURI();
        System.out.println("uri="+uri);
        //请求url(返回StringBuffer)
        System.out.println(request.getRequestURL());

        //1.3获取http协议的版本
        System.out.println("protocal="+request.getProtocol());

        //2.获取指定的请求头信息
        //Host:localhost:8080
        String host=request.getHeader("host");
        System.out.println("host="+host);


    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

在网页中访问http://localhost:8080/requestDemo1,可以在后台看到结果:

4.查看使用浏览器的类型

package com.xunpu.b_request;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RequestDemo2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");//解决乱码。如果输出有中文,全局解决乱码问题。
            //获取user-agent的请求头
        //获取哪类类型的浏览器  Trident:IE浏览器的类型     Chrome:谷歌浏览器的类型      FireFox:火狐浏览器的类型
        String userAgent=request.getHeader("user-agent");
        //返回值是一对字符串:拼接
        System.out.println("userAgent="+userAgent);

        //判断用户使用的是哪种浏览器:contains
        if(userAgent.contains("Trident")){
            response.getWriter().write("您当前使用的是IE浏览器");
        }else if(userAgent.contains("Chrome")){
            response.getWriter().write("您当前使用的是谷歌浏览器");
        }else if(userAgent.contains("fire fox")){
            response.getWriter().write("您当前使用的是火狐浏览器");
        }else{
            response.getWriter().write("当前不支持这个浏览器类型");
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

在谷歌浏览器中打开网址http://localhost:8080/requestDemo2。结果为:

5.request对象获取基本参数

5.1 get和post获取参数是完全不同的
get方式获取参数
        public String getQueryString();
request.getQueryString();//返回?后面跟接的参数(http://localhost:8080/testMethod.html?username=xxx&password=xxx)
post方式获取参数:流
        public String getInputStream();

get和post方式提交数据,后台获取参数是不一样的,因此想办法将get方式和post方式提交获取 参数通用的方法:
request.getParameter(String name)-->String value
request.getParameterNames()--->返回Enumeration--->Iterator迭代器

testMethod.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>获取表单参数</title>
</head>
<body>
<h3>get方式提交</h3>
<form action="/requestDemo3" method="get">
    用户名:<input type="text" name="username"><br>
    密&nbsp;&nbsp;&nbsp;码:<input type="text" name="password"><br>
    性别:<input type="radio" name="gender" value="男">男
    <input type="radio" name="gender" value="女">女
    爱好:
    <input type="checkbox" name="hobit" value="足球">足球
    <input type="checkbox" name="hobit" value="篮球">篮球
    <input type="checkbox" name="hobit" value="羽毛球">羽毛球

    <input type="submit" value="提交"><br>
</form>
<hr>
<h3>post方式提交</h3>
<form action="/requestDemo3" method="post">
    用户名:<input type="text" name="username"><br>
    密&nbsp;&nbsp;&nbsp;码:<input type="text" name="password"><br>
    <input type="submit" value="提交"><br>
</form>

</body>
</html>

requestDemo3

package com.xunpu.b_request;

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;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

/**
 * request获取参数
 * get方式和post提交数据,后台获取参数不一样,想办法将 get方式和post方式提交获取参数通用方式
 * request.getParameter(String name)----》String value
 * request.getParameterNames()-->Enumeration-->Iterator:迭代器
 */
//@WebServlet(name = "RequestDemo3")
public class RequestDemo3 extends HttpServlet {
    //默认执行get提交
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get和post获取参数数据是完全不同的
//        get方式获取参数:
        //public String getQueryString();   http://localhost:8080/testMethod.html?username=xxx&password=xxx
        String queryString=request.getQueryString();
        System.out.println(queryString);//username=xxx&password=xxx

        //get方式和post方式通用获取参数数据的方法
        //通过表单的name参数值-->获取表单的内容
        //方式一:获取单个参数名称
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        //tomcat8.0以下的版本,遇见中文参数的,需要手动解码。
        System.out.println(username+"&"+password);
        //方式二:
        //获取所有的参数名称
        Enumeration<String> enums=request.getParameterNames();
        while(enums.hasMoreElements()){
            String parametername = enums.nextElement();
            //通过参数名称获取参数值
            String paraValue=request.getParameter(parametername);
            System.out.println(parametername+":"+paraValue);
        }
        //方式三:获取所有的参数对象
        //key(参数名称),value:如果只有一个参数:value[0]
       Map<String,String[]> parametermap=request.getParameterMap();
        //map集合的遍历
        //1.entrySet()  获取当前map集合中的所有的键值对对象
        //2.keySet()  获取所有的键,遍历
        Set<Map.Entry<String,String[]>> entrySet=parametermap.entrySet();
        for(Map.Entry<String,String[]> entry:entrySet){
            //通过键值对对象获取所有的键和值
            String name=entry.getKey();
            String[] value=entry.getValue();
            System.out.println(name+":"+value[0]);//只打印第一个值
        }
        System.out.println("==================================");
        Set<String> set=parametermap.keySet();
        for(String key:set){
            String[] value=parametermap.get(key);
            System.out.println(key+"="+value[0]);
        }

//        方式四:通过获取参数:获取一个参数(对应多个参数值)复选框
        String[] hobits=request.getParameterValues("hobit");
//先判断,再遍历
        if(hobits!=null){
            for(String hobit:hobits){
                System.out.println("hobit="+hobit);
            }
        }

    }
//默认执行post方式提交
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("gbk");
        //post方式获取数据
        InputStream in=request.getInputStream();
        //定义一个字节数组
        byte[] bys=new byte[1024];
        int len=0;
        while((len=in.read(bys))!=-1){
            System.out.println(new String(bys,0,len));
        }
        in.close();
    }
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值