JavaWeb
1. 基本概念
web开发:
- web,网页的意思,www.baidu.com
- 静态web
- HTML,CSS
- 提供给所有人看的数据始终不会发生改变
- 动态web
- 提供给所有人看的数据始终会发发生变化,每个人在不同的时间,不同的地点看到的信息各不相同
- 技术栈:Servlet/JSP,ASP,PHP
在java中,动态web资源开发的技术称为javaweb
1.1 前言
1.2web应用程序
web应用程序:可以提供浏览器访问的程序;
- a.html,b.html…多个web资源,这些web资源可以被外界访问,对外界提供服务
- 能访问到的任何一个页面或者资源,都存在于某一台计算机上
- URL
- 这个统一的web资源会被放在同一个文件夹下,web应用程序->Tomcat:服务器
- 一个web应用由多部份组成(静态web,动态web)
- html,css,js
- jsp,servlet
- java程序
- jar包
- 配置文件(properties)
web应用程序编写完毕后,若想提供给外界访问,需要一个服务器来统一管理
1.3静态web
- *.htm,.html这些都是网页的后缀,如果服务器上一直存在这些东西,我们就可以直接进行读取
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gpLBroHP-1625719190370)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210621093621650.png)]
静态web存在的缺点
- web页面无法动态更新,所有用户看到的都是同一个页面
- 轮播图,点击特效:伪动态
- JavaScript[实际开发使用]
- VBscript
- 无法和数据库交互(数据无法持久化,用户无法交互)
1.4 动态web
页面会动态展示:web的页面展示的效果因人而异
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t6iNsHgF-1625719190376)(JavaWeb.assets/image-20210621094515779.png)]
缺点:
- 假如服务器的动态web资源出现了错误,我们需要重新编写我们的后台程序重新发布
- 停机维护
优点:
- web页面可以动态更新,所有用户都看到的都不是同一个界面
- 它可以与数据库交互(数据持久化:注册,商品信息,用户信息)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Dtfb8bxw-1625719190379)(JavaWeb.assets/image-20210621094830316.png)]
2.web服务器
2.1技术讲解
ASP
- 微软:国内最早流行的就是ASP
- 在HTML中嵌入了VB的脚本,ASP+COM
- 在ASP开发中,基本一个页面都有几千行大二业务代码,页面极其紊乱
- 维护成本高
- c#
- IIS
PHP
- PHP开发速度很快,功能很强大,跨平台,代码简单
- 无法承载大访问量的情况(局限性)
JSP/Servlet
B/S:浏览器和服务器
C/S:客户端和服务器
- sun公司主推的B/S
- 基于java语言(所有的大公司,或者一些开源的组件,都是java写的)
- 可以承载三高问题带来的影响
- 语法像ASP
2.2 web服务器
服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息
IIS
微软,ASP,Windows中自带的
3.Tomcat
3.1安装Tomcat
Tomcat官网https://tomcat.apache.org/
3.2Tomcat启动和配置
文件夹作用
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AVaK2klU-1625719190384)(JavaWeb.assets/image-20210621102438666.png)]
3.3配置
服务器核心配置文件
conf/server.xml
可以配置启动的端口号,主机的名称,默认8080端口,默认的主机名为localhost->127.0.0.1,默认网站应用存放的位置为:webapps
网站是如何进行访问的:
-
输入一个域名,回车
-
检查本机hosts配置文件有没有这个域名的映射
- 有:直接放回对应的ip地址
127.0.0.1 localhost
- 没有,去DNS服务器,找到则返回
3.4发布一个web网站
- 将自己写的网站,放到服务器(Tomcat)中指定的web应用的文件夹下(webapps)下,就可以
网站应该有的结构
--webapps:Tomcat服务器web目录
-ROOT
-dong
-WEB-INF
-classes:java程序
-lib:web应用所依赖的jar包
-web.XML
-index.html 默认的首页
-static
-css
-style.css
-js
-img
4.Http
4.1什么是http
超文本传输协议
简单的请求响应协议,通常运行在TCP
- 文本:html,字符串
- 超文本:图片,音乐,视频,定位,地图
- 80端口
https:443
4.2两个时代
- http1.0
- HTTP/1.0,客户端可以与web服务器连接,只能获得一个web资源,断开连接
- http2.0
- HTTP/1.1,客户端可以与web服务器连接,可以获得多个web资源
4.3Http请求
- 客户端-发请求-服务器
百度:
request URL:请求地址
请求方法: GET get、post方法
状态代码: 200 状态码
远程(remote)地址: 23.40.240.75:443
accept: text/plain,
accept-encoding: gzip, deflate, br
accept-language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6 语言
cache-control: no-cache
origin: https://www.baidu.com
pragma: no-cache
referer: https://www.baidu.com/?tn=92768678_hao_pg
sec-ch-ua: " Not;A Brand";v="99", "Microsoft Edge";v="91", "Chromium";v="91"
sec-ch-ua-mobile: ?0
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.54
1.请求行
- 请求行中的请求方式:GET
- 请求方式:**GET,POST,**HEAD,DELETE,PUT,TRACT
- get:请求能够携带的参数比较小,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全,但高效
- 请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内容,安全,但不高效
2.消息头
accept:告诉浏览器它所支持的数据类型
accept-encoding:支持那种编码格式 GBK UTF-8 GB2312 IOS8859-1
accept-language:告诉浏览器它的语言环境
cache-control: 缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机
4.4Http响应
- 服务器-响应-客户端
Cache-Control:private 缓存控制
Connection:连接
Connection-Encoding:gzip 编码
Content-Type:text/html 类型
1.响应体
accept:告诉浏览器它所支持的数据类型
accept-encoding:支持那种编码格式 GBK UTF-8 GB2312 IOS8859-1
accept-language:告诉浏览器它的语言环境
cache-control: 缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机
refrush:告诉客户端,多久刷新一次
location:让网页重新定位
2.响应状态码
200:请求响应成功 200
3xx:请求重定向
- 重定向:重新到新的位置去
4xx:找不到资源 404
- 资源不存在
5xx:服务器代码错误 500 502:网关错误
当浏览器地址栏输入地址并回车的一瞬间到页面能够展示回来,经历了什么
5.Maven
- 在javaweb开发中,需要使用大量的jar包,需要手动导入
- 让东西自动导入和配置这个jar包
5.1Maven项目架构管理工具
Maven核心思想:约定大于配置
- 有约束,不要去违反
Maven会规定好你该如何去编写我们的java代码,必须要按照这个规范来
5.2下载安装
5.3环境配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HrcWHcyh-1625719190389)(JavaWeb.assets/image-20210621173338000.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nd1iUvvG-1625719190391)(JavaWeb.assets/image-20210621173508415.png)]
5.4阿里云镜像
修改Maven的settings.xml文件,在mirrors标签内添加:
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
5.5本地仓库
建立一个本地仓库
<localRepository>F:\environment\Maven\apache-maven-3.8.1\maven-repo</localRepository>
5.6在IDEA中使用Maven
- 启动IDEA
- 创建一个Maven项目
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yC8QeKBC-1625719190393)(JavaWeb.assets/image-20210621181736388.png)]
- IDEA中Maven设置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pib4dDqO-1625719190396)(JavaWeb.assets/image-20210622103012398.png)]
IDEA中配置Maven
:注意:经常在IDEA中会出现一个问题就是项目自动创建完成后,它这个MavenHome会使用IDEA默认,我们如果发现这个问题,手动改为本地的
到这里,Mven在IDEA中的配置和使用就OK了
一个干净的Maven
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-T7gNVInI-1625719190400)(JavaWeb.assets/image-20210622103733115.png)]
main.java:放置java源代码的
main.resources:放置一些配置文件的
test.java:测试使用
一个干净的Maven
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nXd6IpJu-1625719190403)(JavaWeb.assets/image-20210622104007722.png)]
这个只有在Web应用下才会用
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j9XDoZcI-1625719190405)(JavaWeb.assets/image-20210622104239766.png)]
web.xml:web的配置
index.jsp:网页
标记文件夹功能
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nAekE5oM-1625719190406)(JavaWeb.assets/image-20210622104657554.png)]
项目结构配置:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uugGoK9C-1625719190408)(JavaWeb.assets/image-20210622104838362.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nr7sXCar-1625719190409)(JavaWeb.assets/image-20210622104953631.png)]
5.7在IDEA中配置Tomcat
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7SGExaln-1625719190411)(JavaWeb.assets/image-20210622105722739.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RdB7k6Qo-1625719190413)(JavaWeb.assets/image-20210622110120721.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pGBX5mfF-1625719190414)(JavaWeb.assets/image-20210622110226812.png)]
为什么会有这个问题:我们访问一个网站,需要指定一个文件夹名字(必须配置)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5jN0zqOw-1625719190417)(JavaWeb.assets/image-20210622111030125.png)]
5.8 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.dong</groupId>
<artifactId>javaweb-01-maven</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!-- Package:项目的打包方式
jar:java应用
war:javaweb应用-->
<!--配置-->
<properties>
<!-- 项目的默认构建编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 编码版本-->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<!--项目依赖-->
<dependencies>
<!-- 具体依赖的jar包配置文件-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--项目构建用的东西-->
<build>
<finalName>javaweb-01-maven</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
maven高级之处在于:他会帮你导入jar包所依赖的其他jar
maven由于他的约定大于配置,可能会遇到写的配置文件无法被导出或者生效的问题,解决方案:在build中配置resources来防止我们资源导出失败的问题
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uG4B9fgy-1625719190419)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210622214021493.png)]
servlet:
HelloServlet.java
package com.dong.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.io.PrintWriter;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
//响应的类型:HTML
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
//获取响应的输出流
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>你好!</h1>");
out.println("</body>");
out.println("</html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Maven:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--Maven版本和头文件-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 这里就是我们刚才配置的GAV-->
<groupId>com.dong</groupId>
<artifactId>javaweb-01-maven</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!-- Package:项目的打包方式
jar:java应用
war:javaweb应用-->
<!--配置-->
<properties>
<!-- 项目的默认构建编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 编码版本-->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<!--项目依赖-->
<dependencies>
<!-- 具体依赖的jar包配置文件-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
<!--项目构建用的东西-->
<build>
<finalName>javaweb-01-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>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 注册servlet-->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.dong.servlet.HelloServlet</servlet-class>
</servlet>
<!-- 一个servlet对应一个Mapping:映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 请求路径-->
<url-pattern>/dong</url-pattern>
</servlet-mapping>
</web-app>
主页:index.jsp
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
6.Servlet
6.1Servlet简介
- Servlet就是sun公司开发动态web的一门技术
- Sun公司在这些api中提供一个接口叫做:Servlet,如果你想开发一个Servlet程序,只需要完成两个小步骤
- 编写一个类实现Servlet接口
- 把开发好的java类部署到web服务器中
把实现了Servlet接口的java程序叫做,Servlet
6.2HelloServlet
Servlet接口Sun有两个默认的实现类:HttpServlet,GenericServlet
构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建议Moudel;这个空的工程就是Maven主工程
关于Maven父子工程的理解
夫项目中会有
<modules>
<module>servlet-01</module>
</modules>
子项目会有
<parent>
<artifactId>javaweb-02-servlet</artifactId>
<groupId>com.dong</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
夫项目中的java子项目可以直接使用
son extendx father
Maven环境优化
- 修改webXml为最新的
- 将Maven的结构搭建完整
编写一个Servle程序
- 编写一个普通类
- 实现Servlet接口,这里我们直接继承HttpServlet
public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ServletOutputStream outputStream = resp.getOutputStream();
PrintWriter writer = resp.getWriter();
writer.print("hello,Servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
编写Servlet的映射
为什么需要映射:我们写的是java程序,当时要通过浏览器访问,而浏览器需要连接web服务器,所以我么你需要在web服务中注册我们写的Servlet,还需要给他一个浏览器能够访问的路径
<!-- 注册Servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.dong.servlet.HelloServlet</servlet-class>
</servlet>
<!-- Servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
</web-app>
配置Tomcat
启动测试
web.xml
p8的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
HelloServlet.java
package com.dong.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入了doGet");
// ServletOutputStream outputStream = resp.getOutputStream();
PrintWriter writer = resp.getWriter();
writer.print("hello,Servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
父pom
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
6.2 Servlet原理
Servlet是由Web服务器调用,web服务器在收到浏览器请求之后,会:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bnjvGWqA-1625719190422)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210623230840647.png)]
6.4mapping
- 一个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>/hello1</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>*.do</url-pattern>
</servlet-mapping>
-
优先级问题
制定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求
6.5 ServletContext
web容器在启动时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用
1.共享数据
我在这个servlet保存的数据,可以在另外servlet中拿到
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// this.getInitParameter() 初始化参数
//this.getServletConfig() servlet配置
//this.getServletContext() servlet上下文
ServletContext context = this.getServletContext();
String username = "小明";//数据
context.setAttribute("username",username);//将一个数据保存在ServletContext中,名字为:username,值为:username
}
}
public class GetServlet extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字"+username);
}
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.dong.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.dong.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
测试访问结果
2.获取初始化参数
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.dong.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
<!-- 配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
3.请求转发
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入了Demo4");
// RequestDispatcher gp = context.getRequestDispatcher("gp");//转发的请求路径
// gp.forward(req,resp);//调用forwoed实现请求转发
context.getRequestDispatcher("/gp").forward(req,resp);
}
4. 读取资源文件
properties
- 在java目录下新建properties
- 在resources目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath
思路:需要一个文件流
username=root
password=123456
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 pwd = prop.getProperty("password");
resp.getWriter().print(username+pwd);
}
6.6 HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息,找HttpServletResponse
1. 简单分类
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException
PrintWriter getWriter() throws IOException
负责向浏览器发送响应头的方法
响应的状态码
/*
* Server status codes; see RFC 2068.
*/
/**
* Status code (100) indicating the client can continue.
*/
public static final int SC_CONTINUE = 100;
/**
* Status code (101) indicating the server is switching protocols
* according to Upgrade header.
*/
public static final int SC_SWITCHING_PROTOCOLS = 101;
/**
* Status code (200) indicating the request succeeded normally.
*/
public static final int SC_OK = 200;
/**
* Status code (201) indicating the request succeeded and created
* a new resource on the server.
*/
public static final int SC_CREATED = 201;
/**
* Status code (202) indicating that a request was accepted for
* processing, but was not completed.
*/
public static final int SC_ACCEPTED = 202;
/**
* Status code (203) indicating that the meta information presented
* by the client did not originate from the server.
*/
public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
/**
* Status code (204) indicating that the request succeeded but that
* there was no new information to return.
*/
public static final int SC_NO_CONTENT = 204;
/**
* Status code (205) indicating that the agent <em>SHOULD</em> reset
* the document view which caused the request to be sent.
*/
public static final int SC_RESET_CONTENT = 205;
/**
* Status code (206) indicating that the server has fulfilled
* the partial GET request for the resource.
*/
public static final int SC_PARTIAL_CONTENT = 206;
/**
* Status code (300) indicating that the requested resource
* corresponds to any one of a set of representations, each with
* its own specific location.
*/
public static final int SC_MULTIPLE_CHOICES = 300;
/**
* Status code (301) indicating that the resource has permanently
* moved to a new location, and that future references should use a
* new URI with their requests.
*/
public static final int SC_MOVED_PERMANENTLY = 301;
/**
* Status code (302) indicating that the resource has temporarily
* moved to another location, but that future references should
* still use the original URI to access the resource.
*
* This definition is being retained for backwards compatibility.
* SC_FOUND is now the preferred definition.
*/
public static final int SC_MOVED_TEMPORARILY = 302;
/**
* Status code (302) indicating that the resource reside
* temporarily under a different URI. Since the redirection might
* be altered on occasion, the client should continue to use the
* Request-URI for future requests.(HTTP/1.1) To represent the
* status code (302), it is recommended to use this variable.
*/
public static final int SC_FOUND = 302;
/**
* Status code (303) indicating that the response to the request
* can be found under a different URI.
*/
public static final int SC_SEE_OTHER = 303;
/**
* Status code (304) indicating that a conditional GET operation
* found that the resource was available and not modified.
*/
public static final int SC_NOT_MODIFIED = 304;
/**
* Status code (305) indicating that the requested resource
* <em>MUST</em> be accessed through the proxy given by the
* <code><em>Location</em></code> field.
*/
public static final int SC_USE_PROXY = 305;
/**
* Status code (307) indicating that the requested resource
* resides temporarily under a different URI. The temporary URI
* <em>SHOULD</em> be given by the <code><em>Location</em></code>
* field in the response.
*/
public static final int SC_TEMPORARY_REDIRECT = 307;
/**
* Status code (400) indicating the request sent by the client was
* syntactically incorrect.
*/
public static final int SC_BAD_REQUEST = 400;
/**
* Status code (401) indicating that the request requires HTTP
* authentication.
*/
public static final int SC_UNAUTHORIZED = 401;
/**
* Status code (402) reserved for future use.
*/
public static final int SC_PAYMENT_REQUIRED = 402;
/**
* Status code (403) indicating the server understood the request
* but refused to fulfill it.
*/
public static final int SC_FORBIDDEN = 403;
/**
* Status code (404) indicating that the requested resource is not
* available.
*/
public static final int SC_NOT_FOUND = 404;
/**
* Status code (405) indicating that the method specified in the
* <code><em>Request-Line</em></code> is not allowed for the resource
* identified by the <code><em>Request-URI</em></code>.
*/
public static final int SC_METHOD_NOT_ALLOWED = 405;
/**
* Status code (406) indicating that the resource identified by the
* request is only capable of generating response entities which have
* content characteristics not acceptable according to the accept
* headers sent in the request.
*/
public static final int SC_NOT_ACCEPTABLE = 406;
/**
* Status code (407) indicating that the client <em>MUST</em> first
* authenticate itself with the proxy.
*/
public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
/**
* Status code (408) indicating that the client did not produce a
* request within the time that the server was prepared to wait.
*/
public static final int SC_REQUEST_TIMEOUT = 408;
/**
* Status code (409) indicating that the request could not be
* completed due to a conflict with the current state of the
* resource.
*/
public static final int SC_CONFLICT = 409;
/**
* Status code (410) indicating that the resource is no longer
* available at the server and no forwarding address is known.
* This condition <em>SHOULD</em> be considered permanent.
*/
public static final int SC_GONE = 410;
/**
* Status code (411) indicating that the request cannot be handled
* without a defined <code><em>Content-Length</em></code>.
*/
public static final int SC_LENGTH_REQUIRED = 411;
/**
* Status code (412) indicating that the precondition given in one
* or more of the request-header fields evaluated to false when it
* was tested on the server.
*/
public static final int SC_PRECONDITION_FAILED = 412;
/**
* Status code (413) indicating that the server is refusing to process
* the request because the request entity is larger than the server is
* willing or able to process.
*/
public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
/**
* Status code (414) indicating that the server is refusing to service
* the request because the <code><em>Request-URI</em></code> is longer
* than the server is willing to interpret.
*/
public static final int SC_REQUEST_URI_TOO_LONG = 414;
/**
* Status code (415) indicating that the server is refusing to service
* the request because the entity of the request is in a format not
* supported by the requested resource for the requested method.
*/
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
/**
* Status code (416) indicating that the server cannot serve the
* requested byte range.
*/
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
/**
* Status code (417) indicating that the server could not meet the
* expectation given in the Expect request header.
*/
public static final int SC_EXPECTATION_FAILED = 417;
/**
* Status code (500) indicating an error inside the HTTP server
* which prevented it from fulfilling the request.
*/
public static final int SC_INTERNAL_SERVER_ERROR = 500;
/**
* Status code (501) indicating the HTTP server does not support
* the functionality needed to fulfill the request.
*/
public static final int SC_NOT_IMPLEMENTED = 501;
/**
* Status code (502) indicating that the HTTP server received an
* invalid response from a server it consulted when acting as a
* proxy or gateway.
*/
public static final int SC_BAD_GATEWAY = 502;
/**
* Status code (503) indicating that the HTTP server is
* temporarily overloaded, and unable to handle the request.
*/
public static final int SC_SERVICE_UNAVAILABLE = 503;
/**
* Status code (504) indicating that the server did not receive
* a timely response from the upstream server while acting as
* a gateway or proxy.
*/
public static final int SC_GATEWAY_TIMEOUT = 504;
/**
* Status code (505) indicating that the server does not support
* or refuses to support the HTTP protocol version that was used
* in the request message.
*/
public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2.常见应用
- 向浏览器输出消息
- 下载文件
- 要获取下载文件的路径
- 下载等文件名是啥?
- 设置想办法让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileOutputStream流写入到buffer缓冲区
- 使用OutputStream将缓冲区中的数据输出到客户端
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 要获取下载文件的路径
String realPath = "F:\\代码\\javaweb-03-servlet\\response\\target\\classes\\1.jpg";
System.out.println("下载文件的路径"+realPath);
// 2. 下载等文件名是啥?
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名为URLEncoder.encode(file.name,"utf-8")
resp.setHeader("Content-Disposition","attachment;filename="+fileName);
// 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 {
}
}
- 验证码功能
验证怎么来的?
- 前端实现
- 后端实现,需要用到java的图片类,生成一个图片
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器3秒自动刷新一次
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D)image.getGraphics();//笔
//设置图片的背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.BLUE);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNum(){
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i <7-num.length(); i++) {
sb.append("0");
}
num = sb.toString() + num;
return num;
}
- 实现重定向
B一个web资源收到客户端请求后,B它会通知A客户端去访问另外一个web资源C,这个过程叫重定向
常见场景:
- 用户登录
sendRedirect(String location) throws IOException
测试:
// resp.setHeader("location","/response_war/img");
// resp.setStatus(302);
resp.sendRedirect("/response_war/img");//重定向
重定向和转发的区别:
相同点:
- 页面都会跳转
不同点:
- 请求转发的时候URL不会产生变化
- 重定向时候,url会发生变化
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6AFGZUDr-1625719190424)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210624212051552.png)]
简单登陆验证
public class RequestTest 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);
//重定向时候一定要注意路径问题,否则404
resp.sendRedirect("/response_war/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
<%--这里提交的路径需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前的项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit">
</form>
6.7 HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,http请求中的所有信息会被封装到HttpServletRequest,通过HttpServletRequest我们可以获得信息
获取前端传递的参数,请求转发
req.getParameter()
req.getParameterValues()
package com.dong.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.util.Arrays;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("=====================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("==================");
//通过请求转发
req.getRequestDispatcher(req.getContextPath()+"/success.jsp").forward(req,resp);
resp.setCharacterEncoding("utf-8");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("=====================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("==================");
//通过请求转发
//这里的/代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
resp.setCharacterEncoding("utf-8");
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陆</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align: center">
<%-- 以post方式提交表单,提交到login--%>
<form action="${pageContext.request.contextPath}/login" 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="电影">电影
<br>
<input type="submit">
</form>
</div>
</body>
</html>
重定向和转发的区别:
相同点:
- 页面都会跳转
不同点:
- 请求转发的时候URL不会产生变化;307
- 重定向时候,url会发生变化;302
7.Cookie,Session
7.1会话
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话
客户端 服务端
- 服务器给客户端一个兴建,客户端下次访问服务端带上新建就可以的。cookie
- 服务器等级你来过,下次来的时候进行匹配。seesion
7.2 保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务器技术,利用这个技术,可以保存用户的会话信息?我们可以把信息或者数据放在session中
常见场景:网站登陆之后,下次不用在登陆,访问直接就上去了
7.3Cookie
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BOKnpjY8-1625719190426)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210626224519877.png)]
- 从请求中拿到cookie
- 服务器响应给客户端
Cookie[] cookies = req.getCookies();//这里返回数组,说明cookie可能存在多个
cookie.getName();//获得cookie中的key
cookie.getValue();//获得cookie中的value
new Cookie("lastLoginTime", System.currentTimeMillis()+"");//新建一个cookie
cookie.setMaxAge(24*60*60);//设置cookie有效期
resp.addCookie(cookie);//响应给客户端一个cookie
cookie:一般会保存在本地的用户目录下appdata
一个网站cookie是否存在上限:
- 一个cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
- 300个cookie浏览器上限
- cookie大小有限制4kb
删除cookie:
- 不设置有效期,关闭浏览器,自动失效
- 设置有效期时间为0
package com.dong.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();//这里返回数组,说明cookie可能存在多个
//判断cookie是否存在
if (cookies != null){
//如果存在怎么办
out.write("上次访问时间是");
// for (Cookie cookie : cookies) {
//
// }
for (int i = 0; i <cookies.length ; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if (cookie.getName().equals("lastLoginTime")){
//获取cookie的值
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
out.write(date.toLocaleString());
}
}
}else {
out.write("这是第一次访问");
}
//服务器给客户端响应一个cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
//cookie有效期为一天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.dong.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;
public class CookieDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建一个cookie,名字必须要和删除的名字一致
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
编码解码:
package com.dong.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.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
public class CookieDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Cookie[] cookies = req.getCookies();
PrintWriter out = resp.getWriter();
if (cookies != null){
//如果存在怎么办
out.write("上次访问时间是");
// for (Cookie cookie : cookies) {
//
// }
for (int i = 0; i <cookies.length ; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if (cookie.getName().equals("name")){
//获取cookie的值
// System.out.println(cookie.getValue());
//解码
out.write(URLDecoder.decode(cookie.getValue(),"Utf-8"));
}
}
}else {
out.write("这是第一次访问");
}
//编码
Cookie cookie = new Cookie("dong", URLEncoder.encode("董","utf-8"));
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
7.4Session
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KB60JmBB-1625719190428)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210626224800222.png)]
什么是Session:
- 服务器会给每一个用户(浏览器)创建一个session对象
- 一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在
- 用户登陆之后,整个网站它都可以访问 -》保存用户的信息,保存用户车的信息
Session和Cookie的区别:
- Cookie是吧用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
- session把用户的数据写到用户独占session中,服务端保存(保存重要信息,减少服务器资源的浪费)
- session对象有服务创建
使用场景:
- 保存一个登陆的用户的信息
- 购物车信息
- 在整个网站中经常会使用的数据,我们将它保存在session中
使用session:
package com.dong.servlet;
import javax.servlet.ServletException;
import javax.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","董");
//获取Session的ID
String id = session.getId();
//判断session是不是新的
if (session.isNew()){
resp.getWriter().write("session创建成功,ID:"+id);
}else {
resp.getWriter().write("session已经正在服务器中存在了"+id);
}
//session创建的时候做了什么事情
// Cookie cookie = new Cookie("JSESSIONID", id);
// resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.dong.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();
String name = (String) session.getAttribute("name");
System.out.println(name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
设置session失效
方法1:手动
package com.dong.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;
//session注销
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//手动
HttpSession session = req.getSession();
session.removeAttribute("name");
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
方法2:在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.2JSP原理
-
代码层面没有任何问题
-
服务器内部工作
tomcat中有一个work目录
IDEA中使用Tmocat的会在IDEA中生成一个work目录
-
发现页面转变成了Java程序
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet
JSP最终也会转换成一个java类
jsp本质上就是一个servlet
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lfkgA34q-1625719190430)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210703155401464.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LQBca1UX-1625719190432)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210703160005878.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HcWYw4ZB-1625719190435)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210703160319007.png)]
在JSP页面中:
只要是JAVA代码就会原封不动的输出;
如果是html就会进行转换
out.write("\r\n")
8.3 jsp基础语法
任何语言都有自己的语法,java中有,jsp作为java技术的一种应用,它拥有一些自己的扩充语法,java所有语法都支持
jsp表达式
<%-- jsp表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
<%= new java.util.Date()%>
jsp脚本片段
<%-- jsp脚本片段--%>
<%
int sum = 0;
for (int i = 1; i <=100 ; i++) {
sum+=i;
}
out.println("<h1>Sum="+sum+"</h1>");
%>
脚本片段的再实现
jsp声明:会被编译到jsp生成java的类中,其他的就会被生成到jspservice中!
<%!
static {
System.out.println("loading servlet");
}
private int globalvar = 0;
public void dong(){
System.out.println("进入了dong方法");
}
%>
在jsp中,嵌入java代码即可
<%%>
<%=%>
<%!%>
<%--注释-->
jsp的注释,不会再客户端显示,html就会
8.4 jsp指令
定制错误页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%--定制错误页面--%>
<%--<%@ page errorPage="error/500.jsp" %>--%>
<%--显示声明这是一个错误页面--%>
<%@page isErrorPage="true" %>
<%@page pageEncoding="utf-8"%>
<%@page ...%>
在web-xml定义
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
页面合并:
<%@include file=""%>
<%--@include会将三个页面合为一
所以会存在变量名冲突--%>
<%@include file="common/header.jsp"%>
<h1>网页主题</h1>
<%@include file="common/footer.jsp"%>
<hr>
<%-- jsp标签
jsp:clude:拼接页面,本质还是三个
--%>
<jsp:include page="/common/footer.jsp"></jsp:include>
8.5 9大内置对象
- PageContext 存东西
- Request 存东西
- Response
- Session 存东西
- Application【ServletContext】 存东西
- config【ServletConfig】
- out
- page,几乎不用
- exception
pageContext实现转发
<%
pageContext.forward("/index.jsp");
//request.getRequestDispatcher("/index.jsp").forward(request,response); servlet实现
%>
<%--内置对象--%>
<%
pageContext.setAttribute("name1","一号");//保存的数据旨在一个页面中有效
request.setAttribute("name2","二号");//保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","三号");//保存的数据只在一次会话中有效,从打开浏览器到关闭服务器
application.setAttribute("name4","四号");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
%>
<%--脚本片段中的代码会被原封不动的生成到jsp.java
要求:这里面的代码,必须保证java语法的正确性
--%>
<%
//通过pageContext取出保存的值,我们通过寻找的方式来
String name1 = (String) pageContext.findAttribute("name1");
String name2 = (String) pageContext.findAttribute("name2");
String name3 = (String) pageContext.findAttribute("name3");
String name4 = (String) pageContext.findAttribute("name4");
String name5 = (String) pageContext.findAttribute("name5");//不存在
%>
<%--使用EL表达式输出,${}--%>
<h1>取出的值为</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>
<h3><%=name5%></h3>//如果使用这种方式的话会,页面会输出一个null
request:客户端向服务器发送的请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用的
session:客户端向服务器发送的请求,产生的数据,用户看完一会还有用,比如:购物车;
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据
8.6 JSP标签,JSTL标签,EL表达式
导包
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<!-- stabdard标签-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
EL表达式:${}
- 获取数据
- 执行运算
- 获取web开发的常用对象
jsp标签
<%--<jsp:include page=""></jsp:include>--%>
<jsp:forward page="jsptag2.jsp">
<jsp:param name="name" value="dong"/>
<jsp:param name="age" value="12"/>
</jsp:forward>
<%--取出参数--%>
名字:<%=request.getParameter("name")%>
年龄:<%=request.getParameter("age")%>
JSTL标签
JSTL标签库的使用就是为了弥补HTML标签不足:它定义许多标签,可以供我们使用,标签的功能和java代码功能一样
核心标签
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZMpHPS06-1625719190439)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210703214752782.png)]
格式化标签
SQL标签
XML标签
JSTL标签库使用步骤:
- 引入对应的taglib
- 使用其中的方法
- 在Tomcat也需要引入jstl的包,否则会报错:JSTL解析错误
c:if
<form action="coreif.jsp" method="get">
<%-- EL表达式,获取表单中的数据
${parm.参数名}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登陆">
</form>
<%--判断如果登陆的是admin,则登陆成功--%>
<c:if test="${param.username == 'admin'}" var="isadmin">
<c:out value="管理员欢迎你"></c:out>
</c:if>
<c:out value="${isadmin}"></c:out>
<%--定义一个变量score,值为85--%>
<c:set var="score" value="85"></c:set>
<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>
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}"></c:out>
<br>
</c:forEach>
<hr>
<c:forEach begin="1" end="3" step="2" var="people" items="${list}">
<c:out value="${people}"></c:out>
</c:forEach>
9.JavaBeen
<%--// People people = new People();--%>
<%--// people.setAge();--%>
<%--%>--%>
<jsp:useBean id="people" class="com.dong.pojo.People" scope="page"></jsp:useBean>
<jsp:setProperty name="people" property="address" value="北京"></jsp:setProperty>
<jsp:setProperty name="people" property="id" value="1"></jsp:setProperty>
<jsp:setProperty name="people" property="age" value="3"></jsp:setProperty>
<jsp:setProperty name="people" property="name" value="董"></jsp:setProperty>
<%--<%=people.getAddress()%>--%>
姓名:<jsp:getProperty name="people" property="name"/>
ID:<jsp:getProperty name="people" property="id"/>
年龄:<jsp:getProperty name="people" property="age"/>
地址:<jsp:getProperty name="people" property="address"/>
10.MVC三层架构
什么是MVC:Model,view,Controller 模型 视图 控制器
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gykzQozn-1625719190441)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210706210713351.png)]
用户直接访问控制层,控制层就可以直接操作数据库
servlet–curd–>数据库
弊端:程序臃肿,不利于维护 servl的代码中,处理请求,响应,试图跳转,处理jdbc,处理逻辑代码
架构:没有什么是加一层解决不了的
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2gKAeHFx-1625719190443)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210706211727901.png)]
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD(Dao)
View
- 展示数据
- 提供链接,发起Servlet请求(a,from,img…)
Controller(Servlet)
- 接收用户的请求(req:请求参数,Session信息)
- 交给业务层处理对应的代码
- 控制视图的跳转
登陆–>接受用户的登陆请求–>处理用户的请求(获取用户的登陆参数,username,password)–>交给业务层处理登陆业务(判断用户名密码是否正确:事务)–>Dao层查询用户名和密码是否正确–>数据库
11.Filter
Filter:过滤器,用来过滤网站的数据
- 处理中文乱码
- 登陆验证
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vxgb3SP8-1625719190445)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210706214034156.png)]
Filter开发步骤
- 导包
- 编写过滤器
package com.dong.filter;
import javax.servlet.*;
import java.io.IOException;
//导包导的是servlet中的
public class CharacterEncodingFilter implements Filter {
//初始化:web服务器启动,就进行初始化了,随时等待过滤对象出现
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化");
}
//Chain:链
/*
* 1.过滤中的所有代码,在脱氯特定请求的时候都会执行
* 2.必须要让过滤器继续同行
* */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("执行前");
chain.doFilter(request,response);//让我们的请求继续走,如果不写,程序到这就停止了
System.out.println("执行后");
}
//销毁:web服务器关闭的时候,过滤会销毁
public void destroy() {
System.out.println("销毁");
}
}
3.在web.xml中配置映射filter
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.dong.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!-- 只要是/servlet的任何请求,都会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
12.监听器
实现一个监听器的接口
listener
13.过滤器,监听器常见应用
- 用户登陆之后,向Session中放入用户的数据
- 进入主页的时候要判断是否已经登陆,在过滤器中实现
14.JDBC
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eCgm63im-1625719190447)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20210707135018914.png)]
需要jar包的支持:
- java.sql
- javax.sql
- mysql-conter-java(连接驱动)
实验环境搭建
导入数据库依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
package com.dong.test;
import java.sql.*;
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//?useUnicode=true&characterEncoding=gbk解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=gbk";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送sql的对象statement:CRUD
Statement statement = connection.createStatement();
//4.编写sql
String sql = "select * from users;";
//5.执行sql,返回一个ResultSet
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("id="+resultSet.getObject("name"));
System.out.println("id="+resultSet.getObject("password"));
System.out.println("id="+resultSet.getObject("email"));
System.out.println("id="+resultSet.getObject("birthday"));
}
//6.关闭连接释放资源
resultSet.close();
statement.close();
connection.close();
}
}
JDBC固定六部曲
- 加载驱动
- 连接数据库
- 向数据库发送sql对象Statement:CRUD
- 编写SQL(根据业务,不同的SQL)
- 执行SQL
- 关闭连接
ilter>
CharacterEncodingFilter
com.dong.filter.CharacterEncodingFilter
CharacterEncodingFilter
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
## 12.监听器
实现一个监听器的接口
listener
## 13.过滤器,监听器常见应用
1. 用户登陆之后,向Session中放入用户的数据
2. 进入主页的时候要判断是否已经登陆,在过滤器中实现
## 14.JDBC
[外链图片转存中...(img-eCgm63im-1625719190447)]
需要jar包的支持:
- java.sql
- javax.sql
- mysql-conter-java(连接驱动)
实验环境搭建
导入数据库依赖
```xml
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
package com.dong.test;
import java.sql.*;
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//?useUnicode=true&characterEncoding=gbk解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=gbk";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送sql的对象statement:CRUD
Statement statement = connection.createStatement();
//4.编写sql
String sql = "select * from users;";
//5.执行sql,返回一个ResultSet
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("id="+resultSet.getObject("name"));
System.out.println("id="+resultSet.getObject("password"));
System.out.println("id="+resultSet.getObject("email"));
System.out.println("id="+resultSet.getObject("birthday"));
}
//6.关闭连接释放资源
resultSet.close();
statement.close();
connection.close();
}
}
JDBC固定六部曲
- 加载驱动
- 连接数据库
- 向数据库发送sql对象Statement:CRUD
- 编写SQL(根据业务,不同的SQL)
- 执行SQL
- 关闭连接