JavaWeb

本笔记源于【狂神说Java

B站收UP主:遇见狂神说。即可看见教程

或者点击链接JavaWeb入门到实战

目录

本笔记源于【狂神说Java】

1、基本概念

1.1、前言

1.2、web应用程序

1.3、静态web

1.4、动态web

2、web服务器

2.2、web服务器

3、Tomcat

3.1、安装Tomcat

3.2、Tomcat启动和配置

3.3、配置

3.4、发布一个web网站

4、HTTP

4.1、什么是HTTP

4.2、两个时代

4.3、HTTP请求

4.4、HTTP响应

5、Maven

5.1、Maven项目架构管理工具

5.2、下载安装Maven

5.3、配置环境变量

5.4、阿里云镜像

5.5、本地仓库

5.6、在IDEA中使用Maven

5.7、创建一个普通的Maven项目

5.8、标记文件夹功能

5.9、在Maven中配置Tomcat

5.10、pom文件

6、Servlet

6.1、Servlet简介

6.2、HelloServlet

6.3、Servlet原理

6.4、Mapping问题

6.5、ServletContext

1、共享数据

2、获取初始化参数

3、请求转发

4、读取资源文件

6.6、HttpServletResponse

1、简单分类

2、下载文件

3、验证码功能

4、实现重定向

6.7、HttpServletRequest

1、获取参数、请求转发

7、Cookie、Session

7.1、会话

7.2、保存会话的两种技术

7.3、Cookie

7.4、Session(重点)

8、JSP

8.1、什么是JSP

8.2、JSP原理

8.3、JSP基础语法

JSP表达式

jsp脚本片段

JSP声明

8.4、JSP指令

8.5、9大内置对象

8.6、JSP标签、JSTL标签、EL表达式

9、JavaBean

10、MVC三层架构

10.1、前期

10.2、三层架构

11、Filter(重点)

12、监听器

13、过滤器、监听器的应用

14、JDBC


Java和Web

1、基本概念

1.1、前言

web开发:

  • web,网页的意思

  • 静态web

    • 实现方法:html,css

    • 提供给所有人看的数据始终不会发生变化

  • 动态web

    • 几乎所有的网站,如淘宝

    • 提供给所有人看的数据始终发生变化,每个人在不同的时间,不同的地点看到的信息各不相同。

    • 技术栈:Servlet/JSP,ASP,PHP

    在Java中,动态web资源开发的技术统称为JavaWeb

1.2、web应用程序

web应用程序,可以提供浏览器访问的程序

  • a.html、b.html....多个web资源可以被外界访问,对外界提供服务;

  • 你们能访问到的任何一个页面或者资源都会存在这个世界的某一个角落的计算机上。

  • 这个统一的web资源会被放在同一个文件夹下,web应用程序-->Tomcat:服务器

  • 一个web应用由多部份组成(静态web,动态web)

    • html、css、js

    • jsp、servlet

    • java程序

    • jar包

    • 配置文件(properties)

web应用程序编写完毕之后,若想提供给外界访问:需要一个服务器统一管理。

1.3、静态web
  • .html,.html 这些都是网页的后缀,如果服务器上一直存在这些东西,我们就可以直接进行读取

  • 静态web存在的缺点

    • web页面无法动态更新,所有用户看到的都是同一个页面

      • 轮播图,点击特效:伪动态

      • JavaScript(实际开发中用的更多)

      • VBScript

    • 他无法和数据库交互(数据无法持久化,用户无法交互)

1.4、动态web

页面会动态展示:“web的页面展示效果因人而异”

缺点

  • 加入服务器的动态web资源出现错误,我们需要重新编写我们的后台程序,重新发布

    • 停机维护

优点

  • web页面可以动态更新,所有用户看到的都不是同一个页面

  • 他可以和数据库交互(数据持久化:注册,商品信息,用户信息......)

2、web服务器

ASP:

  • 微软:国内最早流行的就是ASP;

  • 在HTML中嵌入了VB脚本,ASP+COM;

  • 在ASP开发中,基本一个页面就有几千行的业务代码,页面极其混乱

  • 维护成本高!

PHP:

  • php开发速度很快,功能很强大,跨平台,代码很简单

  • 无法承载大访问量的情乱(局限性)

JSP/Servlet:

B/C:浏览器和服务器

C/S:客户端和服务器

  • sun公司主推的B/S架构

  • 基于Java语言的(所有的大公司,或者一些开源的组件,都是用Java写的)

  • 可以承载三高问题带来的影响(高并发、高可用、高性能)

  • 语法像ASP,ASP-->,加强市场强度。

2.2、web服务器

服务器是一种被动的操作,用来处理用户的一些请求和给用户带来一些响应信息

IIS

微软的:ASP....,Window中自带的

Tomcat

Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 规范。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为比较流行的Web 应用服务器。 Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选,是javaweb初学者的最佳选择。 而Tomcat 实际上运行JSP 页面和Servlet。Tomcat最新版本为10.0.23。

下载Tomcat:

1、安装 or 解压

2、了解配置文件及其目录结构

3、这个东西的作用

3、Tomcat

3.1、安装Tomcat

下载地址:Apache Tomcat® - Welcome!

3.2、Tomcat启动和配置

目录文件说明:

启动和关闭:

访问测试:http://localhost:8080/

可能遇到的问题:

  1. Java环境变量没有配置

  2. 闪退问题:需要配置兼容性

  3. 乱码问题:配置文件中设置

3.3、配置

可以配置启动的端口号

  • Tomcat的默认端口号为:8080

  • MySQL:3306

  • http:80

  • https:443

 <Connector port="8080" protocol="HTTP/1.1"
            connectionTimeout="20000"
            redirectPort="8443"
            maxParameterCount="1000"
            />=

可以配置主机的名称

  • 默认的主机名为:localhost--->127.0.0.1

  • 默认网站应用存放的位置为:webapps

 <Host name="localhost"  appBase="webapps"
       unpackWARs="true" autoDeploy="true">

高难度面试题:

请谈谈网站是如何进行访问的。

  1. 输入一个域名:回车

  2. 检查本机的C:\Windows\System32\drivers\etc配置文件下有没有这个域名映射

    1. 有,直接返回对应的ip地址,这个地址中,有我们需要访问的web程序,可以直接访问。

    2. 没有,去DNS服务器找,找到的话就返回,找不到就返回找不到。

3.4、发布一个web网站
  • 将自己写的网站,放到服务器(Tomcat)中指定的web应用文件夹(webapps)下,就可以访问了

网站应用的结构

 -- webapps:Tomcat服务器的web目录
     -- Root
     -- comStudy:网站的目录名
         - WEb-INF
             - classes:java程序
             - lib:web应用所依赖的jar包
             - web.xml:网站配置文件
         - index.html 默认的首页
         - static
                 -css
                     -style.css
                 -js
                 -img

4、HTTP

4.1、什么是HTTP

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

HTTP:

  • 文本:html,字符串

  • 超文本:图片,音乐,视频,定位,地图

  • 端口号:80

HTTPS:安全的

  • 端口号:443

4.2、两个时代
  • http1.0

    • HTTP/1.0:客户端可以与web服务器连接后,只能获得一个web资源

  • http2.0

    • HTTP/1.1:客户端可以与web服务器连接后,可以获得多个web资源

4.3、HTTP请求

客户端---发请求---服务器

访问百度:

 // 请求地址
 Request URL: https://www.baidu.com/
 // 请求方法
 Request Method: GET
 // 状态代码
 Status Code: 200 OK
 // 远程地址
 Remote Address: 14.215.177.38:443
 // 引用站点策略
 Referrer Policy: strict-origin-when-cross-origin

Request Headers

 Accept: text/html
 Accept-Encoding: gzip, deflate, br
 // 语言
 Accept-Language: zh-CN,zh;q=0.9
 Cache-Control: max-age=0
 Connection: keep-alive

请求行:

  • 请求行中的请求方式:GET

  • 请求方式:Get,Post,HEAD,DELETE,PUT… GET:请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全,但高效。 POST:请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内容,安全,但不高效。

消息头:

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

4.4、HTTP响应

服务器---响应---客户端

Response Headers

 // 缓存控制
 Cache-Control: no-cache
 // 保持连接(http1.1)
 Connection: keep-alive
 // 文本编码类型
 Content-Encoding: gzip
 // 响应类型
 Content-Type: text/html;charset=utf-8

响应体

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

响应状态码

  • 200:响应成功

  • 3xx:请求重定向(304等等)

  • 4xx:找不到资源(404等等)

  • 5xx:服务器代码错误(500代码错误,502网关错误)

5、Maven

我为什么要学习这个技术?

  1. 在Javaweb开发中,需要使用大量的jar包,我们手动导入;

  2. 如何能够让一个东西帮我自动导入和配置这个jar包;

由此,Maven诞生了!

5.1、Maven项目架构管理工具

我们目前用来就是方便导入jar包的!

Maven的核心思想:约定大于配置

  • 有约束,不要去违反

Maven会规定好该如何去编写我们的Java代码,必须按照这个规范来。

5.2、下载安装Maven

官网:Maven – Welcome to Apache Maven

下载完成后,解压即可;

5.3、配置环境变量

在我们的系统环境变量中

配置如下配置:

  • M2_HOME maven目录下的bin目录

  • MAEVN_HOME maven的目录

  • 在系统的path中配置MAVEN_HOME

测试Maven是否安装成功,保证配置必须完成!

5.4、阿里云镜像
  • 镜像:mirror

    • 作用:加速我们的下载

  • 国内建议使用阿里云镜像

<mirror>
    <id>alimaven</id>
    <mirrorOf>central</mirrorOf>
    <name>阿里云公共仓库</name>
    <url>https://maven.aliyun.com/repository/public</url>
</mirror>

5.5、本地仓库

在本地的仓库,远程仓库

建立一个仓库:localRepository

<localRepository>D:\Maven\apache-maven-3.9.6-bin\apache-maven-3.9.6\maven-repo</localRepository>

5.6、在IDEA中使用Maven
  1. 启动IDEA

  2. 创建一个Maven项目

  1. 等待项目初始化

此时说明项目创建完成~

  1. 观察Maven仓库中多了什么东西?

  2. IDEA中的Maven设置

注意事项:IDEA创建成功后,看一眼Maven的配置

  1. 到这里,Maven在IDEA中的配置和使用就OK了!

5.7、创建一个普通的Maven项目

这个只用在Web应用下才会用!

5.8、标记文件夹功能

5.9、在Maven中配置Tomcat

解决警告问题:

必须的配置:为什么会出现这个问题:我们访问一个网站,需要指定一个文件夹名字;

Maven使用Tomcat

5.10、pom文件

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

pom.xml

<?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>MavenTest</groupId>
  <artifactId>Maven-Test-3.6.3</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
<!--  package:项目的打开方式
      jar:Java应用
      war:Javaweb应用-->

  <name>Maven-Test-3.6.3 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>Maven-Test-3.6.3</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>

maven中因为约定大于配置,我们之后可能遇到我们自己写的配置文件无法被导出或者生效的问题,解决方案如下:

<!--在build中配置resources。来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

目录树

可能出现的问题:

maven默认web项目中的web.xml版本问题

替换为webapp4.0版本和tomcat一致

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">
  

</web-app>

Maven仓库:https://mvnrepository.com/

6、Servlet

6.1、Servlet简介
  • Servlet就是sun公司开发动态web的一门技术

  • Sun在这些API中提供了一个接口叫做:Servlet,若你想开发一个Servlet程序,只需要完成两个小步骤:

    • 编写一个类,实现Servlet接口

    • 把开发好的Java类部署到web服务器当中去

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

6.2、HelloServlet

servlet接口sun公司有两个默认的实现类:HttpServlet,GenericServlet

  1. 构建一个Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建立Moudel;这个空工程就是Maven的主工程;

  2. 关于Maven父子工程的理解:

    父项目中会有

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

    子项目中会有

    <parent>
        <artifactId>javaweb-02-servlet</artifactId>
        <groupId>com.study</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    父项目中的java子项目可以直接使用,

    son extends father
  3. Maven环境优化

    1. 修改web.xml为最新的

      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                            http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
               version="4.0"
               metadata-complete="true">
      
      </web-app>

    2. 将maven的结构搭建完整

      添加java文件夹和resouces文件夹并修改属性

  4. 编写一个Servlet程序

    1. 编写一个普通类

    2. 实现servlet接口,这里我们直接继承HttpServlet,GenericServlet

    package com.study.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    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.study.servlet.HelloServlet</servlet-class>
        </servlet>
        <!--Servlet的请求路径-->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
  6. 配置Tomcat

    注意:配置项目发布的路径就可以了

  7. 启动测试

6.3、Servlet原理
6.4、Mapping问题
  1. 一个servlet可以指定一个映射路径

     <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
  2. 一个servlet可以指定多个映射路径

    <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello1</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello2</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello3</url-pattern>
        </servlet-mapping>
  3. 一个servlet可以指定通用映射路径

    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello/*</url-pattern>
    </servlet-mapping>
    
    
  4. 默认请求路径

    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

  5. 指定一些后缀或者前缀等等......

    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.xiao</url-pattern>
    </servlet-mapping>
  6. 优先级问题

    指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求

    <servlet>
            <servlet-name>error</servlet-name>
            <servlet-class>com.study.servlet.HelloServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>error</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>

6.5、ServletContext

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

1、共享数据

我在这个Servlet中保存的数据,可以在另一个Servlet中拿到;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //this.getInitParameter() 初始化参数
        //this.getServletConfig() Servlet配置
        //this.getServletContext() Servlet上下文

        ServletContext servletContext = this.getServletContext();
        String username = "张三";//数据
        servletContext.setAttribute("username",username);//将一个数据保存在SercletContent中,名字为:username,值:username
        
    }
}
public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        Object username = (String)servletContext.getAttribute("username");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("名字:"+username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
<!--<context-param>
    <param-name>namespace</param-name>
    <param-value></param-value>
  </context-param>-->
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.study.servlet.HelloServlet</servlet-class>
    <!--<init-param>
      <param-name>namespace</param-name>
      <param-value></param-value>
    </init-param>-->
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>getc</servlet-name>
    <servlet-class>com.study.servlet.GetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>getc</servlet-name>
    <url-pattern>/get</url-pattern>
  </servlet-mapping>

2、获取初始化参数
<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext servletContext = this.getServletContext();

    String url = servletContext.getInitParameter("url");
    resp.getWriter().print(url);
}

3、请求转发
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext servletContext = this.getServletContext();

    //RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/gp");//转发的请求路径
    //requestDispatcher.forward(req,resp);//调用forward实现请求转发
    servletContext.getRequestDispatcher("/gp").forward(req,resp);
}

4、读取资源文件

Propersity

  • 在Java目录下新建propersity

  • 在resources目录下新建propersity

发现:都被打包到同一个路径下:classes,我们俗称这个路径为classpsth;

思路:需要一个文件流;

username=zhangsan
password=123456
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");

    Properties prop = new Properties();
    prop.load(is);//拿到文件的流
    String username = prop.getProperty("username");
    String password = prop.getProperty("password");

    resp.getWriter().print(username+":"+password);

}

6.6、HttpServletResponse

web服务器接收到客户端的请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的HttpServletResponse;

  • 如果要获取客户端请求过来的参数:找HttpServletRequest

  • 如果给客户端相应一些信息:找HttpServletResponse

1、简单分类

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

ServletOutputStream getOutputStream() throws IOException;

PrintWriter getWriter() throws IOException;

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

void setCharacterEncoding(String var1);

void setContentLength(int var1);

void setContentLengthLong(long var1);

void setContentType(String var1);


void setDateHeader(String var1, long var2);

void addDateHeader(String var1, long var2);

void setHeader(String var1, String var2);

void addHeader(String var1, String var2);

void setIntHeader(String var1, int var2);

响应的状态码

int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2、下载文件
  1. 向浏览器输出信息

  2. 下载文件

    1. 要获取下载文件的路径

    2. 获取下载的文件名

    3. 设置想办法让浏览器能够支持下载我们需要的东西

    4. 获取下载文件的输入流

    5. 创建缓冲区

    6. 获得OutputStream对象

    7. 将FileOutputStream写入到buffer缓冲区

    8. 使用OutputStream将缓冲区中的数据输出到客户端

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1. 要获取下载文件的路径
    String realPath = this.getServletContext().getRealPath("/Zombatar_1.jpg");
    System.out.println("下载文件的路径:"+realPath);
    // 2. 获取下载的文件名
    String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
    // 3. 设置想办法让浏览器能够支持下载我们需要的东西,中文文件名URLEncoder.encode编码,否则可能就会乱码
    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);
    }
    in.close();
    out.close();
}
3、验证码功能

验证怎么来的?

  • 前端实现

  • 后端实现,需要用到Java的图片类,生成一个图片类

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

    //如何让浏览器5秒刷新一次;
    resp.setHeader("refresh","3");
    //在内存在创建一个图片
    BufferedImage images = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
    //得到图片
    Graphics2D g = (Graphics2D)images.getGraphics();//笔
    //设置图片的背景颜色
    g.setColor(Color.white);
    g.fillRect(0,0,80,20);
    //给图片写数据
    g.setColor(Color.BLUE);
    g.setFont(new Font(null,Font.BOLD,20));
    g.drawString(makeNum(),0,20);
    //告诉浏览器,这个请求用图片的方式打开
    resp.setContentType("image/ipeg");
    //网站存在缓存,不让浏览器缓存
    resp.setDateHeader("expires",-1);
    resp.setHeader("Cache-Control","no-cache");
    resp.setHeader("Pragma","no-cache");

    //把图片写给浏览器
    ImageIO.write(images,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNum(){
    Random random = new Random();
    String num = random.nextInt(9999999) + "";
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 7 - num.length(); i++) {
        sb.append("0");
    }
    String s = sb.toString() + num;
    return num;
}
<servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>com.study.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/img</url-pattern>
</servlet-mapping>
4、实现重定向

一个web资源收到客户端收到客户端A的请求后,B会通知A客户端去访问另外一个web资源C,这个过程叫做重定向。

常见场景:

  • 用户登录

    void sendRedirect(String var1) throws IOException;

测试:

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

    /*resp.setHeader("location","/r/img");
        resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);//302*/

    resp.sendRedirect("/r/img");//重定向
}

面试题:请你聊聊重定向和转发的区别

相同点

  • 页面都会实现跳转

不同点

  • 请求转发的时候,url不会产生变化

  • 重定向的时候,url地址栏会发生变化

页面重定向

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("进入请求了");
    //处理请求
    String username = req.getParameter("username");
    String password = req.getParameter("password");

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

    //重定向的时候一定要注意路径问题,否则404
    resp.sendRedirect("/r/success.jsp");
}

index.jsp

<html>
<body>
<h2>Hello World!</h2>

<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
    用户名:<input type="text" name="username"> <br>
    密码:<input type="password" name="password"> <br>
    <input type="submit">
</form>
</body>
</html>

success.isp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>success</h1>
</body>
</html>

6.7、HttpServletRequest

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

1、获取参数、请求转发

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
//后台接收中文乱码问题
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
//通过请求转发
//这里的 / 代表当前的web应用
req.getRequestDispatcher(req.getContextPath()+"/success.jsp").forward(req,resp);
}

面试题:请你聊聊重定向和转发的区别

相同点

  • 页面都会实现跳转

不同点

  • 请求转发的时候,url不会产生变化; 307

  • 重定向的时候,url地址栏会发生变化; 302

7、Cookie、Session

7.1、会话

会话:用户打开一个浏览器,点击了很多超链接,访问了多个web资源,关闭浏览器;cookie

有状态会话:如:一个同学来过教室,下次再来教室,我们就会知道,这个同学曾经来过,称之为有状态会话

一个网站,怎么证明你来过?

  1. 服务器给客户端一个 信件 ,客户端下次访问服务端带上信件就可以了;cookie

  2. 服务器登记你来过了,下次你来的时候我来匹配你;session

7.2、保存会话的两种技术

cookie

  • 客户端技术(响应,请求)

session

  • 服务器技术,利用这个技术,可以保存用户的会话信息,我们就可以把信息或者数据放在Session!

常见问题:网闸登陆之后,你下次不用再登陆了,第二次访问直接就上去了。

7.3、Cookie
  1. 从请求中拿到cookie信息

  2. 服务器响应客户端cookie

    Cookie[] cookies = req.getCookies();//获得Cookie
    cookie.getName();//获得cookie中的key
    cookie.getValue();//获得cookie中的value
    new Cookie("lastLoginTime", System.currentTimeMillis() + "");//新建一个cookie
    cookie.setMaxAge(24 * 60 * 60);//设置Cookie的有效期
    resp.addCookie(cookie);//响应给客户端一个cookie

    Cookie:一般会保存在本地的用户目录下appdata;

    一个网站cookie是否存在上限!聊聊细节问题

    • 一个Cookie只能保存一个信息;

    • 一个web站点可以浏览器发送多个cookie,最多存在20个cookie;

    • Cookie大小有限制4kb

    • 300个浏览器上限

删除Cookie:

  • 不设置有效期,关闭浏览器,自动失效;

  • 设置有效期为0;

编码解码:

new Cookie("name", URLEncoder.encode("张三","UTF-8"));
URLDecoder.decode(cookie.getValue(),"UTF-8");

保存用户上一次访问的时间

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //服务器,告诉你,你来的时候,把这个时间封装成,一个 信件 ,你带信件来,我就知道你来

    //解决中文乱码
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");

    PrintWriter out = resp.getWriter();

    //cookie,服务器从客户端获得;
    Cookie[] cookies = req.getCookies();//这里返回数组,说明cookie可能存在多个

    //判断Cookie置否存在
    if(cookies != null){
        //如果存在,怎么办
        out.write("你上一次访问的时间是:");

        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            //获取cookie的名字
            if (cookie.getName().equals("lastLoginTime")){
                //获取cookie的值
                long lastLoginTime = Long.parseLong(cookie.getValue());
                Date date = new Date(lastLoginTime);
                out.write(date.toLocaleString());
            }
        }
    }else{
        out.write("这是您第一次访问本站");
    }
    //服务给客户端响应一个Cookie;
    Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
    //cookie有效期一天
    cookie.setMaxAge(24 * 60 * 60);
    resp.addCookie(cookie);
}

7.4、Session(重点)

什么是session:

  • 服务器会给每个用户(浏览器)创建一个Session对象;

  • 一个Session独占一个浏览器,只要浏览器没关,这个session就存在;

  • 用户登陆之后,整个网站都可以访问-->保存用户信息等

session和cookie的区别:

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存->可以保存多个

  • Session把用户的数据写到用户独占的session中,服务器端保存->保存重要的信息,减少服务器资源浪费

存储字符串:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //解决中文乱码
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");

    //得到session
    HttpSession session = req.getSession();

    //给session中存东西
    session.setAttribute("name","张三");

    //获取session的ID
    String sessionid = session.getId();

    //判断Session是不是新建的
    if(session.isNew()){
        resp.getWriter().write("session创建成功,ID:"+sessionid);
    }else{
        resp.getWriter().write("session已经在服务器中存在了,ID:"+sessionid);
    }

    //session 创建的时候做了什么事情
    //        Cookie jsessionid = new Cookie("JSESSIONID", sessionid);
    //        resp.addCookie(jsessionid);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //解决中文乱码
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");

    //得到session
    HttpSession session = req.getSession();

    String name = (String) session.getAttribute("name");

    System.out.println(name);


}

存储对象:

package com.study.pojo;

public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
//给session中存东西
session.setAttribute("name",new Person("张三",1));

//得到session
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("name");
System.out.println(person.toString());

会话自动过期:web.xml配置

<!--设置session默认的失效时间-->
<session-config>
    <!--15分钟后自动失效,以分钟为单位-->
    <session-timeout>15</session-timeout>
</session-config>

8、JSP

8.1、什么是JSP

JavaServerPages:Java服务器端页面,也和servlet一样,用于开发动态web技术

最大的特点:

  • 写jsp就像在写HTML

  • 区别:

    • HTML只给用户提供静态数据;

    • JSP中可以嵌入Java代码,为用户提供动态数据;

8.2、JSP原理

JSP到底怎么执行

  • 代码层面没有问题

  • 服务器内部工作

    tomcat中有一个work目录;

    IDEA中使用Tomcat的会在IDEA中的tomcat中生成一个work目录

8.3、JSP基础语法

任何语言都有自己的语法,Java中有,jsp作为Java的一种应用,它拥有一些自己扩充的语法(了解,知道即可!),Java所有语法都支持!

JSP表达式
<%--  JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
<%=new java.util.Date()%>

jsp脚本片段
<%--  jsp 脚本片段--%>
<%
  int sum = 0;
  for (int i = 0; i < 100; i++) {
    sum += i;
  }
  out.print("<h1>Sum="+sum+"</h1");
%>

脚本片段的再实现

<%
  int x = 10;
  out.print("x="+x);
%>
  <p>这是一个JSP文档</p>
<%
  int y = 2;
  out.println(y);
%>
  <hr>

<%--在代码中嵌入HTML元素--%>
<%
  for (int i = 0; i < 100; i++) {

%>
<h1>Hello,World <%=i%></h1>
<%
  }
%>

JSP声明
<%!
  static {
  System.out.println("Loading Servlet!");
  }
  
  private int globalvar = 0;
  public void study(){
    System.out.println("进入了study方法!");
  }
%>

JSP声明:会被编译到JSP生成的Java的类中,其他的就会生成到——jspService方法中!

在JSP中,嵌入Java代码即可!

<%%>
<%=%>
<%!%>
<%----%>

JSP的注释,不会显示在客户端,HTML的就会!

8.4、JSP指令
<%@ page args... %>
<%@include file=""%>

<%--@include会将两个页面合二为一--%>
<%@include file="common/header.jsp"%>
<h1>网页主体</h1>
<%@include file="common/footer.jsp"%>

<%--jsp标签
jsp:include:拼接页面,本质还是三个
--%>
<jsp:include page="/common/header.jsp"/>
<h1>网页主体</h1>
<jsp:include page="/common/footer.jsp"/>

8.5、9大内置对象
  • PageContext 存东西

  • Request 存东西

  • Response

  • Session 存东西

  • Application [ServletContext] 存东西

  • config [ServletConfig]

  • out

  • page(不用了解)

  • exception

pageContext.setAttribute("name1","张三1号");//保存的数据只在一个页面有效
request.setAttribute("name2","张三2号");//保存的数据只在一次会话中有效,请求转发会携带这个数据
session.setAttribute("name3","张三3号");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","张三4号");//保存的数据只在服务器中有效,从打开服务器到关闭服务器

request:客户端向服务端发送请求,产生的数据,用户看完就没了,比如:新闻;

session:客户端向服务器发送请求,产生的数据,用户用玩一会还有用,比如,购物车

application:客户端向服务端发送请求,产生的数据,一个用户用完了,其他用户还可以在用,比如聊天数据;

8.6、JSP标签、JSTL标签、EL表达式
<!--JSTL表达式的依赖-->
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
<!--standsrd标签ku-->
        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

EL表达式: ${ }

  • 获取数据

  • 执行运算

  • 获取web开发常用对象

JSP标签

<%--
http://localhist:8080/jsptage.jsp?name=zhangsan&age=3
--%>
<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="zhangsan"/>
    <jsp:param name="age" value="3"/>
</jsp:forward>

JSTL表达式

JSTL标签库的使用就是为了弥补HTML标签的不足;他自定义许多标签,可以供我们使用,标签的功能和Java代码一样!

  • 格式化标签

  • SQL标签

  • XML标签

  • 核心标签(掌握部分)

JSTL标签使用步骤:

  1. 引入对应的taglib

  2. 使用其中的方法

  3. 在Tomcat 中也需要引入 JSTL 的包,否则会报错,JSTL解析错误

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%--引入JSTL核心标签,我们才能使用JSTL标签 core--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h4>if测试</h4>

<hr>

<form action="coreif.jsp" method="get">
<%--
EL表达式获取表单中的数据
${param,参数名}
--%>
    <input type="text" name="username" value="${param.username}">
    <input type="submit" value="登录">

</form>
<%--判断如果提交的用户名是管理员,则登陆成功--%>
<%--<%
    if(request.getParameter("username").equals("admin")){
        out.write("登录成功!");
    }
%>--%>

<c:if test="${param.username=='admin'}" var="isAdmin">
    <c:out value="管理员欢迎恁!"/>
</c:if>
<%--闭合标签--%>
<c:out value="${isAdmin}"/>

</body>
</html>

判断

<%--定义一个变量score,值为85--%>
<c:set var="score" value="85"/>
<c:choose>
    <c:when test="${score>=90}">
        你的成绩为优秀
    </c:when>
    <c:when test="${score>=80}">
        你的成绩为良好
    </c:when>
    <c:when test="${score>=70}">
        你的成绩为一般
    </c:when>
    <c:when test="${score>=60}">
        你的成绩为及格
    </c:when>
    <c:when test="${score<=60}">
        你的成绩为不合格
    </c:when>
</c:choose>
<%
    ArrayList<Object> people = new ArrayList<>();
    people.add(0,"张三");
    people.add(1,"李四");
    people.add(2,"王五");
    people.add(3,"赵六");
    people.add(4,"钱七");
    request.setAttribute("list",people);
%>
<%--
var:每一次遍历出来的变量
items:要遍历的对象
--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/> <br>
</c:forEach>

<hr>

<c:forEach var="people" items="${list}" begin="1" end="3" step="2">
    <c:out value="${people}"/> <br>
</c:forEach>

9、JavaBean

实体类

JavaBean有特定的写法:

  • 必须有一个无参构造

  • 属性必须私有化

  • 必须有对应的get/set方法;

一般用来和数据库的字段做映射 ORM;

ORM:对象关系映射

  • 表-->类

  • 字段-->属性

  • 行记录-->对象

people表

idnameageaddress
1张三2America
2李四18China
3王五100earth
class People{
    private int id;
    private String name;
    private int age;
    private String address;
}
class A{
    new People(1,"张三",2,"America");
    new People(2,"李四",18,"America");
    new People(3,"王五",100,"America");
}

<%
//    People people = new People();
//    people.setAddress();
//    people.setAge();
//    people.setId();
//    people.setName();
    
%>

<jsp:useBean id="people" class="com.study.pojo.People" scope="page"/>

<jsp:setProperty name="people" property="address" value="earth"/>
<jsp:setProperty name="people" property="id" value="3"/>
<jsp:setProperty name="people" property="age" value="100"/>
<jsp:setProperty name="people" property="name" value="王五"/>

姓名:<jsp:getProperty name="people" property="name"/>
id:<jsp:getProperty name="people" property="id"/>
年龄:<jsp:getProperty name="people" property="age"/>
地址:<jsp:getProperty name="people" property="address"/>

10、MVC三层架构

什么是MVC:Model View Controller 模型、视图、控制器

10.1、前期

用户直接访问控制层,控制层就可以直接操作数据库

servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求,响应,试图跳转,处理JDBC,处理业务代码,处理逻辑代码

架构:没有什么是加一层解决不了了的!
程序员调用
  |  
 JDBC
  |
Mysql Oracle sqlServer
10.2、三层架构

Model

  • 业务处理:业务逻辑(service)

  • 数据持久层:CRUD(Dao)

View

  • 展示数据

  • 提供链接发起的Servlet请求(a,from,img...)

Controller(Servlet)

  • 接受用户的请求:(req:请求参数,session信息)

  • 交给业务层处理对应的代码

  • 控制视图的跳转

登录-->接受用户的登录请求-->处理用户的请求(获取用户登陆的参数,username,password)-->交给业务层处理登陆业务(判断用户密码是否正确:事务)-->Dao层查询用户名和密码是否正确

11、Filter(重点)

filter:过滤器,用来过滤网站的数据;

  • 处理中文的乱码

  • 登陆验证

Filter开发步骤

  1. 导包

  2. 编写过滤器

    1. 导包不要错

      编写过滤器

      package com.study.filter;
      
      import javax.servlet.*;
      import java.io.IOException;
      
      public class CharacterEncodingFiliter implements Filter {
          //初始化:web服务器启动,就可以初始化了,随时的等待过滤对象的出现
          @Override
          public void init(FilterConfig filterConfig) throws ServletException {
              System.out.println("CharacterEncodingFiliter初始化");
          }
          //chain:链
          /*
          1.过滤中的所有代码,再过滤特定请求的时候都会执行
          2.必须让过滤器继续通行
           filterChain.doFilter(servletRequest,servletResponse);
          * */
          @Override
          public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
              servletRequest.setCharacterEncoding("utf-8");
              servletResponse.setCharacterEncoding("utf-8");
              servletResponse.setContentType("text/html;charset=utf-8");
      
              System.out.println("CharacterEncodingFiliter执行前");
              filterChain.doFilter(servletRequest,servletResponse);//让我们的请求继续走,如果不写程序到这里就被拦截停止了
              System.out.println("CharacterEncodingFiliter执行后");
          }
          //销毁:web服务器关闭的时候,过滤器会销毁
          @Override
          public void destroy() {
              System.out.println("CharacterEncodingFiliter销毁");
          }
      }
  3. 注册web.xml

    <servlet>
        <servlet-name>ShowServlet</servlet-name>
        <servlet-class>com.study.servlet.ShowServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ShowServlet</servlet-name>
        <url-pattern>/servlet/show</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ShowServlet</servlet-name>
        <url-pattern>/show</url-pattern>
    </servlet-mapping>
    
    <filter>
        <filter-name>CharacterEncodingFiliter</filter-name>
        <filter-class>com.study.filter.CharacterEncodingFiliter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFiliter</filter-name>
        <!--        只要是servlet的请求,就会经过这个过滤器-->
        <url-pattern>/servlet/*</url-pattern>
        <!--        <url-pattern>/*</url-pattern>-->
    </filter-mapping>

12、监听器

实现一个监听器的接口;(有N钟)

  1. 编写一个监听器

    实现监听器

    //通过网站统计在线人数:统计session
    public class OnlineCountListener implements HttpSessionListener {
        //创建session囧听:看你的一举一动
        //一旦创建session,就会触发这个
        @Override
        public void sessionCreated(HttpSessionEvent httpSessionEvent) {
            //httpSessionEvent.getSession() 拿取网站的上下文
            ServletContext ctx = httpSessionEvent.getSession().getServletContext();
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(1);
            }else{
                int count = onlineCount.intValue();
                onlineCount = new Integer(count + 1);
            }
            ctx.setAttribute("OnlineCount",onlineCount);
        }
    
        //销毁session监听
        //一旦销毁session,就会触发这个
        @Override
        public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
            ServletContext ctx = httpSessionEvent.getSession().getServletContext();
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(0);
            }else{
                int count = onlineCount.intValue();
                onlineCount = new Integer(count - 1);
            }
            ctx.setAttribute("OnlineCount",onlineCount);
        }
        /*
        * session销毁
        * 1.手动销毁 getsession().invalidate
        * 2.自动销毁 */
    }
    
  2. web.xml中注册监听器

    <!--    注册监听器-->
    <listener>
        <listener-class>com.study.listener.OnlineCountListener</listener-class>
    </listener>
  3. 看情况是否使用

13、过滤器、监听器的应用

package com.study.listener;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("HELLO");//新建一个窗体
        Panel panel = new Panel(null);//面板
        frame.setLayout(null);//设置窗体的布局

        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(0,0,255));

        panel.setBounds(150,150,250,250);
        panel.setBackground(new Color(0,255,255));

        frame.add(panel);

        frame.setVisible(true);

        //监听事件,监听关闭事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
            }
        });
    }
}

用户登陆之后才能进入主页,用户注销后就不能进入主页了!

  1. 用户登录之后,向Session中放如用户的数据

  2. 进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!

    Sysfilter.class

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // ServletRequest  HttpServletRequest
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
    
        //servletRequest1.getSession().getAttribute("USER_SESSION");
    
        if(servletRequest1.getSession().getAttribute(Constant.USER_SESSION) == null){
            servletResponse1.sendRedirect("/error.jsp");
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    LoginServlet.class

//LoginServlet
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端请求的参数
        String username = req.getParameter("username");

        if (username.equals("admin")){//登录成功
            req.getSession().setAttribute(Constant.USER_SESSION,req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else{//登陆失败
            resp.sendRedirect("/sys/error.jsp");
        }
    }

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

LogoutServlet.class

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
        if(user_session != null){
            req.getSession().removeAttribute(Constant.USER_SESSION);
            resp.sendRedirect("/Login.jsp");
        }else{
            resp.sendRedirect("/Login.jsp");
        }
    }

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

Constant.class

public class Constant {
    public final static String USER_SESSION = "USER_SESSION";
}

Login.jsp

<h1>登录</h1>
<form action="/servlet/login" method="post">
    <input type="text" name="username">
    <input type="submit">
</form>

success.jsp

<%--<%
    Object userSession = request.getSession().getAttribute(Constant.USER_SESSION);
    if (userSession == null){
        response.sendRedirect("/Login.jsp");
    }
%>--%>


<h1>主页</h1>

<p><a href="/servlet/logout">注销</a></p>

error.jsp

<h1>错误</h1>
<h3>没有权限,用户名错误</h3>

<a href="/Login.jsp">返回登陆页面</a>

14、JDBC

什么是JDBC:Java连接数据库

需要jar包的支持:

  • java.sql

  • javax.sql

  • mysql-conneter-java..连接驱动(必须要导入)

实验环境搭建

CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
email VARCHAR(60),
birthday DATE
);

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','zs@qq.com','2000-01-01');

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','ls@qq.com','2000-01-01');

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','ww@qq.com','2000-01-01');

SELECT * FROM users

导入数据库依赖

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

编写代码

package com.study.test;

import java.sql.*;

public class TestJDBC {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解决中文乱码
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.向数据库发送对象statement:CURD
        Statement statement = connection.createStatement();
        //4.编写SQL
        String sql = "SELECT * FROM users";
        //5.执行查询SQL。返回一个ResultSet:结果集
        ResultSet rs = statement.executeQuery(sql);

        while(rs.next()){
            System.out.println("id="+rs.getObject("id"));
            System.out.println("name="+rs.getObject("name"));
            System.out.println("password="+rs.getObject("password"));
            System.out.println("email="+rs.getObject("email"));
            System.out.println("birthday="+rs.getObject("birthday"));
        }
        //6.关闭连接,释放资源(一定要做)先开后关
        rs.close();
        statement.close();
        connection.close();
    }
}

JDBC固定步骤:

  1. 加载驱动

  2. 连接数据库,代表数据库

  3. 向数据库发送SQL对象Statement:CRUD

  4. 编写SQL(根据业务,不同的SQL)

  5. 执行SQL

  6. 关闭连接

package com.study.test;

import java.sql.*;

public class TestJDBC2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解决中文乱码
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.编写SQL
        String sql = "INSERT INTO users(id,`name`,`password`,email,birthday) VALUES(?,?,?,?,?);";
        //4.预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //给参数赋值
        preparedStatement.setInt(1,1);
        preparedStatement.setString(2,"张三");
        preparedStatement.setString(3,"123456");
        preparedStatement.setString(4,"zs@qq.com");
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
        //5.执行sql
        int i = preparedStatement.executeUpdate();
        if (i > 0){
            System.out.println("插入成功!");
        }
        //6.关闭连接,释放资源(一定要做)先开后关
        preparedStatement.close();
        connection.close();
    }
}

事务

要么都成功,要么都失败

Junit单元测试

依赖

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

简单使用

@Test注解指在方法上有效,只要加了注解的方法,就可以直接运行

package com.study.test;

import org.junit.Test;

public class TestJDBC3 {

    @Test
    public void test(){
        System.out.println("hello");
    }
}

package com.study.test;

import org.junit.Test;

import java.sql.*;

public class TestJDBC3 {

    @Test
    public void test() {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解决中文乱码
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        Connection connection = null;
        try{
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.连接数据库,代表数据库
            connection = DriverManager.getConnection(url, username, password);
            //3.编写SQL
            connection.setAutoCommit(false);

            String sql = "updata account set money=monsy-100 where name='A'";
            connection.prepareStatement(sql).executeUpdate();

            //制造错误
            int i = 1 / 0;

            String sql2 = "updata account set money=monsy-100 where name='A'";
            connection.prepareStatement(sql2).executeUpdate();

            connection.commit();
            System.out.println("success");
        }catch(Exception e){
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        
    }
}
  • 31
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值