javaweb总——注:跟着狂神学的

本文详细介绍了JavaWeb的动态特性,包括Servlet、JSP、MVC架构、JDBC、Filter与监听器的应用,以及如何搭建和配置Web服务器如Tomcat。涵盖了动态页面、数据交互、服务器管理等内容。
摘要由CSDN通过智能技术生成

1、JavaWeb

1、1基本概念

web开发:

  • web:网页的意思, www.baidu.com
  • 静态网页web
    • html
    • 提供给所有人看的数据始终不会发生改变
  • 动态web
    • 淘宝,几乎是所有的网站都是动态网站;
    • 提供给所有人看的数据始终会发生变化,每个人在不同时间不同地点看到的信息各不相同
    • 技术栈:Serlet/JSP、PHP

在java中,动态web资源技术统称为javaweb

1、2web应用程序

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

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

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

  • URL

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

    • html、css、js
    • jsp、selvet
    • java程序
    • jar包
    • 配置文件(Properties)

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

    1、3静态web
  • *.html, *.htm,这些都是网页的后缀,如果服务器上存在这些东西,我们就可以直接读取
    在这里插入图片描述

  • 静态web存在的缺点

    • web页面无法动态更新,所有用户看到都是同一个页面
      • 轮播图,点击特效:伪动态
      • JavaScript(实际开发中,用的最多)
      • VBScript
    • 它无法和数据库交互(数据无法持久化,用户无法交互)
1、4动态web

页面会动态展示:

在这里插入图片描述

缺点:

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

优点:

  • web页面可以动态更新,所有用户看到都不是同一个页面
  • 它可以与数据库交互(数据持久化:注册)

在这里插入图片描述

新手村:–魔鬼训练(分析原理,看源码)–》PK场

2、web服务器

技术

ASP

  • 微软:国内最早流行的就是ASP
  • 在HTML中嵌入了VB的脚本, ASP+COMv
  • 在ASP开发中,基本一个页面都有几千行的业务代码,页面极其混乱
  • 维护成本高
  • c#
  <h1>
  <%></%>
  </h1>

php

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

jSP/Servlet

B/S:游览器和服务器

C/S:客户端和服务器

  • sun公司主推的B/S架构
  • 基于java语言的(所有打大公司,或者一些开源的组件,都是用java写的
  • 可以承载三高问题带来的影响
  • 语法像ASP,ASP–Jsp,加强市场强度
2、2web服务器

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

IIS

微软的;ASP…Windows中自带的

Tomcat

面向百度编程:

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

Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。对于一个初学者来说,可以这样认为,当在一台机器上配置好Apache 服务器,可利用它响应HTML标准通用标记语言下的一个应用)页面的访问请求。实际上Tomcat是Apache 服务器的扩展,但运行时它是独立运行的,所以当你运行tomcat 时,它实际上作为一个与Apache 独立的进程单独运行的。

Tomcat实际上运行jSP页面和Servlet。Tomcat最新版本为9.0

工作3-5年后,可以尝试

下载tomcat:

1、安装or解压

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

3、这个东西的作用

3、安装tomcat

https://tomcat.apache.org/download-90.cgi

在这里插入图片描述

tomcat文件:

在这里插入图片描述

启动关闭

在这里插入图片描述

  • java环境变量没有配置
  • 闪退问题:需要配置兼容性
  • 乱码问题:配置文件中设置
3、3配置

在这里插入图片描述

可以配置启动的端口号

  • tomcat默认的端口号:8080
  • mysql:3030
  • http:80
  • https:443
	<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

在这里插入图片描述

​ 1、有:直接返回对应的ip地址,这个地址中,有我们访问的web程序,直接访问

127.0.0.1       www.localhost.com

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

在这里插入图片描述

4、可以配置一个环境变量(可选性)

3、4发布一个web网站

不会就先模仿

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

网站应有的结构

  ---webapps:tomcat服务器的web目录
   --Root
   --kuang:网站的目录名
        --WEB_INF
          --clsaaes:java程序
          --lib:wen应用所依赖的jar包
          --web.xml:网站配置文件
  		--index.html  默认的受业
        --static
            --css
               --style.css
            -js
            img
		--....

HTTP协议:面试

Maven:构建工具

  • Maven安装包

Servlet入门

  • HelloWorld!
  • Servlet配置
  • 原理

4、http

4、1什么是HTTP

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

  • 文本:html、字符串、…
  • 超文本:图片、音乐、视频、定位、地图…
  • 端口号:80

https:安全的

  • 端口号:443
4、2两个时代
  • http1.0
    • HTTP/1.0:客户端可以与web服务器连接后,只能获得一个web资源,断开连接
  • http2.0
    • HTTP/1.1:客户端可以与web服务器连接后,可以获得多个web资源。
4、3Http请求
  • 客户端—发送请求(Request)----服务器

向百度发请求:

Request URL: https://www.baidu.com/   //地址
Request Method: GET   //请求方式,get
Status Code: 200 OK    //状态码
Remote Address: 36.152.44.95: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

请求行

  • 请求行中的请求方式:GET
  • 请求方式:GET、Post、HEAD、DELETE、PUT、TRCAt…
    • get:请求能够携带的参数比较少,大小有限制,会在游览器的URL地址栏显示数据内容,不安全,但高效
    • post:请求能携带的参数比较多,大小没有限制,安全,但不搞笑。

消息头

Accept:  告诉游览器,它所支持的数据类型
Accept-Encoding:   支持哪种编码格式  GBK UTF-8  GB2312  ISO8859-1
Accept-Language: 告诉游览器,它的语言环境
Cache-Control: 缓存控制
Connection:  告诉游览器,请求完成是断开还是保持连接
HOST:主机..../..
4、4Http响应
  • 服务器–响应–客户端

百度:

    Cache-Control: private   //缓存控制
    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:主机..../..
    Refresh:告诉客户端,多久刷新一次
        Location:让网页重新定位

响应状态码

200:请求响应成功 200

3xx:请求重定向

  • 重定向:你重新到我给你新位置去。

4xx:找不到资源 404

  • 资源不存在;

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

常见面试题:

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

5、Maven

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

  1. 在javawen开发中,需要使用大量的jar包,我们需要手动导进去
  2. 如何能够让一个东西自动帮我们导入和配置这个jar包。由此,Maven诞生了!
5、1Maven项目架构管理工具

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

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

  • 有约束,不要去违反

Maven会规定好你改如何去编写我们的java代码,按照这个来

下载安装

在这里插入图片描述

下载完成解压即可

5、3配置环境变量

在我们的系统环境中

配置如下:

  • M2_HOME maven目录下的bin目录

在这里插入图片描述

  • MAVEN_HOME meven的目录

在这里插入图片描述

  • 在系统的path中配置 %MAVEN_HOME%\bin

在这里插入图片描述

  • 在cmd中输入 mvn -version

在这里插入图片描述

测试Maven是否安装完毕,保证必须配置完毕

5、4阿里云镜像
  • 镜像:mirrors
    • 作用:加速我们的下载
  • 国内建议使用阿里云的镜像
 <mirror>
3         <id>nexus-aliyun</id>
4         <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
5         <name>Nexus aliyun</name>
6         <url>http://maven.aliyun.com/nexus/content/groups/public</url>
7      </mirror> 
5、5本地仓库

在本地的仓库,远程仓库;

建立一个本地仓库:localRepository

<localRepository>D:\软件app\apache-maven-3.6.3-bin\mevan-repo</localRepository>
5、6在IDEA中使用Maven

在这里插入图片描述

在这里插入图片描述

3、等待自动导入包

在这里插入图片描述

4、出现构建成功了就好了

在这里插入图片描述

5、观察Maven多了什么

在这里插入图片描述

6、IDEA中的Maven设置

IDEA创建成功后,看一眼Maven

在这里插入图片描述

在这里插入图片描述

7、到这里Maven在IDEA中的配置基本成功了

5、7创建一个普通的Maven项目

不用勾模板

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

5、8在IDEA中配置Tomcat

在这里插入图片描述

没有的话点击

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

解决警告问题

为什么会有这个问题:我们访问一个网站:需要制定一个文件夹

在这里插入图片描述

在这里插入图片描述

启动

在这里插入图片描述
在这里插入图片描述

5、9pom文件

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>org.example</groupId>
  <artifactId>java-03-Maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <!--package:  打包方式
      jar:  java应用
      war:  javaweb应用
  -->
  <packaging>war</packaging>

  <name>java-03-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包-->
    <!--Maven的强大之处:会自动帮你导入所依赖的其它jar包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
<!--项目构建用的东西-->
  <build>
    <finalName>java-03-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>

在这里插入图片描述

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>

5、10目录树

在这里插入图片描述

在这里插入图片描述

5、11遇见的一些问题

1、Maven3.6.2

​ 解决办法:降级为3.6.1

在这里插入图片描述

2、Tomcat闪退

3、Idea每次都要配置Maven

只需要在idea全局默认配置里面配置好就行

在这里插入图片描述

在这里插入图片描述

4、Maven项目中Tomcat无法配置

5、Maven默认web项目web/xml版本问题;

在这里插入图片描述

6、替换为webapp一致的版本

7、Maven仓库使用

https://mvnrepository.com/artifact/org.springframework/spring-context/5.3.5

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

6、Servlet

6、1Servlet简介
  • Servlet就是Sun公司开发动态网页的一门技术
  • Sun在这些API中提供了一个接口交Servlet,如果想开发一个Servlet程序,只需要完成两个过程即可
    • 编写一个类,实现Servlet接口
    • 再将开发好的java类部署到web服务器中

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

6、2HelloServlet

Serlvet接口Sun公司有两个默认的实现接口:HTTPServletGenericServlet

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

添加javax.servletavax.servlet.jsp

在这里插入图片描述

在这里插入图片描述

点击这个自动下载

在这里插入图片描述

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

在这里插入图片描述

在这里插入图片描述

<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version>
    <scope>provided</scope>
</dependency>

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

父项目中会有

    <modules>
        <module>java-01Maven</module>
    </modules>

子项目会有

 <parent>
        <artifactId>java-04-Maven</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

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

Son extends  Father

3.Maven环境优化

​ 1、修改web.xml为最新的

旧的:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

新的

3.0

<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_3_1.xsd"
         version="3.1"><!--将web版本4.0修改为3.1,注意上一行约束文件也要修改-->
</web-app>

4、0

<?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的结构搭建

在这里插入图片描述

4.编写一个Servlet程序

  • 编写一个普通类
  • 实现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 {
    super.doPost(req, resp);
}
}

5、编写Servlet的映射

为什么需要映射:我们写的是JAVA程序,,但是要通过游览器访问,而游览器需要连接web服务器,所以我们需要再web服务总注册我们写的Servlet,还需要给他一个游览器访问的路径

<!--注册Servlet-->
<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.bing.HelloServlet</servlet-class>
</servlet>
<!--Servlet请求路径-->
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>hello</url-pattern>
</servlet-mapping>

6、配置Tomcat

注意:配置项目发布的的路径

7、启动测试,OK!

6、3Servlet原理

Servle是由web服务器调用,web服务器在收到游览器请求之后,会:
在这里插入图片描述

6、4Mapping问题
  1. 一个Servlet可以指定一个映射路径
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
  1. 一个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>
  1. 一个Servlet可以指定通用映射路径
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello/*</url-pattern>
    </servlet-mapping>
  1. 一个Servlet可以指定默认映射路径
   <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
  1. 一个Servlet可以指定一些后缀或者前缀映射路径
    <!--Servlet请求路径-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <!--且*.do前面不能加路径-->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
  1. 优先级问题
    指定了固有的映射路径优先级最高,如果找不到会自动走默认的路径
    <servlet>
        <servlet-name>error</servlet-name>
        <servlet-class>com.bing.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>error</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
6、5ServletContext

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

1、共享数据

我在这个Servlet保存的数据可以在另一个Servlet中拿到
设置数据到ServletConttext

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.getServletConfig();  //selvet配置
//        this.getInitParameter(""); //初始化参数
        ServletContext servletContext = this.getServletContext();
        String userName = "冰凝";  //数据
        servletContext.setAttribute("username","userName");  //将一个数据保存在ServletContext中,名字为:username,值为userName;
    }

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

在另一个Servlet里接收ServletContext

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        String 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 {
        super.doPost(req, resp);
    }
}

xml文件

 <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>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>GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>

注意在启动的时候记得把tomacat里的Deplayment设置为当前的Maven,不要多个,要不然会导包多个,影响效率。

在这里插入图片描述

测试结果
http://localhost:8080/Java_02_Maven_war/hello
在这里插入图片描述
http://localhost:8080/Java_02_Maven_war/getc
在这里插入图片描述

2、获取初始化参数
    <context-param>
        <param-name>namespace</param-name>
        <param-value>jdbc:mysql://localhost:8033/mybatis</param-value>
    </context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        String namespace = servletContext.getInitParameter("namespace");
        resp.getWriter().print(namespace);
    }
3、请求转发
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
//        RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/getp");
//        requestDispatcher.forward(req,resp);
        servletContext.getRequestDispatcher("/getp").forward(req,resp);
    }

在这里插入图片描述

4、读取资源文件:Properties()
  • 在java目录下新建properties文件
  • 在resources目录下新建properties文件

发现:都被打包到同一个路径下:classes,我们俗称这个路径为classpath。
思路,需要一个文件流

  • java文件下的
username=root
password=123
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/bing/Servlet/sd.properties");
        Properties properties = new Properties();
        properties.load(is);
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        resp.getWriter().print(username+"   :"   +  password);
    }
  • resources文件下的
username=root
password=123
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/sd1.properties");
        Properties properties = new Properties();
        properties.load(is);
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        resp.getWriter().print(username+"   :"   +  password);
    }
  • 访问测试即可
6、6HttpServletResponse

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、下载文件

让浏览器能支持下载我们需要的文件

resp.setHeader("Content-disposition","attachment;filename"+filename);
//filename是值下载的文件名字
	1、要获取下载文件的路径
	2、下载文件名是啥?
	3、设置想办法让游览器能够支持(Content-Disposition)下载我们需要的东西。
	   解决中文文件名问题,使用URLEncoder.encode(),否则会乱码
	4、获取下载文件中的输入流
	5、创建缓冲区
	6、获取OutputStream对象
	7、将FileOutputStream流写入到buffer缓冲区·
	8、使用OutputStream将缓冲区的数据输出到客户端。
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、要获取下载文件的路径
        String realPath= "D:\\新的代码\\java-04-Maven\\response\\src\\main\\resources\\2.jpg";
        System.out.println(realPath);
//        2、下载文件名是啥?
        String substring = realPath.substring(realPath.lastIndexOf("\\") + 1);
//        3、设置想办法让游览器能够支持(Content-Disposition)下载我们需要的东西。解决中文文件名问题,使用URLEncoder.encode(),否则会乱码
        resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(substring,"utf-8"));
//        4、获取下载文件中的输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);
//        5、创建缓冲区
        int len=0;
        byte[] bytes=new byte[1024];
//        6、获取OutputStream对象
        ServletOutputStream outputStream = resp.getOutputStream();
//        7、将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区的数据输出到客户端。
        while((len=fileInputStream.read(bytes))>0){
            outputStream.write(bytes,0,len);
        }
        fileInputStream.close();
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
3、验证码功能

验证怎么来的

  • 前端实现
  • 后端实现,需要用java的图片类,生产一个图片

如何让游览器定时刷新一次

resp.setHeader("refresh","3");

response 设置http响应头控制浏览器禁止缓存当前文档内容

response.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
public class imageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //定时刷新页面
        resp.setHeader("refresh","3");
        //在内存中创建一张图片
        BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_3BYTE_BGR);
        //得到一张图片
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        //设置图片的背景颜色
        graphics.setColor(Color.white);
        graphics.fillRect(0,0,80,20);
        //给图片写数据
        graphics.setColor(Color.cyan);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(nums(),0,20);
        //告诉游览器,这个图片打开的方式
        resp.setContentType("image/jpeg");
        //网站存在缓存,不让网站缓存
        resp.setDateHeader("expries", -1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        //把图片写给游览器
        ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());
    }
    private String nums(){
        Random random = new Random();
        String s = random.nextInt(9999999) + "";
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 7 - s.length(); i++) {
            stringBuffer.append("0");
        }
        s = stringBuffer.toString()+s;
        return s;
    }
    @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;

测试:

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setHeader("Location","/response_war/img");
//        resp.setStatus(302);
        resp.sendRedirect("/response_war/img");//重定向
    }

在这里插入图片描述

面试题:请你聊聊重定向和请求转发的区别
相同点:页面都会跳转
不同点:

  • 请求转发:URL不会改变 307
  • 重定向:URL会改变 302
  • 请求转发B一个web资源收到客户端A请求,B他会找到另一个web资源C,拿客户端A去访问。这个过程叫做重定向
  • 重定向是B一个web资源收到客户端A请求,B他会通知A客户端去访问另一个web资源C,这个过程叫做重定向

在这里插入图片描述
重定向应用
通过登入界面提交到B界面,而B界面重定向到A
index.jsp

<html>
<body>
<%--这里提交的路径,需要找到当前项目的路径--%>
<%--${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>

/login

public class RequestTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String parameter = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println(parameter +"    "+password);

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

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

success.jsp

<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>

6、7HTTPServletRequest

HTTPServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HTTPServletRequest,通过这个HTTPServletRequest方法获取客户端的信息。
在这里插入图片描述

1、获取前端参数,并且请求转发
public class RequestServlet extends HttpServlet {
    @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[] hobbies = req.getParameterValues("hobby");
        System.out.println("============================");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("============================");
        //这里的/代表当前项目
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

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

7、Cookie、Session

7、1会话

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

  • 有状态的会话:一个同学来过教师,下次再来教师,我们会知道这个同学,曾经来过这个

你 怎么证明你是 该学校的学生
1、发票 学校给你发票
2、学校登记 学校标记你来过
一个网站,怎么证明你来过?
1、服务端给客户端一个信件,客户端下次访问服务端带上信件就可以:Cookic
2、服务端登记你来过了,下次你来的时候我匹配你:Session

7、2保存会话的两种技术

cookie

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

session

  • 服务端技术,利用这个技术可以保存用户的信息,我们可以把信息或者数据存放在session中

常见:网站登入之后,你下次不用在登入了,第二次访问直接就进去了

7、3cookis

在这里插入图片描述

1、从请求中拿到cookie信息
2、服务器响应给客户端cookie

Cookie[] cookies = req.getCookies();  //从请求中拿到cookie信息
cookies1.getName()  //获取cookie中的key 
cookies1.getValue()   //获取cookie中的value
Cookie cookie = newCookie("lastDate",System.currentTimeMillis()+"");  //新建一个cookie
cookie.setMaxAge(24*60*60);   //设置cookie的有效期
resp.addCookie(cookie);     //响应给客户端一个cookie
public class CookieDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws 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 cookies1 = cookies[i];
                //获取cookie的名字
                if(cookies1.getName().equals("lastDate")){
                    //获取cookie的值
                   long value = Long.parseLong(cookies1.getValue());
                    Date date = new Date(value);
                    out.print(date.toLocaleString());
                }
            }
        }else {
            out.write("这是你第一次访问本站:");
        }

        //服务给客户端响应一个cookie
        Cookie cookie = new Cookie("lastDate",System.currentTimeMillis()+"");
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

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

cookie:一般会保存在本地的用户目录下:appdata
一个网站的cookie是否存在上限,聊聊细节问题

  • 一个cookie只能保存一个信息
  • 一个web站点可以给游览器发送多个cookie,最多存放20个cookie
  • cookie大小有限制4kb
  • 300个cookie游览器上线

删除cookie

  • 不设置有效期,关闭游览器
  • 设置有效期为0
//这里定义的cookie必须和上面的相同
Cookie cookie = new Cookie("lastDate",System.currentTimeMillis()+"");
        cookie.setMaxAge(0);

编码解码:

URLEncoder.encode("冰凝","utf-8");   //编码
URLDecoder.decode(cookies1.getValue(),"utf-8");  //解码
7、4session

在这里插入图片描述

什么是session

  • 服务器会给每一个用户(游览器)创建一个session对象
  • 一个session独占一个资源,只要游览器没哟关闭,这个session就存在
  • 用户登入之后,整个网站都可以访问——>保存用户的信息、保存购物的信息
    在这里插入图片描述
    session和cookie区别
  • cookie是把用户的数据写给用户的游览器,游览器保存(可以保存多个)
  • session是把用户的数据写到用户独占session中,服务器保存(保存重要信息,减少服务器资源浪费)
  • session对象有服务器创建

使用场景

  • 保存一个登入用户的信息
  • 购物车信息
  • 在整个网站中经常会使用的数据,我们将它保存在session中

使用session

public class SessionDemo01 extends HttpServlet {
    @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 id = session.getId();
        //判断session是否为第一次创建
        if(session.isNew()){
            resp.getWriter().write("该session是第一次创建 :"+ id);
        }else{
            resp.getWriter().write("该session步是第一次创建 :"+ id);
        }

    }

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

获取session中保存的value

public class SessionDemo02 extends HttpServlet {
    @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存东西
        String name = (String) session.getAttribute("name");
        System.out.println(name);
    }

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

删除保存的session

public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("name");
        session.invalidate();
    }

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

在xml中自动删除session

<session-config>
<!--       一分钟后自动注销session-->
        <session-timeout>1</session-timeout>
    </session-config>

在这里插入图片描述

8、JSP

8、1什么是JSP
  • java Server Page:Java服务端页面,也和Servlet一样,用于动态web技术
  • 最大的特点:
    • 写jsp就像在写HTML
    • 区别:HTML只给用户提供静态数据
      JSP页面中可以嵌入Java代码,为用户提供动态数据
8、2JSP原理

思路:JSP到底怎么执行

  • 代码层面没有任何问题
  • 服务器内部工作
    • tomcat中有一个word目录
    • IDEA使用Tomcat会在IDEA的Tomcat中产生一个work目录

在这里插入图片描述
我电脑的地址

D:\Tomcat8.0\work\Catalina\localhost\ROOT\org\apache\jsp

发现页面变成jsp文件
在这里插入图片描述
游览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet
JSP本身就是Servlet

//请求
public void _jspInit() {
}
//销毁
  public void _jspDestroy() {
  }
JSPService
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)

1、判断请求
2、内置一些对象

  final javax.servlet.jsp.PageContext pageContext;   //页面上下文
  javax.servlet.http.HttpSession session = null;   //session
    final javax.servlet.ServletContext application;  //application
    final javax.servlet.ServletConfig config;  //config
    javax.servlet.jsp.JspWriter out = null;  //out
    final java.lang.Object page = this;  //page
final javax.servlet.http.HttpServletRequest request //请求
final javax.servlet.http.HttpServletResponse response  //响应

3、输出页面前增加的代码

response.setContentType("text/html; charset=UTF-8");  //设置对象响应类型
pageContext = _jspxFactory.getPageContext(this, request, response,
        null, false, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
out = pageContext.getOut();
_jspx_out = out;

4、以上这些对象均可以在jsp中使用
在这里插入图片描述
在JSP页面中,只要是java代码,就会原封不动的输出,
如果是HTML代码,就会转化为

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

这样的格式输出到前端页面中

8、3JSP基础语法

任何语言都有自己的语法,java中有。JSP作为java技术的一种应用,它拥有一些自己扩充的语法(了解、知道即可),java所有语法都支持

jsp表达式

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

jsp脚本片段

<%
    int sum = 0;
    for (int i = 0; i < 100; i++) {
        sum += 1;
    }
    out.print("<h1>sum=" + sum +"</h1>");
%>

JSP脚本片段在实现

<%
    int x = 0;
    out.print(x);
%>
<p>这是一个JSP文档</p>
<%
    int y = 15;
    out.print(y);
%>
<hr>
<%
    for (int i = 0; i < 10; i++) {
%>
    <h1>Hello <%=i%></h1>
<%
    }
%>

JSP声明

<%!
    static {
        System.out.println("lading word");
    }
    private int age = 0;
    public void test(){
        System.out.println("你是最棒的");
    }
%>

JSP声明:会被编译到JSP生成java的类中!其它的就会被生成到_JSPService方法中

在JSP中嵌入java代码即可

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

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

8、4JSP指令
<%--html类型,编码方式:UTF-8--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--定制错误页面--%>
<%@ page errorPage="/Error/error.jsp" %>
<%--显示定义他是错误页面--%>
<%@ page isErrorPage="true" %>

错误页面第二种定义方式:在xml中定义

<error-page>
        <error-code>500</error-code>
        <location>/Error/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/Error/404.jsp</location>
    </error-page>

指令包含于标签包含区别
1、.语法不同:语法范畴不同(jsp、javaee)、写法不同
2、执行机制不同:
指令include:先包含后执行
标签include:如果包含的是动态页面则先执行后包含、静态页面则先包含不执行。
3、一个识别被包含页面的内容,一个不能识别
4、标签包含包含动态页面的时候,当前页面可以向被包含页面传参
5、指令包含包含的时候不能有,也不能有同名的变量定义,否则会报错

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--指令包含:
<%@ include file=""%> 将两个页面合二为一
--%>
<%@ include file="common/header.jsp"%>
<h1>你好</h1>
<%--标签包含:
<jsp:include page=""/>拼接页面,本质还是两个页面
--%>
<jsp:include page="common/header.jsp" />
<h1>你好</h1>
</body>
</html>
8.5、9大内置对象
  • PageContext
  • Request
  • Response
  • Session
  • Application [SerlvetContext]
  • config [servletConfig]
  • out
  • page
  • exception

在这里插入图片描述

PageContextDemo01.jsp:存数据并且取出里面的数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--内置对象--%>
<%
    pageContext.setAttribute("name1","冰凝");  //保存数据只在页面中有效
    request.setAttribute("name3","张大鹏");   //保存数据只在一次请求中有效,请求转发会携带这个数据
    session.setAttribute("name2","小三");   //保存的数据只在一次会话中有效,从打开游览器到关闭游览器
    application.setAttribute("name4","王兵");  //保存的数据只在服务器中有效,从打开服务器到关闭服务器
    pageContext.forward("/PageContextDemo02.jsp");
%>
<%--脚本片段中的代码会原封不动的生成到jsp.java中
要求:java代码必须保证正确性
--%>
<%
    //从pagecontext开始取出,我们通过寻找的方式
    //从底层到高层(作用域):page-->request-->Session-->application
    String name1 = (String)(pageContext.findAttribute("name1"));
    String name2 = (String)(pageContext.findAttribute("name2"));
    String name3 = (String)(pageContext.findAttribute("name3"));
    String name4 = (String)(pageContext.findAttribute("name4"));
    String name5 = (String)(pageContext.findAttribute("name5"));  //不存在
%>
<%--使用EL表达式输出 ${}--%>
<h1>取出值</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>
</body>
</html>

PageContextDemo02.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    //从pagecontext开始取出,我们通过寻找的方式
    //从底层到高层(作用域):page-->request-->Session-->application
    String name1 = (String)(pageContext.findAttribute("name1"));
    String name2 = (String)(pageContext.findAttribute("name2"));
    String name3 = (String)(pageContext.findAttribute("name3"));
    String name4 = (String)(pageContext.findAttribute("name4"));
    String name5 = (String)(pageContext.findAttribute("name5"));  //不存在
%>
<%--使用EL表达式输出 ${}--%>
<h1>取出值</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>
</body>
</html>

request:客户端向服务器发送请求,产生的数据,用户看完就没用了。比如:新闻,用户看完没用的
session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其它用户还能使用,比如:聊天数据

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

EL表达式:${ }

  • 获取数据
  • 执行运算
  • 获取web开发的常用对象
<!--JSTL依赖-->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <!--stand标签库-->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

JSP标签
JSPtag.jsp:跳转到另一个页面,并传递数据


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>1</h1>
<%--<jsp:include page=""></jsp:include>--%>
<jsp:forward page="/JSPtag2.jsp">
    <jsp:param name="name" value="bingning"/>
    <jsp:param name="age" value="13"/>
</jsp:forward>


</body>
</html>

JSPtag2.jsp:该页面接收数据


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>2</h2>
姓名:<%=request.getParameter("name")%>
年龄:<%=request.getParameter("age")%>
</body>
</html>

JSTL表达式:JSTL标签库的使用就是为了弥补HTML标签的不足,可以供我们使用,标签的功能和java代码一样
核心标签(掌握部分即可)
在这里插入图片描述
使用步骤

  • 引入对应的taglib
  • 在使用对应的JSTL标签
  • 在Tomcat中也需要导入JSTL包,要不然会报解析错误的问题

获取form表单提交的值并判断
<c:if>

<%--只有引入了taglib对应的JSTL,我们才能学习使用JSTL表达式--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>测试</h1>
<%--
    EL表达式:${}
--%>
<form action="coreif.jsp">
    <input type="text" name="username" value="${param.username}">
    <input type="submit" value="登入">
</form>
<%--判断是否为管理员登入--%>
<c:if test="${param.username=='admit'}" var="isAdmit">
    <c:out value="管理员欢迎你!"/>
</c:if>
<%--自闭和标签--%>
<c:out value="${isAdmit}"/>
</body>
</html>

<c:choose>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--定义一个变量score,值为85--%>
<c:set var="score" value="85"></c:set>
<c:choose>
    <c:when test="${score > 90}">
        你的成绩为优秀
    </c:when>
    <c:when test="${score > 70}">
        你的成绩为良好
    </c:when>
    <c:when test="${score > 60}">
        你的成绩为及格
    </c:when>
</c:choose>
</body>
</html>

<c:forEach>

<%@ page import="java.util.ArrayList" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    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="name" items="${list}">
    <c:out value="${name}"/> <br>
</c:forEach>
<hr>
<c:forEach var="pen" items="${list}" begin="1" end="3" step="2">
    <c:out value="${pen}"/>
</c:forEach>
</body>
</html>

格式化标签
SQL标签
XML 标签
JSTL函数

9、JavaBean

实体类
JavaBean有特定的写法

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

一般用来和数据库的字段做映射 ORM
ORM:对象关系映射

  • 表–>类
  • 字段–>属性
  • 行记录–>对象
idnameageaddress
1冰凝1123南昌
2冰凝243上海
3冰凝35武汉

Peoria

package com.bing.pojo.bing.pojo;
//实体类,我们一般和数据库中的表一一对应
public class People {
    private int id;
    private String name;
    private int age;
    private String address;

    public People() {
    }

    public People(int id, String name, int age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

jsp调用


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<jsp:useBean id="people" class="com.bing.pojo.bing.pojo.People" scope="page"/>
<jsp:setProperty name="people" property="address" value="江西"/>
<jsp:setProperty name="people" property="age" value="18"/>
<jsp:setProperty name="people" property="id" value="1"/>
<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"/>

</body>
</html>

10、早些年

什么是MVC:Model view Contrdler 模型、视图、控制器

10、1早些年

在这里插入图片描述
用户直接访问控制层,控制层就可以直接操作数据库

Servlet-->CRUD-->数据库
弊端:程序十分臃肿,不利于维护
Servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么事加一层解决不了的

程序猿调用JDBC
|
 MySQL oracle sqlservel
|
10、2MVC 三层架构

在这里插入图片描述
Model

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

View

  • 展示数据
  • 提供链接发起Servlet请求(a、form、img…)
    Controller(servlet)
  • 接受用户的请求:(req:请求参数、session信息…)
  • 交给业务处理对应的代码
  • 控制视图的跳转
登入-->接收用户登入的请求-->处理用户的请求
(获取用户登录的参数,username、password)-->
交给业务层处理登录业务(判断密码是否正确:事务)-->
Dao层查询用户名和密码是否正确-->
数据库

11、Filter

Filter:过滤器:用来过滤网站的数据
在这里插入图片描述
Filter:开发步骤

  1. 导包

  2. 编写过滤器
    1、导包不要错误
    在这里插入图片描述

    2、实现Filter接口,重写方法

public class CharterFilter implements Filter {
//    初始化  web服务器启动已经初始化了
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化文件");
    }
// chain:链
/*
*
* 1、过滤器中的所有代码,再过滤特定请求的时候会执行
* 2、必须要让过滤器继续执行下去*/
    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("CharacterFilter执行前");
        chain.doFilter(request,response); //让请求继续走下去,如果不写,,程序到这里就被拦截了
        System.out.println("CharacterFilter执行后");
    }
//    销毁  :web服务器关闭的时候过滤器销毁
    public void destroy() {
        System.out.println("文件被销毁了");
    }
}
   3、在xml中配置Filter
 <filter>
        <filter-name>CharterFilter</filter-name>
        <filter-class>com.bing.pojo.bing.pojo.filter.CharterFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharterFilter</filter-name>
<!--        只要是servlet下的任何请求,都会经过这个过滤器-->
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>

测试过滤器的servlet

public class ServletDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setCharacterEncoding("utf-8");

        resp.getWriter().write("你好呀!世界");
    }

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

12、监听器

实现一个监听器接口(有n种)
编写一个监听器
1、实现监听器接口

//统计网站在线人数,统计session
public class ListenDemo01 implements HttpSessionListener {
    //    创建session监听,查看你的一举一动
//    一旦创建session,会自动执行下面的代码
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext sev = se.getSession().getServletContext();
        Integer username = (Integer) sev.getAttribute("username");
        if (username==null){
            username= new Integer(1);
        }else {
            int count = username.intValue();
            username = new Integer(count+1);
        }
        sev.setAttribute("username",username);
    }
//一旦session销毁就会触发这个时间
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext sev = se.getSession().getServletContext();

        Integer username = (Integer) sev.getAttribute("username");
        if (username==null){
            username= new Integer(0);
        }else {
            int count = username.intValue();
            username = new Integer(count-1);
        }
        sev.setAttribute("username",username);
    }
    /*自动销毁:se.getSession().invalidate();//
    手动销毁:
    *
    * */
}

手动销毁:se.getSession().invalidate()
2、配置xml中监听器

  <listener>
        <listener-class>com.bing.pojo.bing.pojo.Listen.ListenDemo01</listener-class>
    </listener>

自动销毁:

<session-config>
        <session-timeout>1</session-timeout>
    </session-config>

3、看情况是否使用

过滤器、监听器常用

监听器:GUI编程中经常使用

public class GUIDemo1 {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("监听");
        Panel panel = new Panel(null);
        jFrame.setBounds(300,300,500,500);
        jFrame.setBackground(new Color(53, 220, 64));
        jFrame.setLayout(null);
        panel.setBounds(30,30,300,300);
        panel.setBackground(new Color(19, 0, 121));
        jFrame.add(panel);
        jFrame.setVisible(true);
        jFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
            }
        });
    }
}

用户登入后才能进入主页,用户注销后就进入登入页面。

  1. 用户登入之后向session中放入用户的数据
  2. 进入主页的时候要判断用户是否登入:用Filter实现。

Login.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<h1>登入页面</h1>

<head>
    <title>Title</title>
</head>
<body>
<form action="/servlet/login" method="get">
    <input type="text" name="username">
    <input type="submit" value="登入">
</form>
</body>
</html>

success.jsp

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

<h1>登入成功,执行下面操作</h1>
<a href="/servlet/logout">注销</a>
</body>
</html>

error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登入失败</h1>
<h2>你没有访问的权限</h2>
<img src="../img/500.jpg" alt="500没找到">
<a href="/servlet/logout">重新登入</a>
</body>
</html>

LoginDemo

public class LoginDemo 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("USER_NAME",req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else {
            resp.sendRedirect("/Error/error.jsp");
        }
    }

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

LogoutServlet

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object user_name = req.getSession().getAttribute("USER_NAME");
        if(user_name!=null){
            req.getSession().removeAttribute("USER_NAME");
            resp.sendRedirect("/Login.jsp");
        }else {
            resp.sendRedirect("/Login.jsp");
        }

    }

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

FilterLogin

public class FilterLogin implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if(req.getSession().getAttribute("USER_NAME") == null){
            resp.sendRedirect("/Login.jsp");
        }
        chain.doFilter(request,response);
    }

    public void destroy() {

    }
}

    <filter>
        <filter-name>FilterLogin</filter-name>
        <filter-class>com.bing.pojo.bing.pojo.login.FilterLogin</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterLogin</filter-name>
        <url-pattern>/sys/*</url-pattern>
    </filter-mapping>

14、JDBC

java连接数据库
在这里插入图片描述
1、创建数据库
2、导入项目依赖

 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
  </dependency>

3、连接数据库
在这里插入图片描述

JDBC固定歩奏

  1. 加载驱动
  2. 连接数据库,代表数据库
  3. 向数据库发送SQL的对象statement:CRUD
  4. 编写SQL(根据不同业务来执行)
  5. 执行查询SQL,返回一个ResultSet:结果集
  6. 关闭连接,释放资源(一定要做) 先开后关

查询

public class JDBCTest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
//      配置信息,
//      useUnicode=true&character=utf-8 解决中文乱码问题
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&character=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的对象statement:CRUD
        Statement statement = connection.createStatement();
//        4、编写SQL
        String sql = "select * from users";
//        5、执行SQl,返回一个Resultset:结果集
        ResultSet sql_ = statement.executeQuery("sql ");
        while (sql_.next()){
            System.out.println("id = " + sql_.getObject("id"));
            System.out.println("name = " + sql_.getObject("name"));
            System.out.println("password = " + sql_.getObject("password"));
            System.out.println("email = " + sql_.getObject("email"));
            System.out.println("birthday = " + sql_.getObject("birthday"));
        }
//        6、关闭连接,释放资源(一定要做) 先开后关
        sql_.close();
        statement.close();
        connection.close();
    }
}

增加

public class JDBCTest2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
//      配置信息,
//      useUnicode=true&character=utf-8 解决中文乱码问题
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&character=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的对象statement:CRUD
        String sql = "insert into user(id,name,password,email,birthday) values (?,?,?,?,?)";
//        4、编写SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,1); //给第一个占位符赋值为1
        preparedStatement.setString(2,"冰凝"); //给第二个占位符赋值为冰凝
        preparedStatement.setString(3,"1234"); //给第二个占位符赋值为1234
        preparedStatement.setString(4,"133465@qq.com"); //给第二个占位符赋值为133465@qq.com
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime())); //给第二个占位符赋值为new Date(new java.util.Date().getTime())
//        5、执行SQL
        int i = preparedStatement.executeUpdate();
        if(i>0){
            System.out.println("增加数据成功");
        }
//        6、关闭连接,释放资源(一定要做) 先开后关

        preparedStatement.close();
        connection.close();
    }
}

事物
要么都成功,要么都失败
ACID原则:保证数据的安全

开启事物:
事物提交:commit()
事物回滚: rollback()
关闭事物:
public static void main(String[] args) {
//      配置信息,
//      useUnicode=true&character=utf-8 解决中文乱码问题
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&character=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、通知数据库开启事务
            connection.setAutoCommit(false);
            String sql = "update account set money = money-100 where name = 'A'";
            connection.prepareStatement(sql).executeUpdate();

//            制造错误
//            int i = 1/0;
            String sql1 = "update account set money = money+100 where name = 'B'";
            connection.prepareStatement(sql1).executeUpdate();
            connection.commit(); //以上两条SQL都执行成功了就提交事务
            System.out.println("success");
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

Junit单元测试
项目依赖

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

简单使用
-@Test注解:只能在方法上有效,只要加了注解的这个方法,可以直接运行

public class JDBC3 {
    @Test
    public void test(){
        System.out.println("导入这个直接测试");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值