Java教程

JavaWeb(二)

本文主要是介绍JavaWeb(二),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

HTTP

什么是HTTP

HTTP(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP之上。

  • 文本:html,字符串...
  • 超文本:图片,音乐,视频,定位,地图...

两个时代

  • http1.0
    • HTTP/1.0:客户端与web服务器连接后,只能获得一个web资源
  • http2.0
    • HTTO/1.1:客户端与web服务器连接后,可以获得多个web资源

Http请求

  • 客户端--发请求(Request)--服务器

百度:

Request URL: https://www.baidu.com/  请求地址
Request Method: GET  get方法/post方法
Status Code: 200 OK  状态码:200
Remote Address: 220.181.38.150:443  远程地址:地址加端口
Accept: text/html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9  语言
Cache-Control: max-age=0  缓存控制
Connection: keep-alive

1.请求行

  • 请求行中的请求方式:GET
  • 请求方式:Get,Post,HEAD,DELETE,PUT,TRACT...
    • get:请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏小时数据内容,不安全但高效
    • post:请求能够携带的参数没有限制,大小无限制,不会在浏览器的URL地址栏小时数据内容,安全但不高效

2.请求头(消息头)

Accept:告诉浏览器它所支持的数据类型
Accept-Encoding:告诉浏览器支持哪种编码格式 GBK,UTF8,GB2312,ISO8859-1
Accept-Language:告诉浏览器它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器请求完成后是断开还是保持连接
HOST:主机

Http响应

  • 服务器--响应--客户端
Cache-Control: private  缓存控制
Connection: keep-alive  连接:保持连接
Content-Encoding: gzip  编码
Content-Type: text/html;charset=utf-8  类型

1.响应体

Accept:告诉浏览器它所支持的数据类型
Accept-Encoding:告诉浏览器支持哪种编码格式 GBK,UTF8,GB2312,ISO8859-1
Accept-Language:告诉浏览器它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器请求完成后是断开还是保持连接
HOST:主机
Reflush:刷新
Location:让网页重新定位

2.响应状态码
200:请求响应成功
3xx:请求重定向
4xx:找不到资源,资源不存在
5xx:服务器代码错误 502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车的一瞬间到页面能够展示,经历了什么?

Maven

在JavaWeb开发中,需要导入大量的jar包,需要手动导入,Maven可以自动导入和配置jar包

Maven项目架构管理工具

我们目前使用Maven方便导入jar包
Maven的核心思想:约定大于配置

  • 有约束的事物,不要去违反

Maven会规定好你改如何编写Java代码,必须按照这个规范来

下载安装Maven

官网:https://maven.apache.org/

配置环境变量

  • M2_HOME maven目录下的bin目录
  • MAVEN_HOME maven目录
  • 在系统的path中配置%MAVEN)HOME%\bin

修改阿里云镜像

  • mirrors:国内建立使用阿里云镜像
<mirror>
        <id>aliyunmaven</id>
        <mirrorOf>*</mirrorOf>
        <name>阿里云公共仓库</name>
        <url>https://maven.aliyun.com/repository/public</url>
</mirror>

本地仓库

本地仓库,远程仓库
建立一个本地仓库:
<localRepository>D:\Environment\apache-maven-3.8.3\maven-repoo</localRepository>

在IDEA中使用maven

https://www.bilibili.com/video/BV12J411M7Sj?p=6&spm_id_from=pageDriver
创建一个maven app项目
image
image
观察maven仓库中有什么变化
IDEA中的Maven设置

创建一个普通的maven项目

标记目录
image

在IDEA中配置Tomcat

image
image
image
image

pom文件

pom.xml是maven的核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!--Maven版本和头文件-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
<!--自己配制的GAV-->
  <groupId>com.guan</groupId>
  <artifactId>javaweb-01-maven</artifactId>
  <version>1.0-SNAPSHOT</version>
<!--项目的打包方式
    jar:java应用
    war:javaweb应用
-->
  <packaging>war</packaging>

  <name>javaweb-01-maven Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

<!--配置-->
  <properties>
    <!--项目的默认构建编码-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!--编译版本-->
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <!--项目以来-->
  <dependencies>
    <!--具体以来的jar包配置文件-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <!--项目构建使用所使用的东西-->
  <build>
    <finalName>javaweb-01-maven</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Servlet

Servlet简介

  • Servlet就是sun公司开发动态web的一门技术
  • sun公司在这些API中提供一个接口:Servlet,如果想要开发Servlet程序,只需要完成两个小步骤:1.编写一个类,实现Servlet接口。2.把开发好的Java类部署到web服务器中。

把实现了Servlet接口的java程序叫做Servlet

HelloServlet

1.构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建立module;这个空的工程就是Maven主工程
2.关于Maven父子工程的理解:
父项目中会有:

<modules>
    <module>servlet-01</module>
</modules>

子项目中会有:

<parent>
  <groupId>com.guan</groupId>
  <artifactId>servlet-01</artifactId>
  <version>1.0-SNAPSHOT</version>
</parent>

父项目中的java子项目可以使用
son extends father
3.Maven环境优化
(1)修改web.xml为最新的
(2)将maven的结构搭建完整
4.编写一个Servlet程序
(1)编写一个普通类
(2)实现Servlet接口,继承HttpServlet

public class HelloServlet extends HttpServlet {
    //由于get或者post只是请求实现的不同方式,可以相互调用,业务逻辑都一样
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter(); //响应流
        writer.print("Hello,Servlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

5.编写Servlet的映射
我们所写的Java程序需要通过浏览器方位,而浏览器需要连接web服务,所以我们要在web服务中注册我们所写的Servlet,还需给一条浏览器能够访问的路径

<!--注册Servlet-->
<servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>com.guan.servlet.HelloServlet</servlet-class>
</servlet>
<!--映射-->
<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/hello</url-pattern>
</servlet-mapping>

6.配置tomcat
7.启动测试

Servlet原理

Servlet是由Web服务器调用,web服务器在收到浏览器请求之后,会响应回客户端
image

Mapping问题

1.一个Servlet可以指定一个映射路径
2.一个Servlet可以指定多个映射路径
3.一个Servlet可以指定通用映射路径
4.指定一些后缀或者前缀等等
5.优先级问题:指定了固有的映射优先级最高,如果找不到就会走默认的请求

<servlet>
  <servlet-name>error</servlet-name>
  <servlet-class>com.guan.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>error</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

ServletContext

共享数据

web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;

  • 共享数据:我在这个Servlet中保存的数据,可以在另外一个Servlet中拿到
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.getInitParameter();  初始化参数
//        this.getServletConfig();  Servlet配置
//        this.getServletContext();  Servlet上下文
        ServletContext context = this.getServletContext();
        String username = "欧米茄效应";
        context.setAttribute("username",username); //将一个数据保存在ServletContext中
    }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");
        PrintWriter writer = resp.getWriter();
        writer.print("名字:"+username);
    }

获取初始化参数

<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306</param-value>
</context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }

请求转发

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    RequestDispatcher requestDispatcher = context.getRequestDispatcher("/get");
    requestDispatcher.forward(req,resp); //调用forward实现请求转发
}

HttpServletResponse

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表相应的一个HttpServletResponse对象;
如果要获取客户端请求过来的参数:找HttpServletRequest
如果要给客户端响应信息:找HttpServletResponse

简单分类

负责向浏览器发送数据的方法:

ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;

负责向浏览器发送响应头的方法

void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);

向浏览器输出消息

下载文件

(1)获取下载文件的路径
(2)下载的文件名
(3)想办法让浏览器能够支持下载我们所需要的东西
(4)获取下载文件的输入流
(5)创建缓冲区
(6)获取OutputStream对象
(7)将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //(1)获取下载文件的路径
    String realPath = "D:\\JavaCode\\javaweb\\javaweb-02-servlet\\response\\target\\classes\\1.jpg";
    // String realPath = this.getServletContext().getRealPath("/1.jpg");
    System.out.println("下载文件的路径"+realPath);
    //(2)下载的文件名
    String fileName = realPath.substring(realPath.lastIndexOf("//")+1);
    //(3)想办法让浏览器能够支持(Content-Disposition)下载我们所需要的东西
    resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
    //(4)获取下载文件的输入流
    FileInputStream in = new FileInputStream(realPath);
    //(5)创建缓冲区
    int len = 0;
    byte[] buffer = new byte[1024];
    //(6)获取OutputStream对象
    ServletOutputStream out = resp.getOutputStream();
    //(7)将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
    while((len=in.read(buffer))>0) {
        out.write(buffer,0,len);
    }
    //(8)关闭流
    in.close();
    out.close();
}

验证码功能

验证码怎么来的?
后端实现,需要用到java的图片类,生成一个图片。

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //如何让浏览器三秒自动刷新一次
    resp.setHeader("refresh","3");
    //在内存中创建一个图片
    BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
    //得到图片
    Graphics2D graphics = (Graphics2D) image.getGraphics(); //笔
    //设置图片的背景颜色
    graphics.setColor(Color.white);
    graphics.fillRect(0,0,80,20);
    //给图片写数据
    graphics.setColor(Color.BLUE);
    graphics.setFont(new Font(null,Font.BOLD,20));
    graphics.drawString(makeNum(),0,20);
    //告诉浏览器这个请求用图片的方式打开
    resp.setContentType("image/jpg");
    //网站存在缓存,不让浏览器缓存
    resp.setDateHeader("expires",-1);
    resp.setHeader("Cache-Control","no-cache");
    resp.setHeader("Pragma","no-cache");
    //把图片写给浏览器
    boolean write = ImageIO.write(image,"jpg", resp.getOutputStream());
}

实现重定向

一个web资源收到客户端请求后,他会通知客户端访问另外一个web资源,这个过程叫重定向。
resp.sendRedirect("/r/image");
面试题:请你聊聊重定向和转发的区别?
相同点:都会实现页面跳转
不同点:

  • 请求转发的时候,url不会产生变化
  • 重定向的时候,url会产生变化
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //处理请求
    String username = req.getParameter("username");
    String password = req.getParameter("password");

    System.out.println(username+":"+password);

    resp.sendRedirect("/r/success.jsp");
}

HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息被封装到HttpServletRequest,通过其中的方法,获得客户端的所有信息

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    String usn = req.getParameter("username");
    String psw = req.getParameter("password");
    String[] hobbys = req.getParameterValues("hobbys");

    //后台接收中文乱码问题
    System.out.println("==============================");
    System.out.println("username:"+ usn);
    System.out.println("password:"+ psw);
    System.out.println(Arrays.toString(hobbys));
    System.out.println("==============================");

    //通过请求转发
    req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
这篇关于JavaWeb(二)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!