Java web 学习笔记

Java Web

1、web基础

1.1、基本概念

  • web开发:网页开发,分为 静态web动态web
    • 静态web:由 html 、css、 JavaScript 共同组成,提供给所有人看,数据永远不变。
    • 动态web:提供给所有人看的数组,在不同时间,不同地点看到的数据不相同,类似淘宝的 千人千面
      • 需要的技术:Servlet/JSPASPPHP

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

1.2、web应用程序

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

  • *.html 多个web资源,在被外界访问并提供服务

  • URL:统一资源定位符

  • 很多的 web资源 房子同一个文件夹下,组成一个完整的服务,称为 web应用程序 --> Tomcat:服务器

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

    • html、css、js
    • jsp、servlet
    • Java程序
    • jar包
    • 配置文件(Properties

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

1.3、静态web

  • 如果服务器上存在 *.html,我们就可以直接进行读取。

  • 静态web的缺点
    • web页面无法动态更新,所有用户看到都是同一个页面
    • 它无法与数据库交互(数据无法持久化,用户无法交互)

1.4、动态Web

页面会动态展示:“Web的页面展示效果会因人而异,类似于淘宝的千人千面”

2、web服务器

2.1、主流技术

ASP:

  • 在HTML中嵌套VB脚本,ASP+COM
  • 因为是互相嵌套,页面混乱,维护成本高。
  • window 自带 iis (Internet Information Services) 服务器,一般不会启动

PHP:

  • PHP 开发速度快,功能强大,跨平台,代码很简单(70%)
  • 无法承载大访客量(局限性)

JSP/Servlet:

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

  • 可以承载三高问题带来的影响;

    2.2、web服务器

**IIS:**微软的,ASP,window自带的。

Tomcat:Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,由Apache、Sun 和其他一些公司及个人共同开发而成。由于有了Sun 的参与和支持,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 规范。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。

3、Tomcat

3.1、安装Tomcat

  • 下载 Tomcat 下载地址(64位电脑的): https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-9/v9.0.43/bin/apache-tomcat-9.0.43-windows-x64.zip
  • 将下载的文件 解压放入需要安装的位置
  • 使用Tomcat 9 尽量不要使用 Tomcat 10 因为 对应 javax.servlet-api 5 版本,后期调试会出问题

3.2、Tomcat启动和配置

文件夹信息

启动和关闭Tomcat

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

可能遇见的问题:

  • Java环境变量没有配置
  • 闪退属于兼容性问题
  • **乱码问题:**配置文件中设置

3.3、配置

可以配置启动的 端口号 主机名称 localhost

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

<!--默认的主机名为:"localhost:127.0.0.1"
	默认网站存放位置:"Webapps"
-->
<Host name="localhost"  appBase="webapps"
      unpackWARs="true" autoDeploy="true">

谈谈网站如何进行访问(面试题)

  1. 输入域名回车;
  2. 检查本机的 “C:\Windows\System32\drivers\etc\hosts” 配置文件下查找有没有这个域名映射(有直接放回映射的 IP地址
  3. 如果没有去 DNS 服务器查找。还是没有就放回找不到。

4、HTTP

4.1、什么是HTTP

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

**Https:**安全的超文本传输协议,443端口

4.2、HTTP请求

客户端发起请求(Request)–服务器

以百度为例:

Request URL: https://www.baidu.com/
Request Method: GET
Status Code: 200 OK
Remote Address: 163.177.151.109:443
//上下一一对应   
请求 URL: https://www.baidu.com/
请求方法: GET
状态代码: 200 OK
远程地址: 163.177.151.109: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/Post,Head,Delete,Put,Tract
    • Get:携带参数少,传输不安全,但是高效
    • Post:携带参数无限制,传输安全,但是不高效
  2. 请求头

    Accept:	告诉浏览器,它支持的数据类型
    Accept-Encoding:	支持的编码格式
    Accept-Language: zh-CN,zh;q=0.9	 告诉浏览器,它的语言环境
    Cache-Control:		缓存控制		
    Connection: keep-alive	告诉浏览器请求完成是断开还是保持连接	连接:保持连接
    Host: 主机
    

4.3、HTTP响应

Cache-Control: private  	缓存控制
Connection: keep-alive		连接:保持连接
Content-Encoding: gzip		编码
Content-Type: text/html;charset=utf-8	文本类型和解码类型

1、响应体:

Accept:	告诉浏览器,它支持的数据类型
Accept-Encoding:	支持的编码格式
Accept-Language: zh-CN,zh;q=0.9	 告诉浏览器,它的语言环境
Cache-Control:		缓存控制		
Connection: keep-alive	告诉浏览器请求完成是断开还是保持连接	连接:保持连接
Host: 主机
Refresh: 告诉客户端多久刷新一次
Location:让网页重新定位;

2、响应状态码(重点)

200:请求响应成功

3xx:请求重定向

4xx:找不到资源 404

5xx:服务器代码错误 500 502:网关错误

常见面试题:

当你在浏览器中地址栏输入地址并回车的一瞬间到页面展示回来,经历了什么?

在我们输入网址按下回车后,DNS服务器会通过当前网址解析这一网址的ip;在查找到IP之后,浏览器会向服务器发起一个tcp连接请求,此请求包含三次握手,如下:
第一次握手:建立链接时,客户端浏览器会发送syn包到服务器,并进入SYS_SENT状态,等待服务器的确认;

第二次握手:服务器收到syn包后,必须确认客户端的syn,同时之间发送一个ack包,即是syn加ack包,此时服务器进入SYN_RECV状态,此时服务器被动打开后,接收到客户端的syn并且发送了ack时状态;

第三次握手:客户端接收到服务器的syn+ack包后,给服务器发送确认包ack,包发送完毕之后,客户端和服务器端进入ESTABLISHED(tcp连接成功)状态,完成了第三次握手。
当三次握手结束后客户端和服务器端就建立好了连接,此时tcp协议断开,开始访问服务器下的默认index.html页面,并调用该访问的资源文件,展示相应的内容。

5、Maven

我们为什么需要学习Maven

  1. JavaWeb 开发中需要大量的 jar 包,我们需要手动导入
  2. Maven 能够自动帮我们导入和配置这个jar包

5.1、Maven项目架构管理工具

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

  • 有约束,不要去违反。
  • Maven会规定我们如何去编写Java代码,必须要按照这个规范来;
  • 高级之处在于,会帮助你导入一个 jar 包所需要的其他 jar

5.2、下载安装Maven

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

Maven下载地址(window64位的):https://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.zip

下载完成后解压到需要安装的位置

5.3、Maven配置

  1. 配置环境变量

    • M2_HOME maven目录下的bin目录
    • MAVEN_HOME maven目录
    • 在系统的path中配置 %MAVEN_HOME%\bin
  2. 配置 Maven 的下载源(配置镜像)

    • 作用:解决访问外国网站过慢,下载慢的问题,建议使用阿里云镜像

      1. 进入maven安装目录的 conf 文件夹下的 settings.xml 文件在如下地方添加以下配置

        <mirror>
            <id>nexs-aliyun</id>
            <mirrorOf>*,!jeecg-snapshots</mirrorOf>
            <name>Nexus aliyun</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
        </mirror>
        <!--两个都可以用,任选其一,或者同时配两个也可以-->
        <mirror>
            <id>nexs-aliyun</id>
            <mirrorOf>central</mirrorOf>
            <name>Nexus aliyun</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
        </mirror>
        

  3. 配置本地仓库

    1. 推荐在maven安装目录下新建 repository 文件夹,用于存放下载的东西(jar包,配置文件)

    2. 还是在maven安装目录的 conf 文件夹下的 settings.xml 文件在如下地方添加本地仓库文件夹位置

      <localRepository>D:\apache-maven-3.6.3\repository</localRepository>
      

5.4、在IDEA中使用Maven

  1. 创建Webapps Maven项目




  1. 创建一个普通的Maven 项目(最干净的Maven项目

  1. 标记文件夹功能

5.5、在IDEA中配置Tomcat

  1. 添加配置


解决警告问题:注意必须是Web应用程序才能配置Tomcat服务器,因为我们访问一个网站,需要指定一个文件夹的名字,所以会出现这个问题,本质也是在Tomcat下的Webapps文件夹下新建一个目录,存放文件;



5.6、pom.xml

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.wyx</groupId>
    <artifactId>JavaWeb</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    
<!--子模块-->
    <modules>
        <module>Servlet-01</module>
    </modules>

<!--JDK版本-->
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>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>Servlet-01</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>

5.7、Maven问题

Maven由于约定大于配,我们之后可能遇见自己写的配置文件,无法被导出或者生效,解决方案:

在pom.xml 文件中的 build 下加入以下代码

<!--注意把前后的 build 去掉-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

5.8、遇见的常见问题

  1. Tomcat闪退

    JDK环境配置错误

  2. IDEA每次都需要重新配置

    在全局项目中配置,就是不进项目进行配置就可以了

  3. maven默认web项目中web.xml版本问题,版本太老,建议设置 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>
    
  4. maven仓库的使用

    仓库地址:https://mvnrepository.com/

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
    <scope>provided</scope>
</dependency>

6、Servlet

6.1、Servlet 简介

  • Servlet就是sun公司开发动态web的一门技术
  • Sun 在这些API中提供一个接口叫做:Servlet,如果想开发一个Servlet程序,只需要
    • 编写一个类,实现Servlet 接口
    • 把开发好的 Java 类部署到服务器中

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

6.2、HelloServlet

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

  1. 构建一个普通的Maven项目,删掉里面的 src 目录,这个空的工程就是Maven的主工程。

  2. 向主工程的pom.xml文件添加如下依赖

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
    </dependency>
    
  3. 在主工程中新建 Maven项目的 Webapps 模板项目。

  4. 关于maven 父子工程的理解(父工程的依赖子工程会继承

    父项目中会有

    <modules>
        <!--子项目名-->
        <module>Servlet-01</module>  
    </modules>
    

    子项目中会有(注意检查这里可能不会自动添加需要自行添加

    <parent>
        <!--父项目的GAV-->
        <groupId>com.wyx</groupId>
        <artifactId>JavaWeb</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    
  5. Maven环境优化

    1. 修改web.xml为最新的
    2. 将maven的结构搭建完整
  6. 编写Servlet程序

package com.wyx;

import javax.servlet.ServletException;
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 {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();      //响应流
       writer.print("Hello Servlet"); 
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //无论走什么都是走 doGet() 方法
        doGet(req, resp);
    }
}
  1. 编写Servlet的映射

    为什么需要写映射:我们写的是Java程序,但是需要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要再web服务中注册我们写的 Servlet,还需要给他一个浏览器可以访问的路径,在web.xml中添加以下的配置

    <!--注册Servlet-->
    <servlet>
        <!--注册名字-->
        <servlet-name>hello</servlet-name>
        <!--注册的类-->
        <servlet-class>com.wyx.helloServlet</servlet-class>
    </servlet>
    <!--Servlet的请求路径,一个 Servlet 需要一个注册路径即一个(servlet-mapping)-->
    <servlet-mapping>
        <!--上面注册的名字-->
        <servlet-name>hello</servlet-name>
        <!--访问路径-->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
  2. 配置 Tomcat 参考上面

  3. 启动测试

6.3、Servlet运行原理

Servlet是由Web服务器调用,web服务器在收到浏览器请求之后,会

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>/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>
    
    <servlet-mapping>
        <!--默认请求路径,会优先显示,不能乱使用-->
        <servlet-name>hello</servlet-name>
        <url-pattern>*</url-pattern>
    </servlet-mapping>
    
  4. 指定一些后缀或者前缀。

    <servlet-mapping>
        <!--指定后缀
    		*前面不能加项目映射路劲 /
    	-->
        <servlet-name>hello</servlet-name>
        <url-pattern>*.wyx</url-pattern>
    </servlet-mapping>
    
  5. 优先级问题

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

6.5、ServletContext

架构图

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

  • 共享数据

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

    一个Servlet保存(setAttribute(“键”,值))到ServletContsxt里面,另一个利用ServletContsxt的取数据(getAttribute(“键”))

    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);//将一个数据保存到了ServletContext中 
            //void setAttribute(String var1, Object var2);
    
        }
    }
    
    public class GetServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext context = this.getServletContext();
            String username = (String)context.getAttribute("username");
    		//设置响应格式,否则中文默认GBK格式在浏览器上显示会乱码
    	    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);
    	}
    
    }
    
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>cn.zafu.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>getc</servlet-name>
        <servlet-class>cn.zafu.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>
    <!--*直接请求/getc是拿不到“username”的值的(null),需要先请求一下/hello-->
    
  • 获取初始化参数
    在web.xml中

<!--配置一些web应用初始化参数-->
<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>

获取

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	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();
        System.out.println("进入了sd4");
        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
        requestDispatcher.forward(req,resp);//调用forward实现请求转发
        //合并写  context.getRequestDispatcher("/gp").forward(req,resp);
    }
    
  • 读取资源文件:Properties

    1. 在java目录下新建properties (这里需要使用maven资源导出问题,不然不会导出)
    2. 在resources目录下新建properties
    3. 发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:

    ​ 思路:需要一个文件流;

username=root12312
password=zxczxczxc
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/a.properties");
        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");
        resp.getWriter().print(user+":"+pwd);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

6.6、HttpServletResponse

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的 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);
      void addIntHeader(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. 要获取下载文件的路径

    3. 下载的文件名是啥?

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

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

    6. 创建缓冲区

    7. 获取OutputStream对象

    8. 将FileOutputStream流写入到buffer缓冲区

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

      @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          // 1. 要获取下载文件的路径
          String realPath = "F:\\班级管理\\西开【19525】\\2、代码\\JavaWeb\\javaweb-02-servlet\\response\\target\\classes\\秦疆.png";
          System.out.println("下载文件的路径:"+realPath);
          // 2. 下载的文件名是啥?
          String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
          // 3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名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 的图片类,生产一个图片

    2. package com.kuang.servlet;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.Random;
    
    public class ImageServlet extends HttpServlet {@Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            //如何让浏览器3秒自动刷新一次;
            resp.setHeader("refresh","3");
    
            //在内存中创建一个图片
            BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
            //得到图片
            Graphics2D g = (Graphics2D) image.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/jpeg");
            //网站存在缓存,不让浏览器缓存
            resp.setDateHeader("expires",-1);
            resp.setHeader("Cache-Control","no-cache");
            resp.setHeader("Pragma","no-cache");
    
            //把图片写给浏览器
            ImageIO.write(image,"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");
            }
            num = sb.toString() + num;
            return num;
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }  
    }
    
  4. 实现重定向

    B一个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(302);
         */
        resp.sendRedirect("/r/img");//重定向
    }
    

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

    相同点:页面都会实现跳转
    不同点:请求转发的时候,url不会产生变化, 307 重定向时候,url地址栏会发生变化;302

  5. 简单实现登录重定向(例子)

    <%--这里提交的路径,需要寻找到项目的路径--%>
    <%--${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>
    
    @Override
    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);
    
        //重定向时候一定要注意,路径问题,否则404;
        resp.sendRedirect("/r/success.jsp");
    }
    
    <servlet>
        <servlet-name>requset</servlet-name>
        <servlet-class>com.kuang.servlet.RequestTest</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>requset</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    
    <%@ 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. 获取前端传递的参数

  2. 请求转发 登录界面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>登录</title>
    </head>
    <body>
    <h1>登录</h1>
    <div>
        <form action="${pageContext.request.contextPath}/login" method="post">
            <span>用户:</span><input type="text" name="username"><br>
            <span>密码:</span><input type="password" name="password"><br>
            <span>爱好:</span><input type="checkbox" name="hobbys" value="打球">打球
            <input type="checkbox" name="hobbys" value="抓鱼">抓鱼
            <input type="checkbox" name="hobbys" value="游泳">游泳<br>
            <input type="submit">
        </form>
    </div>
    </body>
    </html>
    
    <%--
      Created by IntelliJ IDEA.
      User: 王玉星
      Date: 2021/3/6
      Time: 13:51
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>登录</title>
    </head>
    <body>
        <h1>登录成功</h1>
    </body>
    </html>
    
	@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("=============================");
    //后台接收中文乱码问题
    System.out.println(username);
    System.out.println(password);
    System.out.println(Arrays.toString(hobbys));
    System.out.println("=============================");
    System.out.println(req.getContextPath());
    //通过请求转发
    //这里的 / 代表当前的web应用
    req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
}

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

相同点:页面都会实现跳转
不同点:请求转发的时候,url不会产生变化 307,重定向时候,url地址栏会发生变化; 302

7、Cookie、Session

7.1、会话(Session)

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

有状态会话:浏览器访问一个资源,下一次,再次访问时,知道之前访问过。

一个网站,怎么证明你来过?
客户端 服务端
服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了; cookie

客户端 : 服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了; cookie
服务端:服务器登记你来过了,下次你来的时候我来匹配你; seesion

7.2、保存会话的两种技术

cookie

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

session

  • 服务器技术,利用这个技术,可以保存用户的会话信息?可将信息或数据放在 session 中

常见应用:登录网站后,下一次访问不需要登录

7.3、Cookie

  1. 从请求中拿到 cookie 信息
  2. 服务器响应给客户端 cookie
Cookie[] cookies = req.getCookies(); //获得Cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的vlaue
new Cookie("lastLoginTime", System.currentTimeMillis()+""); //新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie的有效期
resp.addCookie(cookie); //响应给客户端一个cookie

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

  • 一个 Web 站点可以给浏览器发送多个 Cookie,最多存放 20 个 cookie;
  • cookie 大小有限制 4kb;
  • 300 个 cookie 浏览器上限

删除 Cookie;

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

编码解码:解决乱码问题

URLEncoder.encode("秦疆","utf-8")		//编码
URLDecoder.decode(cookie.getValue(),"UTF-8")   //解码

7.4 Session(重点)

  1. 什么是 Session ?

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

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

    • 用户登录之后,整个网站它都可以访问!-> 保存用户的信息;保存购物车的信息…

  2. Session 和 cookie 的区别:

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

    • Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费),过多浏览器会卡

    • Session 对象由服务创建;

  1. 使用场景:
  • 保存一个登录用户的信息;

  • 购物车信息;

  • 在整个网站中经常会使用的数据,我们将它保存在 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",new Person("秦疆",1));
        //获取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 cookie = new Cookie("JSESSIONID",sessionId);
//        resp.addCookie(cookie);
        
        //得到Session
        HttpSession session = req.getSession();
		//获取Session中Attribute存的值
        Person person = (Person) session.getAttribute("name");

        System.out.println(person.toString());
		
        HttpSession session = req.getSession();
        //移除Session中Attribute存的值
        session.removeAttribute("name");
        //手动注销Session
        session.invalidate();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
<!--web.xml配置过期时间-->
<!--设置Session默认的失效时间-->
<session-config>
    <!--15分钟后Session自动失效,以分钟为单位-->
    <session-timeout>15</session-timeout>
</session-config>

8、JSP

8.1、什么 JSP

Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!

最大的特点:

写JSP就像在写HTML

区别:

  • HTML只给用户提供静态的数据
  • JSP 页面中可以嵌入Java 代码,为用户提供动态数据;

8.2、JSP 原理

服务器内部工作:
Tomcat 中有一个 work 工作目录;
IDEA 中使用 Tomcat 的会在 IDEA 中 Tomcat 中生产一个 work 目录

文件夹位置:

C:/用户/当前用户/AppData/Local/JetBrains/IntelliJIdea2020.3(版本)/tomcat/f80e8f26-30f6-43c0-a446-fbd8f03a7ef8(看项目,解析不一样)/work/Catalina/localhost/ROOT

发现页面转变成了 Java 程序

浏览器向服务器发送请求,不管访问什么资源,起始都是在访问 Servlet !

JSP 最终也会被转换成一个 Java 类!
JSP 本质上就是一个 Servlet

//初始化
  public void _jspInit() {
      
  }
//销毁
  public void _jspDestroy() {
  }
//JSPService
  public void _jspService(.HttpServletRequest request,HttpServletResponse response)
  1. 判断请求
  2. 内置一些对象
final javax.servlet.jsp.PageContext pageContext;  //页面上下文
javax.servlet.http.HttpSession session = null;    //session
final javax.servlet.ServletContext application;   //applicationContext
final javax.servlet.ServletConfig config;         //config
javax.servlet.jsp.JspWriter out = null;           //out
final java.lang.Object page = this;               //page:当前
HttpServletRequest request                        //请求
HttpServletResponse response                      //响应
  1. 输出页面前增加的代码
response.setContentType("text/html");       //设置响应的页面类型
pageContext = _jspxFactory.getPageContext(this, request, response,
                                          null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
  1. 以上这些对象可直接在 JSP 中使用

在JSP页面中;

只要是 JAVA代码就会原封不动的输出;

如果是HTML代码,就会被转换为:

out.write("<html>\r\n");

这样的格式,输出到前端!

8.3、JSP 表达式

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

JSP 脚本片段

  <%--jsp脚本片段--%>
  <%--Java代码放入里面--%>
  <%
    int sum = 0;
    for (int i = 1; i <=100 ; i++) {
      sum+=i;
    }
    out.println("<h1>Sum="+sum+"</h1>");
  %>

脚本片段的再实现

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

  <hr>


  <%--在代码嵌入HTML元素--%>
  <%
    for (int i = 0; i < 5; i++) {
  %>
    <h1>Hello,World  <%=i%> </h1>
  <%
    }
  %>

JSP 声明

  <%!
    static {
      System.out.println("Loading Servlet!");
    }

    private int globalVar = 0;

    public void kuang(){
      System.out.println("进入了方法Kuang!");
    }
  %>

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

<%[Java代码]%>
<%= 变量或者表达式%>
<%! jsp声明 %>

<%--注释--%>

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

8.4、JSP指令

<%@ page import="java.util.Date" %> <%--导入Java包,更多方法请看详细参数--%>

<%@include file=""%>

<%--@include会将两个页面合二为一,使用如下(常用与网页的开头和结尾跳转不变部分)   基本上不使用,因为有变量同名会报错--%>

<%@include file="common/header.jsp"%>
<h1>网页主体</h1>
<%@include file="common/footer.jsp"%>

<hr>


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

8.5、九大内置对象

  • 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表达式

使用JSTP标签、必须导入以下依赖

<!-- JSTL表达式的依赖 -->
   <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
   </dependency>
<!-- standard标签库 -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

EL 表达式: ${}

  • 获取数据
  • 执行运算
  • 获取 Web 开发的常用对象

JSP 标签

<%--jsp:include--%>

<%--
http://localhost:8080/jsptag.jsp?name=kuangshen&age=12
--%>

<%--携带参数跳转到jsptag2.jsp页面--%>
<jsp:forward page="/jsptag2.jsp">  
    <jsp:param name="name" value="kuangshen"></jsp:param>
    <jsp:param name="age" value="12"></jsp:param>
</jsp:forward>

JSTL表达式

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

格式化标签

SQL标签

XML 标签

核心标签 (掌握部分)

JSTL标签库使用步骤

  • 引入对应的 taglib
  • 使用其中的方法
  • 在 Tomcat 也需要引入 JSTL 的包,否则会报错:JSTL 解析错误

c: if

<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>

<%--判断如果提交的用户名是管理员,则登录成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
    <c:out value="管理员欢迎您!"/>
</c:if>

<%--自闭合标签--%>
<c:out value="${isAdmin}"/>

</body>

c:choose c:when

<body>

<%--定义一个变量score,值为85--%>
<c:set var="score" value="55"/>

<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:choose>

</body>

c:forEach

<%
    ArrayList<String> people = new ArrayList<>();
    people.add(0,"张三");
    people.add(1,"李四");
    people.add(2,"王五");
    people.add(3,"赵六");
    people.add(4,"田六");
    request.setAttribute("list",people);
%>


<%--
var , 每一次遍历出来的变量
items, 要遍历的对象
begin,   哪里开始
end,     到哪里
step,   步长
--%>
<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="1" >
    <c:out value="${people}"/> <br>
</c:forEach>

9、JavaBean

实体类
JavaBean有特定的写法:

  • 必须要有一个无参构造
  • 属性必须私有化
  • 必须有对应的get/set方法;

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

ORM :对象关系映射

  • 表—>类
  • 字段–>属性
  • 行记录---->对象
// 一个类代表数据库的一个表,属性代表列名,生成的一个对象代表一行数据,通常补充get和set方法,加上toString方法
class People{
    private int id;
    private String name;
    private int id;
    private String address;
}

class A{
    new People(1,"秦疆1号",3"西安");
    new People(2,"秦疆2号",3"西安");
    new People(3,"秦疆3号",3"西安");
}

10、MVC 三层架构

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

10.1 以前

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

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

架构:没有什么是加一层解决不了的!
程序猿调用
|
JDBC
|
Mysql Oracle SqlServer ....
12345678910
*/

10.2 MVC 三层架构

Model

  • 业务处理:业务逻辑(Service)
  • 数据持久层:CRUD

View

  • 展示数据
  • 提供链接发起 Servlet 请求(a,form,img…)

Controller (Servlet)

  • 接收用户的请求:(req:请求参数、Session 信息…)
  • 交给业务层处理对应的代码
  • 控制试图的跳转

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

11、Filter(重点)

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

  • 处理中文乱码
  • 登录验证

在这里插入图片描述
Filter 开发步骤:

  1. 导包
  2. 编写过滤器
    • 导包不要错
      在这里插入图片描述
public class CharacterEncodingFilter implements Filter {

    //初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现!
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化");
    }

    //Chain : 链
    /*
    1. 过滤中的所有代码,在过滤特定请求的时候都会执行
    2. 必须要让过滤器继续同行
        chain.doFilter(request,response);
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        System.out.println("CharacterEncodingFilter执行前....");
        chain.doFilter(request,response); //让我们的请求继续走,如果不写,程序到这里就被拦截停止!
        System.out.println("CharacterEncodingFilter执行后....");
    }

    //销毁:web服务器关闭的时候,过滤会销毁
    public void destroy() {
        System.out.println("CharacterEncodingFilter销毁");
    }
}
  1. 在 web.xml 中配置Filter
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <!--只要是 /servlet的任何请求,会经过这个过滤器-->
    <url-pattern>/servlet/*</url-pattern>
    <!--<url-pattern>/*</url-pattern>-->
</filter-mapping>

12、监听器

实现一个监听器;

  1. 编写一个监听器
    实现监听器的接口…
//统计网站在线人数 : 统计session
public class OnlineCountListener implements HttpSessionListener {

    //创建session监听: 看你的一举一动
    //一旦创建Session就会触发一次这个事件!
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();

        System.out.println(se.getSession().getId());

        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就会触发一次这个事件!
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.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. 自动销毁
     */
}
  1. 在 web.xml 中注册监听器
<!--注册监听器-->
<listener>
    <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>
  1. 看情况是否使用!
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值