文章目录
JavaWeb
1、基本概念
1.1、前言
web开发:
- web,网页的意思,www.baidu.com·
- 静态web
- html,css
- 提供给所有人看的数据始终不会发生变化!
- 动态web
- 淘宝,几乎是所有的网站;
- 提供给所有人看的数据始终会发生变化,每个人在不同的时间,不同的地点看到的信息各不相同!
- 技术栈:Servlet/JSP,ASP,PHP
1.2、web应用程序web应用程序:
可以提供浏览器访问的程序;
-
a.html、b.html.….多个web资源,这些web资源可以被外界访问,对外界提供服务;
-
你们能访问到的任何一个页面或者资源,都存在于这个世界的某一个角落的计算机上。
-
URL
-
这个统一的web资源会被放在同一个文件夹下,web应用程序>Tomcat:服务器
-
一个web应用由多部分组成(静态web,动态web)
- html,css,js
- jsp,servlet
- Java程序
- 配置文件(Properties)
Web酸用程序编写完毕后,若想提供给外界访问;需费一个服务器来统一管理
1.3、静态web
- *.htm, *.html这些都是网员的后境、如果服务器上一直存在这些东四,我们就可以直接进行读取、需要网络;
静态web存在的缺点
- Web页面无法动态更新,所有用户看到都是同一个页面
- 轮播图,点击特效:伪动态
- JavaScript[实际开发中,它用的最多]
- VBScript
- 它无法和数据库交互(数据无法持久化,用户无法交互)
1.4、 动态web
页面会动态展示,“web页面的展示效果因人而异”
缺点:
- 加入服务器的动态web资源出现了错误,我们需要重新编写我们的后台程序,重新发布;
- 停机维护优点:
- Web页面可以动态更新,所有用户看到都不是同一个页面
- 它可以与数据库交互(数据持久化:注册,商品信息,用户信息………)
2、web服务器
2.1、技术讲解
ASP:
- 微软:国内最早流行的就是ASP;
- ·在HTML中嵌入了VB的脚本,ASP+COM;
- ·在ASP开发中,基本一个页面都有几干行的业务代码,页面极其换乱
- ·维护成本高!
- C#
- IIS
php:
- PHP开发速度很快,功能很强大,跨平台,代码很简单(70%,WP)
- ·无法承载大访问量的情况(局限性)
jSP/Servlet:
B/S;浏览和服务器C/S:客户端和服务器
- sun公司主推的B/S架构
- 基于Java语言的(所有的大公司,或者一些开源的组件,都是用Java写的)
- 可以承载三高问题带来的影响;
- 语法像ASP,ASP->JSP,加强市场强度;
2.2、web服务器
服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息;
lIS
微软的;ASP.,Windows中自带的
Tomcat
面向百度编程:
Tomcat是Apache 软件基金会(Apache Software Foundation)的jakarta项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat中得到体现,因为Tomcat 技术先进、性能稳定,而且免费,因而深受lava爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web应用服务器。Tomcat 服务器是一个免费的开放源代码的Web应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP程序的首选。对于一个Java初学web的人来说,它是最佳的选择
Tomcat 实际上运行JSP页面和Serlet。Tornct最新版易9.0
工作3-5年之后,可以尝试手写Tomcat服务器;下载tomcat:
- 安装or解压
- 了解配置文件及目录结构
- 这个东西的作用
3、Tomcat
3.1、安装tomcat tomcat
官网:http://tomcat.apache.org/
3.2、Tomcat启动和配置
文件夹作用:
访问测试:http://localhost:8080/
可能遇到的问题:
- Java环境变量没有配置
- 闪退问题:需要配置兼容性
- 乱码问题:配置文件中设置
可以修改 conf/logging.properties 中的 java.util.logging.ConsoleHandler.encoding = GBK 解决乱码问题
3.3、配置
可以配置启动的端口号
- tomcat的默认端口号为:8080
- mysql:3306
- http:80
- https:443
<Connector port="8081" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
可以配置主机的名称
- 默认的主机名为:localhost->127.0.0.1
- 默认网站应用存放的位置为:webapps
<Host name="www.qinjiang.com" appBase="webapps"
unpackWARs="true" autoDeploy="true">
高难度面试题:
请你谈谈网站是如何进行访问的!
-
输入一个域名;回车
-
检查本机的C:\Windows\System32\drivers\etc\hosts配置文件下有没有这个域名映射;
- 有:直接返回对应的ip地址,这个地址中,有我们需要访问的web程序,可以直接访问
- 没有:去DNS服务器找,找到的话就返回,找不到就返回找不到;
4.可以配置一下环境变量(可选性)
3.4、发布一个web网站
不会就先模仿
- 将自己写的网站,放到服务器(Tomcat)中指定的web应用的文件夹(webapps)下,就可以访问了
--webapps :Tomcat服务器的web目录
-ROOT
-kuangstudy :网站的目录名
- WEB-INF
-classes : java程序
-lib:web应用所依赖的jar包
-web.xml :网站配置文件
- index.html 默认的首页
- static
-css
-style.css
-js
-img
-.....
HTTP协议:面试
Maven:构建工具
- Maven安装包
Servlet入门
- HelloWorld!
- Servlet配置 ·原理
4、Http
4.1、什么是HTTPHTTP
(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP之上。
- 文本:html,字符串,…
- 超文本:图片,音乐,视频,定位,地图.……
- 端口:80
Https:安全的
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:14.215.177.39:443
Accept:text/html
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9 语言
Cache-Control:max-age=0
Connection:keep-alive
1、请求行
-
请求行中的请求方式:GET
-
请求方式:Get,Post,HEAD,DELETE,PUT,TRACT.…
- get:请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全,但高效
- post:请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内容,安全,但不高效。
2、消息头
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../.
4.4、Http响应
- 服务器–响应…….客户端
百度:
Cache-Control:private 缓存控制
Connection:Keep-Alive 连接
Content-Encoding:gzip 编码
Content-Type:text/html 类型
1、响应体
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../.
Refresh:告诉客户端,多久刷新一次;
Location:让网页重新定位;
2、响应状态码
200:请求响应成功200
3xx:请求重定向·重定向:你重新到我给你新位置去;
4xx:找不到资源404·资源不存在;
5xx:服务器代码错误 500 502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车的一瞬间到页面能够展示回来,经历了什么?
5、Maven
我为什么要学习这个技术?
- 在Javaweb开发中,需要使用大量的jar包,我们手动去导入;
- 如何能够让一个东西自动帮我导入和配置这个jar包。
由此,Maven诞生了!
5.1、 Maven项目架构管理工具
我们目前用来就是方便导入jar包的!
Maven的核心思想:约定大于配置
- 有约束,不要去违反。
Maven会规定好你该如何去编写我们Java代码,必须要按照这个规范来;
5.2、下载安装Maven
官网:https://maven.apache.org/
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9UPOGbe6-1655773911678)(JavaWeb.assets/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70.png)]
下载完成后,解压即可;
小狂神友情建议:电脑上的所有环境都放在一个文件夹下,方便管理;
5.3、配置环境变量
在我们的系统环境变量中配置如下配置:
- M2_HOME maven目录下的bin目录
- MAVEN_HOME maven的目录
- 在系统的path中配置%MAVEN_HOME%\bin
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CBCuwQHU-1655773911679)(JavaWeb.assets/20200423213124579.png)]
测试Maven是否安装成功,保证必须配置完毕!mvn -version
5.4阿里云镜像
- 镜像:mirrors
- 作用:加速我们的下载
- 国内建议使用阿里云的镜像
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
5.4、本地仓库
在本地的仓库,远程仓库; 建立一个本地仓库:localRepository(建议放在maven安装文件夹下)
<localRepository>本地仓库位置</localRepository>
5.5、在 IDEA 中使用 Maven
- 启动 IDEA
- 创建一个 MavenWeb 项目
- 等待项目初始化完毕
- 观察 maven 仓库中多了什么东西?
- IDEA 中的 Maven 设置
注意:IDEA 项目创建成功后,看一眼 Maven 的配置
- 到这里,Maven 在 IDEA 中的配置和使用就 OK 了!
5.6 、创建一个普通的 Maven 项目
这个只有在Web应用下才会有!
5.7、 标记文件夹功能
5.8 、在 IDEA 中配置 Tomcat
解决警告问题
必须要的配置:为什么会有这个问题:我们访问一个网站,需要指定一个文件夹名字;
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UUOASWQu-1655773911680)(JavaWeb.assets/image-20220604192909173.png)]
5.9 、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.example</groupId>
<artifactId>demo01</artifactId>
<version>1.0-SNAPSHOT</version>
<!--Package:项目的打包方式
jar:java应用
war:JavaWeb应用
-->
<packaging>war</packaging>
<!--配置-->
<properties>
<!--项目的默认构建编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--编码版本-->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<!--项目依赖-->
<dependencies>
<!--具体依赖的jar包配置文件-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
<!--项目构建用的东西-->
<build>
<finalName>demo01</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、 IDEA 查看依赖树
5.11 、解决遇到的问题
-
Maven 3.6.2
解决方法:降级为 3.6.1 -
Tomcat 闪退
-
IDEA中每次都要重复配置Maven
在IDEA中的全局默认配置中去配置 -
Maven 默认 Web 项目中的 web.xml 版本问题
-
替换为 webapp4.0 版本和 Tomcat 一致
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0" metadata-complete="true"> </web-app>
6、Servle
6.1、Servlet简介
- Servlet就是sun公司开发动态web的一门技术
- Sun在这些APi中提供一个接口叫做:Servlet,如果你想开发一个Servlet程序,只需要完成两个小步骤:
- 编写一个类,实现Serlet接口
- 把开发好java类部署到web服务器中。
把实现了Servlet接口的Java程序叫做,Servlet
6.2、HelloServlet
Serlvet接口Sun公司有两个默认的实现类:HttpServlet,GenericServled
6.2、HelloServlet
-
构建一个普通的Maven项目,删除面的src目录,以后我们的学习就在这个项目里面建立Moudel;这个空的工程就题Maven主工程;
-
关于Maven父子工程的理解;
父项目中会有<modules> <module>servlet-01</module> </modules>
子项目会有
<parent> <artifactId>javaweb-02-servlet</artifactId> <groupId>com.kuang</groupId> <version>1.0-SNAPSHOT</version> </parent>
父项目中的java子项目可以直接使用
son extends father
-
Maven环境优化
- 修改web.xml为最新的
- 将maven的结构搭建完整
-
编写一个Servlet程序
-
编写一个普通类
-
实现Servlet接口,这里我们直接继承HttpServlet
==注意:==Tomcat10以后,javax.servlet更名为jakarta.servlet,所以写成javax.servlet,tomcat就无法找到servlet依赖的类。使用导依赖的时候要导jakarta.servlet的
package com.suwei.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("进入doGet方法"); PrintWriter writer = resp.getWriter(); writer.println("Hello,Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req,resp); } }
-
-
编写Servlet的映射
为什么需要映射:我们写的是JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需
要再web服务中注册我们写的Servlet,还需给他一个浏览器能够访问的路径;<?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"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.suwei.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <!-- servlet 和 servlet-mapping 的 servlet-name 必须要相同 servlet 的 servlet-class 为 该servlet的路径(组名下的) servlet-mapping 的 url-pattern 可以随便起,为servlet的请求路径,在浏览器中请求的时候用 --> </web-app>
-
配置Tomcat
注意:配置项目发布的路径就可以了Server的配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qP7g9X5i-1655773911681)(JavaWeb.assets/image-20220604191504916.png)]
Deployment配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dsqnQRRR-1655773911682)(JavaWeb.assets/image-20220604191711559.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6jfaDbOh-1655773911683)(JavaWeb.assets/image-20220604191751300.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JBiPmjDy-1655773911684)(JavaWeb.assets/image-20220604192146388.png)]
-
启动测试,OK!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u2fAMGoj-1655773911685)(JavaWeb.assets/image-20220604185827395.png)]
6.3、Servlet原理
Servlet是由Web服务器调用,web服务器在收到浏览器请求之后,会:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mIilyXYQ-1655773911686)(JavaWeb.assets/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70.png)]
6.4、Mapping问题
-
一个Servlet可以指定一个映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
-
一个servlet可以指定多个映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello3</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello4</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello5</url-pattern> </servlet-mapping>
-
一个servlet可以指定通用映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping>
-
默认请求路径
<!--默认请求路径--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
-
指定一些后缀或者前缀等等…
<!--可以自定义后缀实现请求映射 注意点,*前面不能加项目映射的路径 hello/sajdlkajda.qinjiang --> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.qinjiang</url-pattern> </servlet-mapping>
-
优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;<!--404--> <servlet> <servlet-name>error</servlet-name> <servlet-class>com.kuang.servlet.ErrorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
6.5、ServletContext
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
6.5.1共享数据
我在这个Servlet中保存的数据,可以在另外一个servlet中拿到;
保存数据
package com.suwei.servlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// this.getInitParameter(); 初始化参数
// this.getServletConfig(); servlet配置
// this.getServletContext(); servlet上下文
ServletContext servletContext = this.getServletContext();
String username = "suwei";
servletContext.setAttribute("name",username); //将一个数据保存在了ServletContext中,键为:name 值 username
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
取出数据
package com.suwei.servlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String name = (String) servletContext.getAttribute("name");
System.out.println(name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
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">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.suwei.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getServlet</servlet-name>
<servlet-class>com.suwei.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getServlet</servlet-name>
<url-pattern>/getServlet</url-pattern>
</servlet-mapping>
</web-app>
6.5.2 获取初始化参数
<!--配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
6.5.3 请求转发
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入了ServletDemo04");
//RequestDispatcher requestDispatcher = context.getRequestDispatcher("/getParameter"); //转发的请求路径
//requestDispatcher.forward(req,resp); //调用forward实现请求转发;
context.getRequestDispatcher("/getParameter").forward(req,resp);
}
6.5.4 读取资源文件
Properties
- 在 java 目录下新建 properties
- 在 resources 目录下新建 properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:
思路:需要一个文件流;
username=root
password=0000
package com.suwei.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class GetProperties extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
prop.load(is);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
resp.getWriter().println(username + ":" + password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6.6 、HttpServletResponse
Web 服务器接收到客户端的 http 请求,针对这个请求,分别创建一个代表请求的 HttpServletRequest 对象,代表响应的一个 HttpServletResponse;
- 如果想要获取客户端请求过来的参数:找 HttpServletRequest
- 如果要给客户端响应一些信息:找 HttpServletResponse
6.6.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;
6.6.2 下载文件
给浏览器输出消息
下载文件
1.要获取下载文件的路径
2.下载的文件名是什么?
3.设置浏览器使其支持下载的内容
4.获取下载文件的输入流
5.创建缓冲区
6.获取 OutputStream 对象
7.将 FileOutputStream 写入到 buffer缓冲区
8.使用 OutputStream 将缓冲区中的数据输出到客户端
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class FileDown extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.要获取下载文件的路径
String realPath = "F:\\Java\\StudyCode\\javaweb\\study_servlet\\ServletResponse\\target\\ServletResponse-1.0-SNAPSHOT\\WEB-INF\\classes\\小人.png";
// System.out.println(realPath);
//2.下载的文件名是什么?
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
System.out.println(fileName);
//3.设置浏览器使其支持下载的内容
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
//4.获取下载文件的输入流
FileInputStream fis = new FileInputStream(realPath);
//5.创建缓冲区
int len;
byte[] bytes = new byte[1024];
//6.获取 OutputStream 对象
ServletOutputStream os = resp.getOutputStream();
//7.将 FileOutputStream 写入到 buffer缓冲区,将缓冲区中的数据输出到客户端
while ((len = fis.read(bytes)) != -1){
os.write(bytes,0,len);
}
os.close();
fis.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6.6.3 实现重定向
Web 资源 B 收到客户端 A 请求后,通知 A 访问另一个 Web 资源 C ,这个过程叫做重定向
常见场景:
- 用户登录
void sendRedirect(String var1) throws IOException;
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Redirect extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
resp.setHeader("Location","/down");
resp.setStatus(302);
*/
resp.sendRedirect("/down");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
面试题:重定向与转发的区别?
相同点:
- 页面都会实现跳转
不同点:
- 请求转发的时候,URL 不会发生变化
- 重定向时候,URL 地址栏会发生变化;
6.6.4 简单实现登录重定向
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<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>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登陆成功</h1>
</body>
</html>
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Login extends HttpServlet {
@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("/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.example.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
6.7、 HttpServletRequest
获取参数,请求转发
HttpServletRequest 代表客户端的请求,用户通过 HTTP 协议访问服务器,HTTP 请求中的所有信息会被封装到 HttpServletRequest ,通过这个HttpServletRequest 的方法,获得客户端的所有信息;
获取参数,请求转发
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>登录</title></head>
<body>
<div>
<%--${pageContext.request.contextPath}为获取项目的路径--%>
<form action="${pageContext.request.contextPath}/gd" method="post">
用户名:<input type="text" name="username"> <br>
密码:<input type="password" name="password"> <br>
爱好:<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>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>登陆成功</h1>
</body>
</html>
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class GetDispatcher 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(username + ":" + password);
System.out.println(Arrays.toString(hobbys));
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>GetDispatcher</servlet-name>
<servlet-class>com.example.servlet.GetDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetDispatcher</servlet-name>
<url-pattern>/gd</url-pattern>
</servlet-mapping>
7 、Cookie、Session
7.1、 会话
会话:用户打开一个浏览器,点击了很多超链接,访问多个 Web 资源,关闭浏览器,这个过程可以称之为会话;
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;
你能怎么证明你是学生?
你 学校
发票 学校开的发票
学校登记 校牌
你 | 学校 |
---|---|
发票 | 学校开的发票 |
学校的登记 | 学校给你的校牌 |
一个网站,怎么证明你来过?
客户端 服务端
服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了; cookie
客户端 : 服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了; cookie
服务端:服务器登记你来过了,下次你来的时候我来匹配你; seesion
7.2、 保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务器技术,利用这个技术,可以保存用户的会话信息?可将信息或数据放在 session 中
7.3、 Cookie
- 从请求中拿到 cookie 信息
- 服务器响应给客户端 cookie
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CookieDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置请求和响应时的编码
resp.setHeader("Content-type", "text/html;charset=UTF-8");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Cookie[] cookies = req.getCookies();
PrintWriter out = resp.getWriter();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if (cookies != null){
out.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("lastLoginTime")){
String value = cookie.getValue();
long l = Long.parseLong(value);
Date date = new Date(l);
String format = simpleDateFormat.format(date);
out.println(format);
}
}
} else {
out.write("这是你第一次访问");
}
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
cookie.setMaxAge(24*60*60); //给cookie设置过期时间,值位秒
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>CookieDemo</servlet-name>
<servlet-class>com.example.servlet.CookieDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo</servlet-name>
<url-pattern>/cd</url-pattern>
</servlet-mapping>
cookie : 一般会保存在本地的用户目录下 appdata ;
- 一个 Web 站点可以给浏览器发送多个 Cookie,最多存放 20 个 cookie;
- cookie 大小有限制 4kb;
- 300 个 cookie 浏览器上限
删除 Cookie;
- 不设置有效期,关闭浏览器,自动失效;
- 设置有效期为 0;
编码解码:
URLEncoder.encode("秦疆","utf-8")
URLDecoder.decode(cookie.getValue(),"UTF-8")
7.4 Session(重点)
什么是 Session ?
- 服务器会给每一个用户(浏览器)创建一个 Session 对象;
- 一个 Session 独占一个浏览器,只要浏览器没有关闭,这个 Session 就存在;
- 用户登录之后,整个网站它都可以访问!-> 保存用户的信息;保存购物车的信息…
Session 和 cookie 的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
- Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)
- Session 对象由服务创建;
使用场景:
- 保存一个登录用户的信息;
- 购物车信息;
- 在整个网站中经常会使用的数据,我们将它保存在 Session 中;
使用 Session:
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
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", "suwei");
//获取SessionID
String sessionId = session.getId();
//判断Session是不是新创建
if (session.isNew()) {
resp.getWriter().write("session创建成功,ID为:" + sessionId);
// resp.getWriter().println("session创建成功,ID为:" + sessionId);
} else {
resp.getWriter().write("session已经在服务器中存在了,ID为:" + sessionId);
// resp.getWriter().println("session已经在服务器中存在了,ID为:" + sessionId);
}
// Session实际上做了:
// Cookie cookie = new Cookie("JSESSIONID", sessionId);
// resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
===============================================================================================
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
Object name = session.getAttribute("name");
resp.getWriter().write(name.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.example.servlet;
import com.example.pojo.Person;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo03 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");
HttpSession session = req.getSession();
session.setAttribute("person",new Person(1001,"suwei"));
resp.getWriter().write("person已存入");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
===================================================================================================
package com.example.servlet;
import com.example.pojo.Person;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("person");
resp.getWriter().write(person.toString());
System.out.println(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注销session:
package com.example.servlet;
import com.example.pojo.Person;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo05 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");
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销Session
session.invalidate();
resp.getWriter().write("session清除成功");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
设置session自动过期:
<!-- 设置session默认过期时间-->
<session-config>
<!-- 以分钟为单位-->
<session-timeout>1</session-timeout>
</session-config>
8、JSP
8.1 、什么 JSP
Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!
最大的特点:
写JSP就像在写HTML
区别:
- HTML只给用户提供静态的数据
- JSP 页面中可以嵌入Java 代码,为用户提供动态数据;
8.2 、JSP 原理
服务器内部工作:
Tomcat 中有一个 work 工作目录;
IDEA 中使用 Tomcat 的会在 IDEA 中 Tomcat 中生产一个 work 目录
C:\Users\86177\AppData\Local\JetBrains\IntelliJIdea2021.1\tomcat\1e4eba22-5d13-4ce5-9c7d-4928e9446d16
发现页面转变成了 Java 程序
浏览器向服务器发送请求,不管访问什么资源,起始都是在访问 Servlet !
JSP 最终也会被转换成一个 Java 类!
JSP 本质上就是一个 Servlet
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(.HttpServletRequest request,HttpServletResponse response)`
-
判断请求
-
内置一些对象
final javax.servlet.jsp.PageContext pageContext; //页面上下文 javax.servlet.http.HttpSession session = null; //session final javax.servlet.ServletContext application; //applicationContext final javax.servlet.ServletConfig config; //config javax.servlet.jsp.JspWriter out = null; //out final java.lang.Object page = this; //page:当前 HttpServletRequest request //请求 HttpServletResponse response //响应
-
输出页面前增加的代码
response.setContentType("text/html"); //设置响应的页面类型 pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out;
-
以上这些对象可直接在 JSP 中使用
在JSP页面中;
只要是 JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为:
out.write("<html>\r\n");
这样的格式,输出到前端!
8.3、 JSP 基础语法
任何语言都有自己的语法,JAVA中有,。 JSP 作为java技术的一种应用,它拥有一些自己扩充的语法(了解,知道即可!),Java所有语法都支持!
JSP表达式
<%--JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
<%= new java.util.Date()%>
JSP脚本片段
<%
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
out.println("<h1>sum=" + sum + "</h1>");
%>
脚本片段的再实现
<%
int x = 10;
out.println(x);
%>
<h1>这是一个JSP</h1>
<%
int y = 20;
out.println(y);
%>
<hr>
<%
for (int i = 0; i < 5; i++) {
%>
<%--这里表示HelloWorld后面拼接了i--%>
<h1>Hello World <%= i%></h1>
<%
}
%>
JSP声明
<%!
static{
System.out.println("Loading Servlet");
}
private int globalVar = 10;
public void test(){
System.out.println("进入了test方法");
}
%>
JSP声明:会被编译到JSP生成Java的类中!其他的,就会被生成到_jspService方法中!
在JSP,嵌入Java代码即可!
<%%>
<%=%>
<%!%>
<%--注释--%>
JSP的注释,不会在客户端显示,HTML就会!
8.4、JSP指令
错误页面的跳转
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%-- 手动指定错误页面的跳转--%>
<%--<%@ page errorPage="/error/500.jsp" %>--%>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
// int a = 1 / 0; //有错误,跳转到自定义的500.jsp
int b = 1 / 1;
%>
</body>
</html>
<!-- xml配置错误页面跳转-->
<error-page>
<location>/error/404.jsp</location>
<error-code>404</error-code>
</error-page>
<error-page>
<location>/error/500.jsp</location>
<error-code>500</error-code>
</error-page>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<%--提取公共头部和尾部--%>
<body>
<%--@include会将两个页面合二为一--%>
<%@ include file="header/header.jsp"%>
<h1>Hello,World</h1>
<%--因为header.jsp中定义了a变量,所以会报错 证明@include会将两个页面合二为一--%>
<%--<%--%>
<%-- int a = 10;--%>
<%--%>--%>
<%@ include file="footer/footer.jsp"%>
<hr>
<%--jSP标签
jsp:include:拼接页面,本质还是三个
--%>
<jsp:include page="header/header.jsp"/>
<h1>网页</h1>
<%--这里不会报错,所以证明jsp:include:拼接页面,本质还是三个--%>
<%--<%--%>
<%-- int a = 10;--%>
<%--%>--%>
<jsp:include page="footer/footer.jsp"/>
</body>
</html>
8.5、9大内置对象
- PageContext 存东西
- Request 存东西
- Response
- Session 存东西
- Application 【SerlvetContext】 存东西
- config 【SerlvetConfig】
- out
- page ,不用了解
- exception
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
pageContext.setAttribute("name1", "1");
request.setAttribute("name2", "2");
session.setAttribute("name3", "3");
application.setAttribute("name4", "4");
%>
<%
//String name1 = (String) pageContext.getAttribute("name1");
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");
%>
<h1>取出的值为:</h1>
<h1>${name1}</h1>
<h1>${name2}</h1>
<h1>${name3}</h1>
<h1>${name4}</h1>
<h1>${name5}</h1>
<%--EL表达式自动过滤掉空值--%>
<hr>
<h1><%= name1%></h1>
<h1><%= name2%></h1>
<h1><%= name3%></h1>
<h1><%= name4%></h1>
<h1><%= name5%></h1>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
//String name1 = (String) pageContext.getAttribute("name1");
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");
%>
<%----%>
<h1>取出的值为:</h1>
<h1>${name1}</h1> <%--null,因为只在一个页面中有效--%>
<h1>${name2}</h1> <%--null,因为旨在一次请求中有效--%>
<h1>${name3}</h1> <%--3,有值,在一次session中有效--%>
<h1>${name4}</h1> <%--4,有值,在一次服务中有效--%>
<h1>${name5}</h1> <%--null,没有给name5存值--%>
<%--EL表达式自动过滤掉空值--%>
<hr>
<h1><%= name1%></h1>
<h1><%= name2%></h1>
<h1><%= name3%></h1>
<h1><%= name4%></h1>
<h1><%= name5%></h1>
</body>
</html>
pageContext.setAttribute("name1","秦疆1号"); //保存的数据只在一个页面中有效
request.setAttribute("name2","秦疆2号"); //保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","秦疆3号"); //保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","秦疆4号"); //保存的数据只在服务器中有效,从打开服务器到关闭服务器
request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用的!
session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车;
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据;
8.6、EL表达式、JSP标签、JSTL标签、
<!-- 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 标签
<%--
Created by IntelliJ IDEA.
User: 86177
Date: 2022/6/16
Time: 17:07
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>
<%--<jsp:include page=""--%>
<h1>1</h1>
<jsp:forward page="/jspTag02.jsp">
<jsp:param name="name" value="zhangsan"/>
<jsp:param name="age" value="18"/>
</jsp:forward>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: 86177
Date: 2022/6/16
Time: 17:07
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>
<h1>2</h1>
姓名:<%= request.getParameter("name")%>
年龄: <%= request.getParameter("age")%>
</body>
</html>
JSTL表达式
JSTL 标签库的使用就是为了弥补 HTML 标签的不足;它自定义许多标签,可以供我们使用,标签的功能和 Java 代码一样!
格式化标签
SQL标签
XML 标签
核心标签 (掌握部分)
JSTL标签库使用步骤
- 引入对应的 taglib
- 使用其中的方法
- 在 Tomcat 也需要引入 JSTL和standard 的包,否则会报错:JSTL 解析错误
c: if
<head>
<title>Title</title>
</head>
<body>
<h4>if测试</h4>
<hr>
<form action="coreif.jsp" method="get">
<%--
EL表达式获取表单中的数据
${param.参数名}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
<%--判断如果提交的用户名是管理员,则登录成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="管理员欢迎您!"/>
</c:if>
<%--自闭合标签--%>
<c:out value="${isAdmin}"/>
</body>
c:choose c:when
<body>
<%--定义一个变量score,值为85--%>
<c:set var="score" value="55"/>
<c:choose>
<c:when test="${score>=90}">
你的成绩为优秀
</c:when>
<c:when test="${score>=80}">
你的成绩为一般
</c:when>
<c:when test="${score>=70}">
你的成绩为良好
</c:when>
<c:when test="${score<=60}">
你的成绩为不及格
</c:when>
</c:choose>
</body>
c:forEach
<%
ArrayList<String> people = new ArrayList<>();
people.add(0,"张三");
people.add(1,"李四");
people.add(2,"王五");
people.add(3,"赵六");
people.add(4,"田六");
request.setAttribute("list",people);
%>
<%--
var , 每一次遍历出来的变量
items, 要遍历的对象
begin, 哪里开始
end, 到哪里
step, 步长
--%>
<c:forEach var="people" items="${list}">
<c:out value="${people}"/> <br>
</c:forEach>
<hr>
<c:forEach var="people" items="${list}" begin="1" end="3" step="1" >
<c:out value="${people}"/> <br>
</c:forEach>
9、 JavaBean
实体类
JavaBean有特定的写法:
- 必须要有一个无参构造
- 属性必须私有化
- 必须有对应的get/set方法;
一般用来和数据库的字段做映射 ORM;
ORM :对象关系映射
- 表—>类
- 字段–>属性
- 行记录---->对象
people表
id | name | age | address |
---|---|---|---|
1 | 秦疆1号 | 3 | 西安 |
2 | 秦疆2号 | 18 | 西安 |
3 | 秦疆3号 | 100 | 西安 |
class People{
private int id;
private String name;
private int id;
private String address;
}
class A{
new People(1,"秦疆1号",3,"西安");
new People(2,"秦疆2号",3,"西安");
new People(3,"秦疆3号",3,"西安");
}
- 过滤器
- 文件上传
- 邮件发送
- JDBC 复习 : 如何使用JDBC , JDBC crud, jdbc 事务
10、MVC三层架构
- 什么是MVC: Model view Controller 模型、视图、控制器
10.1、以前的架构
用户直接访问控制层,控制层就可以直接操作数据库;
servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
程序猿调用
↑
JDBC (实现该接口)
↑
Mysql Oracle SqlServer ....(不同厂商)
10.2、MVC三层架构
Model
- 业务处理 :业务逻辑(Service)
- 数据持久层:CRUD (Dao - 数据持久化对象)
View
- 展示数据
- 提供链接发起Servlet请求 (a,form,img…)
Controller (Servlet)
- 接收用户的请求 :(req:请求参数、Session信息….)
- 交给业务层处理对应的代码
- 控制视图的跳转
登录--->接收用户的登录请求--->处理用户的请求(获取用户登录的参数,username,password)---->交给业务层处理登录业务(判断用户名密码是否正确:事务)--->Dao层查询用户名和密码是否正确-->数据库
11、Filter (重点)
比如 Shiro安全框架技术就是用Filter来实现的
Filter:过滤器 ,用来过滤网站的数据;
- 处理中文乱码
- 登录验证….
(比如用来过滤网上骂人的话,我***我自己 0-0)
Filter开发步骤:
-
导包
-
编写过滤器
导包不要错 (注意)
实现Filter接口,重写对应的方法即可
package com.suwei.filter; import javax.servlet.*; import java.io.IOException; public class CharacterFilter implements Filter { //初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现! public void init(FilterConfig filterConfig) throws ServletException { System.out.println("过滤器初始化成功!"); } //Chain : 链 /* 1. 过滤中的所有代码,在过滤特定请求的时候都会执行 2. 必须要让过滤器继续同行 chain.doFilter(request,response); */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;characterEncoding=utf-8"); System.out.println("过滤器执行前"); chain.doFilter(request,response); System.out.println("过滤器执行后"); } //销毁:web服务器关闭的时候,过滤器会销毁 public void destroy() { System.out.println("过滤器销毁"); } }
-
在web.xml中配置 Filter
<filter> <filter-name>CharacterFilter</filter-name> <filter-class>com.suwei.filter.CharacterFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterFilter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
12、监听器
实现一个监听器的接口;(有n种监听器)
-
编写一个监听器
实现监听器的接口…
依赖的jar包
//统计网站在线人数 : 统计session public class OnlineCountListener implements HttpSessionListener { //创建session监听: 看你的一举一动 //一旦创建Session就会触发一次这个事件! public void sessionCreated(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); System.out.println(se.getSession().getId()); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount = new Integer(1); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } ctx.setAttribute("OnlineCount",onlineCount); } //销毁session监听 //一旦销毁Session就会触发一次这个事件! public void sessionDestroyed(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount = new Integer(0); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } ctx.setAttribute("OnlineCount",onlineCount); } /* Session销毁: 1. 手动销毁 getSession().invalidate(); 2. 自动销毁 */ }
-
web.xml中注册监听器
<!--注册监听器--> <listener> <listener-class>com.kuang.listener.OnlineCountListener</listener-class> </listener>
13、过滤器的使用
管理员登录之后才能进入主页!注销后就不能进入主页了!
- 用户登录之后,向Sesison中放入用户的数据
- 进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!
登录:
<%--
Created by IntelliJ IDEA.
User: 86177
Date: 2022/6/20
Time: 19:33
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>
<h1>登录</h1>
<%--这里的action的路径要和对应的Servlet的配置文件中的请求路径一样--%>
<form action="/servlet/login" method="get">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
登陆成功:
<%@ page import="com.suwei.utii.Constant" %><%--
Created by IntelliJ IDEA.
User: 86177
Date: 2022/6/20
Time: 19:32
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>
<%--<%--%>
<%-- Object attribute = request.getSession().getAttribute(Constant.userSession);--%>
<%-- if (attribute == null){--%>
<%-- response.sendRedirect("/login.jsp");--%>
<%-- }--%>
<%--%>--%>
<h1>主页</h1>
<a href="/servlet/loginOut">注销</a>
</body>
</html>
登陆失败:
<%--
Created by IntelliJ IDEA.
User: 86177
Date: 2022/6/20
Time: 19:44
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>
<h1>错误</h1>
<h2>权限不足或没有登陆</h2>
<a href="/login.jsp">点击登录</a>
</body>
</html>
登录Servlet:
package com.suwei.servlet;
import com.suwei.utii.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 Login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求的参数
String username = req.getParameter("username");
if (username.equals("admin")){ //登陆成功
req.getSession().setAttribute(Constant.userSession,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);
}
}
注销Servlet:
package com.suwei.servlet;
import com.suwei.utii.Constant;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//处理注销操作,点击注销进入这个servlet
public class LoginOut extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object attribute = req.getSession().getAttribute(Constant.userSession);
//如果用户session不为空,证明登录了
if (attribute != null){
//点击注销就移除session,并且重定向到登录页面
req.getSession().removeAttribute(Constant.userSession);
resp.sendRedirect("/login.jsp");
} else {
//否则就是没有登录,直接进入登录页面
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
过滤器拦截:
package com.suwei.filter;
import com.suwei.utii.Constant;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter 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;
Object userSession = req.getSession().getAttribute(Constant.userSession);
if (userSession == null){
resp.sendRedirect("/error/error.jsp");
}
chain.doFilter(request,response);
}
public void destroy() {
}
}
xml:
//登录
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.suwei.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<!-- 这里的请求路径对应前端页面form表单中的action请求路径-->
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
//注销
<servlet>
<servlet-name>LoginOut</servlet-name>
<servlet-class>com.suwei.servlet.LoginOut</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginOut</servlet-name>
<url-pattern>/servlet/loginOut</url-pattern>
</servlet-mapping>
//过滤器
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.suwei.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</urttern>
</filter-mapping>
letResponse;
import java.io.IOException;
//处理注销操作,点击注销进入这个servlet
public class LoginOut extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object attribute = req.getSession().getAttribute(Constant.userSession);
//如果用户session不为空,证明登录了
if (attribute != null){
//点击注销就移除session,并且重定向到登录页面
req.getSession().removeAttribute(Constant.userSession);
resp.sendRedirect("/login.jsp");
} else {
//否则就是没有登录,直接进入登录页面
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
过滤器拦截:
```java
package com.suwei.filter;
import com.suwei.utii.Constant;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter 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;
Object userSession = req.getSession().getAttribute(Constant.userSession);
if (userSession == null){
resp.sendRedirect("/error/error.jsp");
}
chain.doFilter(request,response);
}
public void destroy() {
}
}
xml:
//登录
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.suwei.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<!-- 这里的请求路径对应前端页面form表单中的action请求路径-->
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
//注销
<servlet>
<servlet-name>LoginOut</servlet-name>
<servlet-class>com.suwei.servlet.LoginOut</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginOut</servlet-name>
<url-pattern>/servlet/loginOut</url-pattern>
</servlet-mapping>
//过滤器
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.suwei.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</urttern>
</filter-mapping>