JaveWeb笔记

JavaWeb

1、基本概念

1.1、前言

web开发:

. web,网页的意思,

静态web

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

动态web

  • 淘宝,几乎是所有的网站;
  • 提供给所有人看的数据始终会发生变化,每个人在不同的时间,不同的地点看到的信息各不相同!。
  • 技术栈: Servlet/SP,ASP,PHP
  • 在Java中,动态web资源开发的技术统称为lavaWeb;

1.2、web应用程序

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

  • a.html.
    b.htm.……多个web资源,这些web资源可以被外界访问,对外界提供服务;·你们能访问到的任何一个页面或者资源,都存在于这个世界的某一个角落的计算机上。
  • URL:统一资源定位符
  • 这个统一的web资源会被放在同一个文件夹下,web应用程序–>Tomcat:服务器。一个web应用由多部分组成((静态web,动态web)
  • html,css,is
  • seruleto Java程序。 jar包
  • 配置文件(Properties)

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

1.3、静态web

.htm,.html,这些都是网页的后缀,如果服务器上一直存在这些东西,我们就可以直接进行读取通过网络连接;
在这里插入图片描述
静态web存在的缺点

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

1.4、动态web

页面会动态展示:“Web的页面展示的效果因人而异";(千人千面)
在这里插入图片描述
缺点:

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

优点:

  • Web页面可以动态更新,所有用户看到都不是同一个页面·它可以与数据库交互

2、web服务器

服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息;
lls
微软的;ASP…,Windows中自带的

3、Tomcat

3.1、 安装tomcat

tomcat官网

面向百度编程;
Tomcat是Apache软件基金会(Apache Software Foundation)的Jakarta项目中的一个核心项目,最新的Servlet和SP规范总是能在Tomcat中得到体现,因为Tomcat技术先进、性能稳定,而且免费,因而深受Java爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web应用服务器。
Tomcat服务器是一个免费的开放源代码的Web应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试SP程序的首选。对于一个Java初学web的人来说,它是最佳的选择
Tomcat 实际上运行JSP页面和Servlet。Tomcat最新版本为9.0。
工作3-5年之后,可以尝试手写Tomcat服务器;

下载tomcat:
1.安装or解压
2.了解配置文件及目录结构3.这个东西的作用

3.2、 Tomcat启动与配置

文件夹的作用:在这里插入图片描述
访问测试: http://localhost:8080/
可能遇到的问题:
1.Java环境变量没有配置
2.闪退问题:需要配置兼容性
3.乱码问题:配置文件中设置

3.3、 配置在这里插入图片描述

可以配置启动的端口号

  • tomcat的默认端口号为:8080.
  • mysql : 3306
  • http: 80
  • https: 443
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

可以配置主机名称:

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

高难度面试题:
请你谈谈网站是如何进行访问的!
1.输入一个域名;回车
⒉.检查本机的C\Windows\System32\driversletchosts配置文件下有没有这个域名映射;
​ 1.有:直接返回对应的ip地址,这个地址中,有我们需要访问的web程序,可以直接访问

127.0.0.0.1     localhost

​ 2.没有:去DNS服务器找,找到的话就返回,找不到就返回找不到;
在这里插入图片描述

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.3、Http请求

·客户端—发请求(Request) —服务器
百度:

Request URL :https : //www.baidu . com/请求地址
Request Method: GET    get方法/post方法
status code : 200 oK状态码:200
Remote(远程) Address : 
Accept:text/html
Accept-Encoding: gzip, def1ate,br
Accept-Language :zh-cN ,zh ; q=0.9语言
cache-contro7 : max-age=0
connection :keep-alive

1、请求行
请求行中的请求方式: GET
请求方式: Get,Post,HEAD,DELETE,PUT,TRACT…

  • get:请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全,但高效
  • post:请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内容,安全,但不高效。

2、消息头

Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式―GBK UTF-8 GB2312 IS08859-1
Accept-Language:告诉浏览器,它的语言环境
cache-control:缓存控制
connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../ .

4.4、Http响应

服务器—响应-----客户端
百度:
cache-control:private 缓存控制
Connection :Keep-Alive 连接
content-Encoding: gzip 编码
content-Type :text
1.响应体

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

2、响应状态码(重点)

200:请求响应成功200
3xx:请求重定向
重定向:你重新到我给你新位置去;
4xx:找不到资源404
·资源不存在;
5xx:服务器代码错误 500
502:网关错误

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

5、Maven

我为什么要学习这个技术?
1.在Javaweb开发中,需要使用大量的jar包,我们手动去导入;
2.如何能够让一个东西自动帮我导入和配置这个jar包。
由此,Maven诞生了!

5.1、Maven项目架构管理工具我们目前用来就是方便导入jar包的!

Maven的核心思想:约定大于配置
有约束,不要去违反。
Maven会规定好你该如何去编写我们的Java代码,必须要按照这个规范来;

5.2、下载安装Maven

下载:http://maven.apache.org/

5.3、配置环境变量

系统高级设置中,找环境变量,来配置 MAVEN_HOME 与M2_HOME

在我们的系统环境变量中配置如下配置:
. M2_HOME maven目录下的bin目录
.MAVEN_HOME maven的目录
·在系统的path中配置%MAVEN_HOME%/bin

5.4、阿里云镜像

镜像:mirrors
作用:加速我们的下载·国内建议使用阿里云的镜像

<mirror>
<id>nexus-aliyun</id>
<mirrorof>* , !jeecg, ! jeecg-snapshots</mirrorf>
<name>Nexus aliyun</name>
<url>http : // maven.aliyun.com/nexus/content/groups/public</url>
</mirror>

5.5、本地仓库

在本地的仓库,远程仓库;
建立一个本地仓库:localRepository

<localRepository>E:\whl151885\apache-maven-3.6.3\maven-repn</localRepository>

5.6、在IDEA中便用Maven

1.启动IDEA
2.创建一个MavenWeb项目
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
3.等待项目初始化完毕
在这里插入图片描述在这里插入图片描述
4.IDEA中的Maven设置
注意: IDEA项目创建好后,看一眼Maven的配置
在这里插入图片描述
在这里插入图片描述
5.到这里,Maven在IDEA中的使用和配置就🆗了

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

在这里插入图片描述
在这里插入图片描述
这个只有在Web目录中才会有:
在这里插入图片描述

5.8、在IDEA中标记文件夹功能

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

5.9、在IDEA中配置Tomcat

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
解决警告问题:
必须要的配置 : 为什么会有这个问题? 我们访问一个网站,需要指定一个文件夹名字
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5.10、pom文件

pom.xml文件 为Maven的核心文件
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<!--Maven 的版本和头文件-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
<!--这里就是我们刚才配置的GAV-->
  <groupId>com.wang</groupId>
  <artifactId>JavaWeb-Demo01_maven</artifactId>
  <version>1.0-SNAPSHOT</version>
<!--  package: 项目的打包方式
jar: Java应用
war: JavaWeb应用
-->
  <packaging>war</packaging>
<!--项目名称-->
  <name>JavaWeb-Demo01_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.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
<!--项目依赖-->
  <dependencies>
<!--    具体依赖的jar配置文件-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
<!-- 项目构建的东西-->
  <build>
    <finalName>JavaWeb-Demo01_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>

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

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

5.11、IDEA操作

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

6、servlet

6.1、servlet简介

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

6.2、Hello servlet

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

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

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

子项目中会有:

<person>
新版本的idea中不会自动生成
</person>

父项目中的Java程序子项目中可以直接使用:

son extends father;//类似于Java中的继承

3.Maven环境优化
1.修改web.xml为最新的

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

2.将maven的结构搭建完整
在这里插入图片描述
4.编写一个Servlet程序
1.编写一个普通类
2.实现Servlet接口,这里我们直接继承HttpServlet

public class HelloServlet extends HttpServlet {

    //由于get 或者post只是请求实现的不同的方式,可以相互调用,其业务逻辑相同;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        //ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter();//相应流
        writer.print("Hello Servlet");
    }

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

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

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

6.配置Tomcat
注意:配置Tomcat的项目路径就可以了
7.启动Tomcat

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>/hello1</url-pattern>
</servlet-mapping>
<servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello2</url-pattern>
</servlet-mapping>
<servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello3</url-pattern>
</servlet-mapping>
<servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello4</url-pattern>
</servlet-mapping>
//通过这种方法可以,让多个路径访问同一个项目

3.一个Servlet可以指定通用映射路径

<!--        servlet的请求路径-->
<!--        在<url-pattern>中可以通过自定义后缀实现映射  如*.wanghailin
 注意点: *为通配符前面不能加项目映射的路径-->
        <servlet-mapping>
                <servlet-name>hello</servlet-name>
                <url-pattern>/*</url-pattern>//这样可以使http://localhost:8080/....都可以访问到这个页面
        </servlet-mapping>

4.指定一些后缀或者前缀等等…

   <!--   servlet的请求路径-->
<!--        在<url-pattern>中可以通过自定义后缀实现映射  如*.wanghailin
 注意点: *为通配符前面不能加项目映射的路径-->
        <servlet-mapping>
                <servlet-name>hello</servlet-name>
                <url-pattern>*.wanghailin</url-pattern>//***.wanghailin可以访问到这个页面
        </servlet-mapping>

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

6.5、ServletContext

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

1.共享数据
我在这个Servlet中保存的数据,可以在另外一个servlet中拿到;
将数据存放在servletContext中;(放置数据的类)

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();//servlet上下文,实现servlet中的文本共享
        String username = "王海林";
        context.setAttribute("王海林",username);//将数据以对象的形式保存在ServletContext中,其对象名为:username,值为"王海林"

    }

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

得到servletContext中的数据(读取数据的类)

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("uaername");
        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>com.Wang.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>com.Wang.servlet.GetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>getc</servlet-name>
    <url-pattern>/getc</url-pattern>
  </servlet-mapping>

启动Tomcat测试;

2.获取初始化参数

<!--  配置web应用初始化参数-->
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc://mysql/localhost:3306/mybatis</param-value>
  </context-param>
public class servletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        //需要一个响应将 url中的值传递出去
        resp.getWriter().print(url);
    }

3.请求转发

public class servletDemo04 extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        System.out.println("进入Demo04");
//        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
//        requestDispatcher.forward(req,resp);//调用forward实现请求转发
        //上面两个语句和起来的效果与下面这个的效果相同
        context.getRequestDispatcher("/gp").forward(req,resp);//达到实现页面不跳转,但能够获得 其他页面的值
    }

在这里插入图片描述
4、读取资源文件
Properties: 通过在Java中new出properties,然后从properties中拿到自己想要的资源;

一般在main目录下的resource文件中新建properties。在resources目录下新建properties
发现:都被打包到了同一个路径下: classes,我们俗称这个路径为classpath:

思路:需要一个文件流;

username = wanghailin
password = 123456
public class servletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //通过getContext()来拿到所有的东西(相当与一个中间商所有的请求都需要通过它来实现传递
        //getResourceAsStream("这里是相对路径") 通过该方法来实现将properties中的资源变成 流
        //路径中第一个/代表当前web应用,路径要以编译过的路径为准
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/dp.properties");
        //设置一个资源,用来加载 流
        Properties prop = new Properties();
        //将 流 填充到properties中去
        prop.load(is);
        //通过该对象获得相应的资源
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");
        //返回的响应
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print(user+":"+pwd);
    }

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

启动Tomcat访问测试即可;

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 setBufferSize(int 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);

    void setStatus(int var1);
  • 响应的状态码
int SC_CONTINUE = 100;
    int SC_SWITCHING_PROTOCOLS = 101;
    int SC_OK = 200;
    int SC_CREATED = 201;
    int SC_ACCEPTED = 202;
    int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    int SC_NO_CONTENT = 204;
    int SC_RESET_CONTENT = 205;
    int SC_PARTIAL_CONTENT = 206;
    int SC_MULTIPLE_CHOICES = 300;
    int SC_MOVED_PERMANENTLY = 301;
    int SC_MOVED_TEMPORARILY = 302;
    int SC_FOUND = 302;
    int SC_SEE_OTHER = 303;
    int SC_NOT_MODIFIED = 304;
    int SC_USE_PROXY = 305;
    int SC_TEMPORARY_REDIRECT = 307;
    int SC_BAD_REQUEST = 400;
    int SC_UNAUTHORIZED = 401;
    int SC_PAYMENT_REQUIRED = 402;
    int SC_FORBIDDEN = 403;
    int SC_NOT_FOUND = 404;
    int SC_METHOD_NOT_ALLOWED = 405;
    int SC_NOT_ACCEPTABLE = 406;
    int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    int SC_REQUEST_TIMEOUT = 408;
    int SC_CONFLICT = 409;
    int SC_GONE = 410;
    int SC_LENGTH_REQUIRED = 411;
    int SC_PRECONDITION_FAILED = 412;
    int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    int SC_REQUEST_URI_TOO_LONG = 414;
    int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    int SC_EXPECTATION_FAILED = 417;
    int SC_INTERNAL_SERVER_ERROR = 500;
    int SC_NOT_IMPLEMENTED = 501;
    int SC_BAD_GATEWAY = 502;
    int SC_SERVICE_UNAVAILABLE = 503;
    int SC_GATEWAY_TIMEOUT = 504;
    int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

2、下载文件
1.向浏览器输出消息(一直在讲,就不说了)

2.下载文件

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

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//    1.要获取下载文件的路径
        String realPath = "C:\\Users\\whl151885\\Desktop\\Markdown学习\\JavaWeb-02-servlet\\response\\src\\main\\resources\\1.png";
        System.out.println("下载文件名:"+realPath);
//    2.下载的文件名是啥?文件路径的最后一个/后面的字符,这个/需要转义,所以写成//
        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
//    3.设置想办法让浏览器(Content-disposition)能够支持下载我们需要的东西,使用URLEncoder.encode(fileName,"UTF-8")解决文件名乱码的问题
        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();
    }

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

3. 验证码实现

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //让浏览器每5秒自动刷新一次
        resp.setHeader("refresh","5");
        //在内存中创建一个图片
        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.CYAN);
        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());

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
//老程序员必会
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 7 - num.length(); i++) {
            buffer.append("0");
        }
        num = buffer.toString()+num;
        return num;
    }

4.实现重定向

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	//tomcat的配置的项目地址/web.xml中配置的这个servlet的地址,所以这里写的是"/r/image"
        resp.sendRedirect("/r/image");//重定向实现页面跳转,url的地址会发生改变
    }

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

面试题:请你聊聊重定向与转发的区别
相同点:

  • 页面都会跳转

不同点:

  • 请求转发时,url的地址不会发生改变
  • 重定向时,url的地址会发生改变
    在这里插入图片描述
    登录表单:
<html>
<body>
<%@ page pageEncoding="UTF-8"%>
    
    //action="${pageContext.request.contextPath}/login" 表示该表单中的内容所要,提交的地址
<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>

servlet后端处理:

    @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);
        resp.sendRedirect("/r1/success.jsp");//重定向

    }

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

接收context信息的页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Success 软考必过</h1>
</body>
</html>

6.7、HttpServletRequest

在这里插入图片描述
在这里插入图片描述
1.获得前端传递的数据
在这里插入图片描述
2.获取参数,请求转发
登录表单

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<h2>登录</h2>
<div style="text-align: center">
    <form action="${pageContext.servletContext.contextPath}/login" method="post">
        用户名:<input type="text" name="username"> <br>
        密码: <input type="password" name="password"> <br>
        hobbys:
        <input type="checkbox" name="hobbys" value="女孩">女孩
        <input type="checkbox" name="hobbys" value="编程">编程
        <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>

servlet后台处理

package com.Wang.servlet;

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.lang.reflect.Array;
import java.util.Arrays;

public class LoginServlet 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[] hobbys = req.getParameterValues("hobbys");
        System.out.println("======================");
        System.out.println(username+password);
        System.out.println(Arrays.toString(hobbys));
        System.out.println("======================");

        req.getRequestDispatcher("/success.jsp").forward(req,resp);//请求转发

    }

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

接收页面

<%--
  Created by IntelliJ IDEA.
  User: whl151885
  Date: 2021/7/6
  Time: 9:44
  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>

7、Cookie、Session

7.1、会话

会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
**有状态会话:**一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;
你能怎么证明你是西开的学生?

你 西开
1.发票 西开给你发票
2.学校登记 西开标记你来过了
—个网站,怎么证明你来过?
客户端 服务端

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

7.2、保存会话的两种技术

cookie

  • 客户端技术(响应,请求)
    session
  • 服务器技术,利用这个技术,可以保存用户的会话信息?我们可以把信息或者数据放在Session中!

常见常见:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!

7.3、Cookie

在这里插入图片描述
1.从请求中拿到cookie信息
2.服务器响应给客户端cookie

Cookie[] cookies = req.getCookies();//从请求中获得cookie
cookie.getName() //获得cookie的key 也就是cookie的名字
cookie.getValue() //获得cookie的Value
new Cookie("lastLoginTime",System.currentTimeMillis()+"");//新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie在网站中的保存时间
resp.addCookie(cookie)//响应给服务端一个cookie

运用实例:

package com.Wang.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置格式
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        PrintWriter out = resp.getWriter();
        //判断所有cookie,如果没有的话该怎么办
        Cookie[] cookies = req.getCookies();
        if (cookies!=null){

            out.write("你上次访问的时间为:");

            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];

                if (cookie.getName().equals("lastLoginTime")){
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
            }
        }else {
            out.write("z这是你第一次登录该网站;");
        }

        //创建一个cookie
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(24*60*60);
        resp.setContentType("text/html;charset=utf-8");
        resp.addCookie(cookie);


    }

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

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

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

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

删除Cookie;

  • 不设置有效期,关闭浏览器,自动失效;
  • 设置有效期时间为0;
    编码解码:
URLEncoder.encode("秦疆", "utf-8")
URLDecoder.decode(cookie.getvalue(, "UTF-8")

7.4、Session(重点)

在这里插入图片描述什么是Session:

  • 服务器会给每一个用户(浏览器)创建一个Seesion对象;
  • 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
  • 用户登录之后,整个网站它都可以访问! -->保存用户的信息;保存购物车的信息…
    在这里插入图片描述session和cookie的区别:
  • Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
  • Session把用户的数据写到用户独占Session中,服务器端保存︰(保存重要的信息,减少服务器资源的浪费).Session对象由服务创建;

使用场景:

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

使用Seesion

package com.Wang.servlet;

import com.Wang.pojo.Person;

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

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", new Person("王海林",3));
        //获取session的id
        String sessionId = session.getId();
        //判断这个id是不是session的新id
        if (session.isNew()){
            resp.getWriter().write("这是一个新的id"+sessionId);
        }else {
            resp.getWriter().write("这不是一个新的id"+sessionId);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
package com.Wang.servlet;

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

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读入东西
        Object name = session.getAttribute("name");
        System.out.println(name);
    }
}
package com.Wang.servlet;

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

public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //获得session
        HttpSession session = req.getSession();
        //移除session
        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原理

思路:JSP到底怎么执行的!

  • 代码层面没有任何问题
  • 服务器内部工作

tomcat中有一个work目录;
IDEA中使用Tomcat的会在IDEA的tomcat中生产一个work目录
在这里插入图片描述在这里插入图片描述浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet!
JSP最终也会被转换成为一个Java类!
JSP本质上就是一个Servlet
在这里插入图片描述1.判断请求
2.内置一些对象
在这里插入图片描述3.输出页面前的代码
在这里插入图片描述4.以上这些对象我们可以在就是怕页面中直接使用
在这里插入图片描述
在JSP页面中;
只要是Java代码就会原封不动的输出;
如果是HTML代码,就会被转换成:

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

这样的格式输出到前端!

8.3、JSP基本语法

使用时需要导入的依赖

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

    </dependencies>

JSP表达式

<%--  JSP表达式
作用:用来将程序的输出 ,输出到客户端
  模板:   <%= 变量或者表达式%>

--%>
<%= new java.util.Date()%>

JSP脚本片段

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

%>

脚本片段的再实现

<%
  int x=100;
  out.println(x);
%>
<p>这是一个jsp页面</p>
<%
  int y=20;
  out.println(y);
%>


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

  %>

<h1>hello zhoujie <%=i%></h1>

<%
  }
%>

JSP声明

<%!
  static {
    System.out.println("这里是静态代码块");
  }
  private int globaVal = 0;
  public void Wang(){
    System.out.println("这是一个方法");
  }
%>

JSP声明:会被编译到SP生成Java的类中!其他的,就会被生成到_jspService方法中!在JSP,嵌入Java代码即可!

<% %> 
<%= %>
<%! %>
<%-- 注释 --%>

jsp的注释在客户端中 不能被查看 ,HTML可以被查看

8.4、JSP指令

<%@page .....%> 导入包
<%@include file="">
    
<%--@include 会将多个页面合二为一--%>
<%@ include file="common/head.jsp"%>
<h1>页面主体</h1>
<%@ include file="common/foot.jsp"%>


<hr>

<%--
jsp:include 本质上是拼接页面,本质上还是3个页面
--%>
<jsp:include page="common/head.jsp"></jsp:include>
<h1>页面主体</h1>
<jsp:include page="common/foot.jsp"></jsp:include>

8.5、9大内置对象

  • PageContext 存东西
  • Request 存东西
  • Response
  • Session 存东西
  • Application 【SerlvetContext】存东西
  • config【serlvetConfig )
  • out
  • page
  • exception
<%--
  Created by IntelliJ IDEA.
  User: whl151885
  Date: 2021/7/7
  Time: 11:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--内置对象--%>
<%
    pageContext.setAttribute("name1","王海林01");//保存的数据在一个页面内有效
    session.setAttribute("name2","王海林02");//保存的数据在请求中有效,请求转发会携带这个数据
    request.setAttribute("name3","王海林03");//保存的数据在一次会话中有效,从打开游览器到关闭游览器
    application.setAttribute("name4","王海林04");//保存的数据在服务器中有效,从打开服务器到关闭服务器
%>

<%--
脚本片段中的代码会被原封不动的转换为 jsp.java 的形式
注意:因此在脚本代码中要注意 Java代码的语法规范
--%>

<%
    //通过pageContext来取出,find寻找出来
    //从底层到高层(根据作用域来)
    String name1 = (String) pageContext.getAttribute("name1");
    String name2 = (String) pageContext.getAttribute("name2");
    String name3 = (String) pageContext.getAttribute("name3");
    String name4 = (String) pageContext.getAttribute("name4");
    String name5 = (String) pageContext.getAttribute("name5");


%>
<%--使用EL表达式来取出--%>
<h1>取出的值为:</h1>
${name1}
${name2}
${name3}
${name4}
${name5} //等价与 <%=name5 %>



</body>
</html>
  • request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用的!
  • session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车;
  • application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据;

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

需要导入的依赖

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

EL表达式: ${ }

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

JSP标签

<%--给jspTag2 发出请求 并携带着 参数--%>
<jsp:forward page="jspTag2.jsp">
    <jsp:param name="name1" value="王海林"/>
</jsp:forward>
     
    
    

<%--接收tag的请求 打印在页面上--%>
姓名:<%= request.getParameter("name1")%>

JSTL表达式

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

  • 格式化标签
  • SQL标签
  • XML标签
  • 核心标签(掌握部分即可)
    在这里插入图片描述
    JSTL标签库使用步骤
  • 引入对应的taglib
  • 使用其中的方法
  • 在Tomcat也需要引入jstl的包,否则会报错:JSTL解析错误

c:if

<body>

<h1>if测试</h1>

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

<%--判断是否为管理员 --%>
<c:if test="${param.username=='admin'}" var="isAdmin">
    <c:out value="管理员欢迎您"></c:out>
</c:if>

<c:out value="isAdmin"></c:out>



</body>

c:when

<body>
<%--定义一个变量 score value = 80 --%>
<c:set var="score" value="80"></c:set>

<c:choose>
    <c:when test="${score>=90}" >
        <c:out value="1"></c:out>
    </c:when>
    <c:when test="${score>=80}" >
        <c:out value="2"></c:out>
    </c:when>
    <c:when test="${score>=70}" >
        <c:out value="3"></c:out>
    </c:when>
    <c:when test="${score>=60}" >
        <c:out value="4"></c:out>
    </c:when>
    <c:when test="${score>=50}" >
        <c:out value="5"></c:out>
    </c:when>
</c:choose>

</body>

c:forEach

<body>

<%
    ArrayList<String> person = new ArrayList<>();
    person.add(0,"王海林");
    person.add(1,"王海林");
    person.add(2,"王海林");
    person.add(3,"王海林");
    person.add(4,"王海林");
    request.setAttribute("list",person);
%>
<%--
var ,每一次遍历出来的变量

items,要遍历的对象

begin,哪里开始

end,到哪里

step,步长
--%>

<c:forEach var="person" items="${list}">
    <c:out value="${person}"></c:out>
</c:forEach>

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

</c:forEach>

</body>

9、JavaBean

实体类
JavaBean有特定的写法:

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

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

ORM:对象关系映射

  • 表—>类
  • 字段–>属性
  • 行记录---->对象

people表

idnameageaddress
1王王3杭州
2王王123杭州
3王王233杭州
Class people{
    private int id;
    private String name;
    private int age;
    private String address;
}
Class A{
    new people("1","周洁","3","衢州);
    new people("1","周洁","3","衢州);
    new people("1","周洁","3","衢州);
}

10、MVC三层架构

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

10.1、早些年

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

servlet–CRUD–>数据库弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBc、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
程序猿调用
|
JDBC
|
Mysq1 oracle sqlserver …”

10.2、MVC三层架构

在这里插入图片描述
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接口,重写对应的方法即可

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {


    //初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现!
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化");
    }
//chain: 链
//    1.过滤所有的代码 ,在过滤特定请求时都会被执行
//    2.过滤完后必须让过滤器 继续往下执行
//     filterChain.doFilter(servletRequest,servletResponse);必须要写
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;Charset=utf-8");

        System.out.println("CharacterEncodingFilter过滤前");
        filterChain.doFilter(servletRequest,servletResponse);//相当于过滤器的阀口,让过滤前后的数据,输出来

        System.out.println("CharacterEncodingFilter过滤后");
    }
    
//销毁: web服务器关闭的时候,过滤会销毁
    public void destroy() {
        System.out.println("CharacterEncodingFilter注销");
    }
}

3).在web.xml中配置 Filter

 <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.Wang.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
<!--        只要是/servlet 请求, 都会走这个过滤器-->
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>

12、监听器

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

1.编写一个监听器

2.实现监听器的接口

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//统计网站在线人数: 统计session
public class OnLineCountListener implements HttpSessionListener {
    @Override
    //创建session监听:看你的一举一动
    // 一旦创建Session就会触发一次这个事件!
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        ServletContext cxt = httpSessionEvent.getSession().getServletContext();
        Object onLineCount = cxt.getAttribute("OnLineCount");

        if (onLineCount==null){
            onLineCount = new Integer(1);
        }else {
            int count = (int) onLineCount;
            onLineCount = (Integer)count+1;
        }
        cxt.setAttribute("onLineCount",onLineCount);
    }

    @Override
    //销毁session监听:看你的一举一动
    // 一旦销毁Session就会触发一次这个事件!
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext cxt = httpSessionEvent.getSession().getServletContext();
        Object onLineCount = cxt.getAttribute("OnLineCount");

        if (onLineCount==null){
            onLineCount = new Integer(1);
        }else {
            int count = (int) onLineCount;
            onLineCount = (Integer)count-1;
        }
        cxt.setAttribute("onLineCount",onLineCount);
    }
    
    
    /*
session销毁:
1.手动销毁getsession ().invalidate(;
2.自动销毁 在xml中配置销毁时间
*/
}

2.web.xml中注册监听器

<listener>
        <listener-class>com.Wang.listener.OnLineCountListener</listener-class>
    </listener>

3.看情况是否使用!

13、过滤器、监听器常见应用

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

1.用户登录之后,向Sesison中放入用户的数据
2.进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!
login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<h1>login</h1>
<form action="/servlet/login" method="post">
    <input type="text" name="username">
    <input type="submit">
</form>
</body>
</html>

LoginServlet

package com.Wang.servlet;


import com.Wang.util.Constant;

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

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得前端传来的数据
        String username = req.getParameter("username");								
        //判断
        if (username.equals("admin")) {
            //将这个请求放到session中
            req.getSession().setAttribute(Constant.USER_SESSION, req.getSession().getId()); 	
            resp.sendRedirect("/sys/success.jsp");// 重定向
        } else {
            resp.sendRedirect("/error.jsp");
        }
    }

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

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>home</title>
</head>
<body>
<h1>this is home!</h1>
<p><a href="/servlet/logout">注销</a></p>
</body>
</html>

error.jsp

<%--
  Created by IntelliJ IDEA.
  User: whl151885
  Date: 2021/7/8
  Time: 14:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>error</title>
</head>
<body>
<h1>error</h1>
<h2>错误! 没有用户名!</h2>
<p><a href="/login.jsp">返回登录页面</a></p>
</body>
</html>

LoginOut

package com.Wang.servlet;

import com.Wang.util.Constant;

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

public class LoginOut extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取当前session中的值
        Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
        if(user_session==null){
            req.removeAttribute(Constant.USER_SESSION);
        }
        resp.sendRedirect("/login.jsp");
    }

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

SysFilter过滤器:过滤登录结果

package com.Wang.filter;

import com.Wang.util.Constant;
import com.mysql.cj.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //为了拿到session ,我们需要将 seq 与 response的权限给提高
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //通过判断session的值是否为空 如果为空的话 就跳转到错误的页面
        if(request.getSession().getAttribute(Constant.USER_SESSION)==null){
            response.sendRedirect("/error.jsp");
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}

Constant:存放普通变量

package com.Wang.util;

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

14、JDBC

什么是JDBC : Java连接数据库!
在这里插入图片描述需要jar包的支持:·

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

实验环境搭建

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

INSERT INTO users(id,`name`,`password`,eamil,birthday)
VALUE(1,'张三','123456','zs@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,eamil,birthday)
VALUE(2,'李四','123456','ls@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,eamil,birthday)
VALUE(3,'王五','123456','ww@qq.com','2000-01-01');


SELECT * FROM users;

导入数据库依赖

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

idea连接数据库
在这里插入图片描述
JDBC固定步骤:

  • 1.加载驱动
  • 2.连接数据库,代表数据库
  • 3.向数据库发送SQL的对象Statement : CRUD
  • 4.编写SQL(根据业务,不同的SQL)
  • 5.执行sQL
  • 6.关闭连接
package com.Wang.test;

import com.mysql.jdbc.Driver;

import java.sql.*;

public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //设置配置信息
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";
        //导入驱动
        Class.forName("com.mysql.jdbc.Driver");
        //连接数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //创建数据库操作对象
        Statement statement = connection.createStatement();
        //实现想执行的操作
        String sql = "select * from jdbc.users";
        //将执行的操作给操作数据库的对象
        ResultSet resultSet = statement.executeQuery(sql);
        //选择打印自己想查的数据,选择性输出
        while (resultSet.next()){
            System.out.println("id"+resultSet.getString("id"));
            System.out.println("name"+resultSet.getString("name"));
            System.out.println("password"+resultSet.getString("password"));
            System.out.println("eamil"+resultSet.getString("eamil"));
            System.out.println("birthday"+resultSet.getString("birthday"));
        }
        //为不影响数据库的性能 关闭连接 遵循先开后关的原则
        resultSet.close();
        statement.close();
        connection.close();

    }
}

预编译的方式

package com.Wang.test;

import java.sql.*;

public class TestJdbc2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //设置配置信息
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";
        //导入驱动
        Class.forName("com.mysql.jdbc.Driver");
        //连接数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //实现想执行的操作
        String sql = "insert into users(id,name,password,eamil,birthday) value (?,?,?,?,?)";

        //使用预编译来操作数据库
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,3);
        preparedStatement.setString(2,"王海林呀");
        preparedStatement.setString(3,"123456");
        preparedStatement.setString(4,"20@qq.com");
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));

        int i = preparedStatement.executeUpdate();
        if (i>0){
            System.out.println("插入成功"+i);
        }
        //为不影响数据库的性能 关闭连接 遵循先开后关的原则
        preparedStatement.close();
        connection.close();

    }
}

事务

要么都成功,要么都失败!

ACID原则:保证数据的安全。

开启事务
事务提交 commit()
事务回滚 ro11back()
关闭事务
转账: A :1000 B:1000 A(900)–100–>B(1100)

Junit单元测试
依赖

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

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

package com.Wang.test;

import org.junit.Test;

public class TestJdbc3 {

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

测试成功:
在这里插入图片描述
测试失败:
在这里插入图片描述

package com.Wang.test;

import org.junit.Test;

import java.sql.*;

public class TestJdbc3 {

    @Test
    public void test() throws ClassNotFoundException, SQLException {
        //设置配置信息
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";
        //导入驱动
        Class.forName("com.mysql.jdbc.Driver");

        Connection connection =null;

        try {
            //连接数据库
            connection = DriverManager.getConnection(url, username, password);

            //开启事务
            connection.setAutoCommit(false);

            //实现想执行的操作
            String sql1 = "update account1 set money=money-100 where name='A'";
            String sql2 = "update account1 set money=money+100 where name='B'";

            connection.prepareStatement(sql1).executeUpdate();
            connection.prepareStatement(sql2).executeUpdate();


            connection.commit();
            System.out.println("success!");

        } catch (SQLException throwables) {
            connection.rollback();
            System.out.println("失败");

            throwables.printStackTrace();
        }finally {
            System.out.println("结束");
        }
    }
}
  //使用预编译来操作数据库
    PreparedStatement preparedStatement = connection.prepareStatement(sql);

    preparedStatement.setInt(1,3);
    preparedStatement.setString(2,"王海林呀");
    preparedStatement.setString(3,"123456");
    preparedStatement.setString(4,"20@qq.com");
    preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));

    int i = preparedStatement.executeUpdate();
    if (i>0){
        System.out.println("插入成功"+i);
    }
    //为不影响数据库的性能 关闭连接 遵循先开后关的原则
    preparedStatement.close();
    connection.close();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值