JavaWeb
1、基本概念
1.1、web应用程序
web应用程序:可以提供浏览器访问的程序;
- a.html、b.html…多个web资源,这些web资源可以被外界访问,对外界提供服务
- 你们能访问到的任何一个页面或者资源,都存在于这个世界的某一个角楼的计算机上
- URL
- 这个统一的web资源会被放在同一个文件夹下,web应用程序:Tomcat:服务器
- 一个web应用由多个部分组成(静态web,动态web)
- html,css,js
- jsp,servlet
- java程序
- jar包
- 配置文件(properties)
web应用程序编写完毕后,若想提供给外界访问:需要一个服务器来统一管理;
1.2、静态web
-
*.html,这些网页的后缀,如果服务器上一直存在这些东西,我们就可以直接进行读取。通络;
-
静态web存在的缺点
- Web页面无法动态更新,所有用户看到都是同一个页面
- 轮播图
- JavaScript
- VBScript
- 它无法和数据库交互(数据无法持久化,用户无法交互)
- Web页面无法动态更新,所有用户看到都是同一个页面
1.3、动态web
页面会动态展示:Web的页面
缺点:
- 加入服务器的动态web资源出现了错误,我们需要重新编写我们的后台程序,重新发布
- 停机维护
优点:
- Web页面可以动态更新,所有用户看到都是不同的页面
- 可以与数据库交互(数据持久化:注册,商品信息)
2、web服务器
2.1、技术讲解
ASP
- 微软:国内最早流行的就是ASP
- 在HTML中嵌入VB脚本,ASP+COM
- 维护成本高
php
- PHP开发速度很快,功能很强大,跨平台,代码很简单
- 无法承载大访问量的情况下
JSP/Servlet
B/S:浏览器和服务器
C/S:客户端服务器
-
sun公司主推的B/S结构
-
基于java语言的
-
可以承载三高问题带来的影响
2.2、web服务器
服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息
llS
微软的:ASP
Tomcat
下载Tomcat:
- 安装
- 了解配置文件和目录结构
- 作用
3、Tomcat
3.1、安装Tomcat
https://tomcat.apache.org/download-90.cgi
3.2、Tomcat启动和配置
文件目录信息
启动和关闭Tomcat
访问测试:localhost:8080 http://localhost:8080/
3.3、配置
可以配置启动的端口号
- Tomcat默认端口号:8080
- mysql:3306
- http:80
- https:443
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
可以配置主机的名称
- 默认主机为:localhost->127.0.0.1
- 默认网站应用存放的位置为:webapps
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
高难度面试题:
请谈谈网站是如何进行访问的!
-
输入一个域名
-
检查本机的 c:\Windows\System32\drivers\etc\hosts配置文件下这个文件里的东西是否都作为本地DNS缓存
- 有:直接返回对应的ip地址,在这个地址中,有我们需要访问的web程序,可以直接访问
- 没有:去DNS云服务器中,找到就返回,找不到就报错
- 可以配置一下环境变量
3.4、发布一个web网站
将自己写的网站,放到Tomcat中指定的web应用的文件夹(webapps)下,就可以访问了
网页应有的结构
--webapps:Tomcat服务器的web目录
-Root
-xxx:网站的目录名
-WEB-INF
-classes:java程序
-lib:web应用所依赖的jar包
-web.xml:网站配置文件
-index.html 默认的首页
-static
-css
-style.css
-js
-img
-...
4、Http
4.1、什么是HTTP
http(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP之上。
- 文本:html,字符串,~~~
- 超文本:图片,音乐,视频,定位,地图
- 80端口
Https:安全的
- 443
4.2、两个时代
- http1.0
- HTTP/1.0:客户端可以与 web服务器连接后,只能获得一个web资源,断开连接
- http2.0
- HTTP/1.1:客户端可以与 web服务器连接后,可以获得多个web资源
4.3、Http请求
- 客户端—发请求(Requset)—服务器
百度:
请求 URL: https://www.baidu.com/
请求方法: GET
状态代码: 200 OK
远程地址: 14.215.177.39:443
Accept: text/html
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:max-age=0
Connection: keep-alive
4.3.1、请求行
- 请求行中的请求方式:GET
- 请求方式:Get,Post,HEAD,DELETE,PUT
- get:请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全,但高效
- post:请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内容,不安全,不高效
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式,GBK,UTF-8
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机
4.4、Http响应
- 服务器—响应—客户端
百度:
Cache-Control: private 缓存控制
Connection: keep-alive 连接
Content-Encoding: gzip 编码
Content-Type: text/html;charset=utf-8 类型
4.4.1、响应体
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式,GBK,UTF-8
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机
Refrlush:告诉客户端,多久刷新一次
Location:让网页重新定位
4.4.2、响应状态码
200:请求响应成功
3**:请求重定向
- 重定向:你重新到我给你的新位置去
4xx:找不到资源 404
- 资源不存在
5xx:服务器代码错误 500 502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车的一瞬间到页面能够展示回来,经历了什么?
5、Maven
为什么要学这个?
- 在javaweb开发中,需要使用大量的jar包,我们手动去导入;
- 如何能够让一个东西自动帮我导入和配置这个jar包。
5.1、Maven项目架构管理工具
我们目前用来接收方便导入jar包
Maven的核心思想:约定大于配置
- 有约束,不要去违反
Maven会规定好你该如何去编写我们的java代码,必须要按照这个规范来
5.2、下载安装Maven
下载完成后,解压即可
5.3、配置环境变量
配置如下环境变量:
- M2_HOME maven目录下的bin目录
- MAVEN_HOME maven的目录
- 在系统的path中配置 %MAVEN_HOME%\bin
测试Maven是否安装成功,保证必须配置成功
5.4、阿里云镜像
- 镜像:mirrors
- 作用:加速我们的下载
- 国内建议使用阿里云镜像
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
5.5、本地仓库
在本地的仓库,远程仓库
建立一个本地仓库:localRepos
<localRepository>D:\Maven\apache-maven-3.6.3\maven-repo</localRepository>
5.6、在IDEA中使用Maven
- 在idea中创建一个MavenWeb项目
2. 等待项目初始化完毕
-
观察maven仓库中多了什么东西?
-
IDEA中Maven设置
- 到这来,Maven在IDEA中的配置就完成了
5.7、创建一个普通的Maven项目
在最开始的时候,不勾选模板
这个只有在Web应用下才会有
5.8、标记文件夹功能
5.9、在IDEA中配置Tomcat
创建Tomcat:
解决警告问题:
必要的配置:我们访问一个网站,需要指定一个文件夹名字
5.10、pom文件
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.hao</groupId>
<artifactId>javaweb-01-maven</artifactId>
<version>1.0-SNAPSHOT</version>
<!--packaging:项目的打包方式
jar:java应用
war:JavaWeb应用
-->
<packaging>war</packaging>
<name>javaweb-01-maven Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<!--配置-->
<properties>
<!--项目的默认构建编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--编码版本-->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!--项目依赖-->
<dependencies>
<!--具体依赖的jar包配置文件-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--项目构建用的东西-->
<build>
<finalName>javaweb-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由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
<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.12、IDEA操作
6、Servlet
6.1、Servlet简介
-
Servlet就是sun公司开发动态web的一门技术
-
Sun在这些API中提供一个接口叫做:Servlet,如果你想开发一个Servlet程序,只需要完成两个小步骤:
- 编写一个类,实现Servlet接口
- 把开发好的java类部署到web服务器中
把实现了Servlet接口的java程序叫做 Servlet
6.2、HelloServlet
实现结构:自己写的类 --> HttpServlet --> GenericServlet -->Servlet
-
构建一个普通的Maven项目,删除里面的src目录,以后我们学习就在这个项目里面建立Moudel;这个空的工程技术Maven主工程;
-
关于Maven父子工程的理解:
父项目中会有
<modules> <module>servlet-01</module> </modules>
子项目会有
<parent> <artifactId>javaweb-02-servlet</artifactId> <groupId>com.hao</groupId> <version>1.0-SNAPSHOT</version> </parent>
父项目中的java子项目可以直接使用
son extends father
-
Maven环境优化
- 修改web.xml为最新的
- 将maven的结构搭建完整
-
编写一个Servlet程序
- 编写一个普通类
- 实现Servlet接口,这里我们直接继承HTTPServlet
package com.hao; 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; /** * @author 许浩 * @date 2020/7/10 - 22:25 */ public class HelloServlet extends HttpServlet { // 由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = resp.getWriter(); // 响应流 writer.print("Hello,Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
-
编写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> <servlet-name>hello</servlet-name> <servlet-class>com.hao.HelloServlet</servlet-class> </servlet> <!--Servlet的请求路径--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
-
配置Tomcat
-
启动测试
6.3、Servlet原理
- 当客户端浏览器向服务器请求一个 Servlet 时,服务器收到该请求后,首先到容器中检索与请求匹配的 Servlet 实例是否已经存在。
- 若不存在,则 Servlet 容器负责加载并实例化出该类 Servlet的一个实例对象,接着容器框架负责调用该实例的 init() 方法来对实例做一些初始化工作,然后Servlet 容器运行该实例的 service() 方法。
- 若 Servlet 实例已经存在,则容器框架直接调用该实例的 service() 方法。
service() 方法在运行时,自动派遣运行与用户请求相对应的 doXX() 方法来响应用户发起的请求。通常,每个 Servlet 类在容器中只存在一个实例,每当请求到来时,则分配一条线程来处理该请求。在处理请求时: - Servlet容器会创建一个请求对象ServletRequst,其中封装了用户请求的信息,以便处理客户端请求,此外还会创建一个响应对象ServletResponse,用于响应客户端请求,向客户端返回数据。
- 然后Servlet容器把创建好的ServletRequst和ServletResponse对象传给用户所请求的Servlet。
- Servlet利用ServletResponse包含的数据和自身的业务逻辑处理请求,并把处理好的结果写在ServletResponse中,最后Servlet容器把响应结果传给用户。
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可以指定通用映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
- 默认请求路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
- 指定一些后缀或前缀等等…
<!--可以自定义后缀实现请求映射
注意点:*前面不能加项目映射的路径
hello/dafsdf.xuhao也可以,只要是以xuhao结尾的
-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.xuhao</url-pattern>
</servlet-mapping>
-
优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求
<!--404--> <servlet> <servlet-name>error</servlet-name> <servlet-class>com.hao.ErrorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
6.5、ServletContext
web容器在启动的时候,它会为每个web程序创建一个对应的ServletContext对象,它代表当前的web应用
创建的ServletContext凌驾于所有的Servlet上,他们都会访问同一个ServletContext
6.5.1、共享数据
我在这个Servlet中保存的数据,可以在另一个Servlet中使用
共享数据:
/**
* @author 许浩
* @date 2020/7/12 - 16:31
*/
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,值为许浩
}
}
读取数据:
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String)context.getAttribute("username");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
resp.getWriter().print("名字:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.hao.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.hao.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
测试访问结果:先进行设置值,然后获取值
6.5.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.hao.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GP</servlet-name>
<url-pattern>/GP</url-pattern>
</servlet-mapping>
6.5.3、请求转发
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
//请求转发
//RequestDispatcher requestDispatcher = context.getRequestDispatcher("/GP"); // 转发请求路径
//requestDispatcher.forward(req,resp); //调用forwad实现请求转发
context.getRequestDispatcher("/GP").forward(req,resp);
}
6.5.4、读取资源文件
Properties
- 在java目录下创建properties
- 在resources目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath
思路:需要一个文件流;
public class ServletDemo05 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 user=prop.getProperty("username");
String pwd=prop.getProperty("password");
resp.getWriter().print(user+":"+pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
properties:
username=xuhao
password=123456
6.6、HttpServletResponse
Web服务器接收到客户端http请求,针对这个请求,分别创建一个代表请求的HTTPServletRequest对象,代表响应一个HttpServletResponse
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HTTPServletResponse
6.6.1、简单分类
负责向浏览器发送数据的方法
public PrintWriter getWriter() throws IOException;
public ServletOutputStream getOutputStream() throws IOException;
负责向浏览器发送响应头的方法
public void setContentType(String type);
public void setContentLengthLong(long len);
public void setContentLength(int len);
public void setCharacterEncoding(String charset);
响应的状态码
6.6.2、下载文件
用法一:1.向浏览器输出消息
用法二:2.下载文件
1.要获取下载文件的路径
2.下载的文件名是什么
3.设置想办法让浏览器能够支持我们下载的内容
4.获取下载文件的输入流
5.常见缓冲区
6.获取OutputStream对象
7.将FileOutputStream流写到缓冲区
8.使用OutputStream将缓冲区中的数据输出到客户端
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.要获取下载文件的路径
String realPath = "D:\\JavaWeb\\javaweb-02-servlet\\response\\target\\classes\\1.png";
// 2.下载的文件名是什么
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3.设置想办法让浏览器能够支持我们下载的内容,将名字为中文的文件进行URLEncode.encode编码
resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"uft-8"));
// 4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
// 5.常见缓冲区
int len=0;
byte[] buffer = new byte[1024];
// 6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
// 7.将FileOutputStream流写到缓冲区
while ((len=in.read(buffer))!=-1){
out.write(buffer,0,len);
}
in.close();
out.close();
}
6.6.3、验证码
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 如何让浏览器5s自动刷新一次
resp.setHeader("refresh","3");
// 在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
// 得到图片
Graphics2D g=(Graphics2D) image.getGraphics(); // 笔
// 设置图片的背景颜色
g.setColor(Color.white);
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-cahche");
resp.setHeader("Pragma","no-cahche");
// 把图片写给浏览器
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;
}
6.6.4、实现重定向
B一个web资源收到A请求后,B他会通知A客户端去访问另外一个web资源C,这个过程叫重定向
常见场景:
- 用户登录
public void sendRedirect(String location) throws IOException;
测试:
public class RdeirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
resp.setHeader("Location","/response_war/image");
resp.setStatus(302);
*/
resp.sendRedirect("/response_war/image"); // 重定向
}
面试题:请你聊聊请求转发和重定向的区别?
相同点
- 页面都会实现跳转
不同点
- 请求转发的url不会变化
- 重定向时,url地址栏会发生变化
6.7、HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息;
6.7.1、获取请求传递的参数
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobbys");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
}
6.7.2、请求转发
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobbys");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
/* // 重定向转发
resp.sendRedirect("/success.jsp");*/
// 通过请求并转发
req.getRequestDispatcher("/success.jsp").forward(req, resp);
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align: center">
<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>
7、Cookie、Session
7.1、会话
**会话:**用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程称之为会话
**有状态会话:**服务端知道客户端曾经来过,这个过程叫有状态会话
一个网站,怎么证明你来过?
客户端 服务端
- 服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了; cookie
- 服务端登记你来过了,下次你来的时候我来匹配你; session
7.2、保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务器技术,利用这个技术,可以保存用户的会话信息,我们可以把信息或数据放在Session中
常见场景:网站登录之后,你下次不用再登录,第二次访问直接上去了
7.3、Cookie
- 从请求中拿到cookie信息
- 服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();// 获得一个cookie,返回一个数组
cookie.getName(); // 获得cookie中的key
cookie.getValue(); // 获得cookie中的value
cookie.setMaxAge(24*60*60); // 设置cookie的有效期
resp.addCookie(cookie); // 响应给客户端一个cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");//新建一个cookie
注意:
- 一个Cookie只能保存一个信息;
- 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
- Cookie大小有限制4kb
- 300个cookie浏览器上限
删除Cookie:
- 不设置有限期,关闭浏览器,自动失效;
- 设置有限期时间为0;
编码解码:
URLDecoder.decode(cookie.getValue(), "uft-8")
URLEncoder.encode("许浩", "utf-8")
7.4、Session(重点)
什么 Session:
- 服务器会给每一个用户(浏览器)创建一个Session对象
- 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就一直存在
- 用户登录之后,整个网站它都能访问
Session和cookie的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以存多个)
- Session把用户的数据写到用户独占Session中,服务端保存
- Session对象由服务器创建
使用场景:
- 保存一个登录用户的信息
- 购物车信息
- 在整个网站中经常会使用的数据,我们将它保存在Session中
使用Session:
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// 得到Session
HttpSession session = req.getSession();
// 给Session中存东西
session.setAttribute("name",new Person("许浩",18));
// 获取Session的ID
String id = session.getId();
// 判断Session是不是新创建的
if(session.isNew()){
resp.getWriter().write("session创建成功,ID为:"+id);
}else{
resp.getWriter().write("session已经存在,ID为:"+id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
@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();
Person person = (Person) session.getAttribute("name");
System.out.println(person.toString());
}
@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.removeAttribute("name");
// 手动注销Session
session.invalidate();
}
会话自动过期:web.xml配置
<!--设置Session默认的失效时间-->
<session-config>
<!--1分钟后Session自动失效,已分钟为单位-->
<session-timeout>1</session-timeout>
</session-config>
8、jsp
8.1、JSP原理
电脑中idea中jsp的位置:
C:\Users\浅墨\AppData\Local\JetBrains\IntelliJIdea2020.1\tomcat\Unnamed_javaweb-session-cookie\work\Catalina\localhost\javaweb_session_cookie_war\org\apache\jsp
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet
JSP本质就是一个Servlet
在JSP页面中:
只要是java代码就会原封不动的输出
如果是HTML代码,就会转换为:
out.write("<html>\r\n")
这样的格式
8.3、JSP基础语法
JSP有一些自己的语法,同时java语法都支持
JSP表达式
<%--JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或表达式%>
--%>
<%= new java.util.Date()%>
JSP脚本片段
<%--JSP脚本片段--%>
<%
int sum=0;
for (int i = 0; i < 100; i++) {
sum+=i;
}
out.println("<h1>Sum="+sum+"</h1>");
%>
脚本片段再实现
<%
int x=0;
out.println(x);
%>
<p>这是一个JSP文档</p>
<%
int y=0;
out.println(y);
%>
<%--在代码嵌入HTML元素--%>
<%
for (int i = 0; i < 2; i++) {
%>
<h1>Hello,World</h1>
<%
}
%>
JSP声明
<%--JSP声明--%>
<%!
static{
System.out.println("Loading Servlet");
}
private int globalvar=0;
public void test(){
System.out.println("进入了test方法");
}
%>
JSP声明:会被编译到JSP生成JAVA的类中,其他的则会被生成到_jspService方法中
语法:
<%%>
<%=%>
<%!%>
<%--注释--%>
JSP的注释不会显示在客户端显示,HTML就会
8.4、JSP指令
<%@page args... %>
<%@include file=""%>
<%--@include会将两个页面合二为一--%>
<%@include file="commom/header.jsp"%>
<h1>网页主体</h1>
<%@include file="commom/footer.jsp"%>
<%--jsp标签
jsp:include:拼接页面,本质还是三个页面
--%>
<jsp:include page="/common/header.jsp"/>
<h1>网页主体</h1>
<jsp:include page="/common/footer.jsp"/>
8.5、9大内置对象
- PageContext 存东西
- Request 存东西
- Response
- Session 存东西
- Application 【ServletContext】 存东西
- config 【ServletConfig】
- out
- page
- exception
pageContext.setAttribute("name1","许浩1"); //保存的数据只在一个页面中有效
request.setAttribute("name2","许浩2"); //保存的数据只在一个请求中有效,请求转发会携带这个数据
session.setAttribute("name3","许浩3"); //保存的数据只在一次会话中有效,从打开服务器到关闭服务器
application.setAttribute("name4","许浩4"); //保存的数据只在服务器中有效,从打开服务器到关闭服务器
request:客户端向服务端发送请求,产生的数据,用户用完了就没用了(新闻)
session:客户端向服务端发送请求,产生的数据,用户用完了还有用(购物车)
application:客户端向服务端发送请求,产生的数据,一个用户用完了其他用户还能用
8.6、JSP标签、JSTL标签、EL表达式
<!--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标签
<%--<jsp:include page="jsptag2.jsp"></jsp:include>--%>
<jsp:forward page="/jsptag2.jsp">
<jsp:param name="name" value="xuhao"/>
<jsp:param name="age" value="18"/>
</jsp:forward>
<%--取出参数--%>
名字:<%=request.getParameter("name")%>
年龄:<%=request.getParameter("age")%>
JSTL表达式
JSTL标签库的使用激素为了弥补HTML标签的不足,它自定义许多标签,可以供我们使用,标签的功能和java代码一样
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
核心标签
JSTL标签库使用步骤
- 引入对于的taglib
- 使用其中的方法
- 在Tomcat也需要引入jstl的包,否则会报错:JSTL解析错误
<c:if >
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%--引入JSTL核心标签库,我们才能使用JSTL核心库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<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>
<%--判断如果提交的用户名是管理员,则登录成功--%>
<%--<%
if(request.getParameter("username").equals("admin")){
out.print("登录成功");
}
%>--%>
<c:if test="${param.username=='admin'}" var="isadmin">
<c:out value="管理员欢迎你"/>
</c:if>
<c:out value="${isadmin}"/>
</body>
</html>
<c:chose > <c:when >
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%--引入JSTL核心标签库,我们才能使用JSTL核心库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>when测试</h4>
<hr>
<%--定义一个变量score,指为85--%>
<c:set var="score" value="85"/>
<c:choose>
<c:when test="${score>=90}">
你的成绩为优秀
</c:when>
<c:when test="${score>=80}">
你的成绩为良好
</c:when>
<c:when test="${score>=60}">
你的成绩为一般
</c:when>
<c:when test="${score<60}">
你的成绩为不及格
</c:when>
</c:choose>
</body>
</html>
< c:foreach >
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%--引入JSTL核心标签库,我们才能使用JSTL核心库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>foreach测试</h4>
<hr>
<%
ArrayList<String> people = new ArrayList<>();
people.add(0, "张三");
people.add(1, "李四");
people.add(2, "王五");
request.setAttribute("list", people);
%>
<%--
var,每一次遍历出来的变量
items,要遍历的对象
--%>
<c:forEach var="peoples" items="${list}">
<c:out value="${peoples}"/> <br>
</c:forEach>
<hr>
<c:forEach var="peoples" items="${list}" begin="0" end="3" step="2">
<c:out value="${peoples}"/> <br>
</c:forEach>
</body>
</html>
9、JavaBean
实体类
JavaBean有特定的写法:
- 必须要有一个无参构造
- 属性必须私有化
- 必须有对应的get/set方法
一般用来和数据库的字段做映射 ORM
ORM:对象关系映射
- 表—类
- 字段—属性
- 行记录—对象
<%@ page import="com.hao.pojo.People" %>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--
<%
People people=new People();
%>
--%>
<jsp:useBean id="people" class="com.hao.pojo.People" scope="page"/>
<jsp:setProperty name="people" property="address" value="长沙"/>
<jsp:setProperty name="people" property="id" value="1"/>
<jsp:setProperty name="people" property="age" value="18"/>
<jsp:setProperty name="people" property="name" value="诺言"/>
姓名:<jsp:getProperty name="people" property="name"/>
ID:<jsp:getProperty name="people" property="id"/>
年龄:<jsp:getProperty name="people" property="age"/>
地址:<jsp:getProperty name="people" property="address"/>
</body>
</html>
10、MVC三层架构
什么是MVC:Model view Controller 模型,视图,控制器
10.1、早些年的架构
用户直接访问控制器,控制器就可以直接操作数据库
servlet--CRUD--->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求,响应,视图跳转,处理JDBC,处理业务代码,逻辑代码
架构:没有什么是加一层解决不了的
10.2、三层架构
Model
- 业务处理:业务逻辑(service)
- 数据持久层:CRUD(Dao)
View
- 展示数据
- 提供链接发起Servlet请求(a,form,img。。。)
Controller(Servlet)
- 接收用户请求
- 接收用户的请求:(req:请求参数,Session信息)
- 交给业务层处理对应的代码
- 控制视图的跳转
11、Filter
Filter:过滤器,用来过滤网站的数据
- 处理中文乱码
- 登录验证
- 。。。
步骤:
-
导包
-
编写过滤器
- 导包不要倒错了,javax.servlet
- 实现Filter接口,实现响应的方法
public class CharacterEncoding implements Filter { // 初始化:web服务器启动,就已经初始化了,随时准备执行 public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharacterEncoding已经初始化"); } //chain:链 /* 1.过滤中的所有代码,在过滤特定请求的时候都会执行 2.必须要让过滤器继续执行 filterChain.doFilter(servletRequest,servletResponse); */ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); servletResponse.setContentType("text/html;charset=UTF-8"); System.out.println("CharacterEncoding执行前"); filterChain.doFilter(servletRequest,servletResponse); //让我们的请求继续走,如果不写,到这里就被拦截停止了 System.out.println("CharacterEncoding执行后"); } //销毁:web服务器关闭的时候,过滤会销毁 public void destroy() { System.out.println("CharacterEncoding已经销毁"); } }
-
在web.xml中配置Filter
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.hao.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncoding</filter-name>
<filter-class>com.hao.filter.CharacterEncoding</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
12、监听器
实现一个监听器的接口:
-
编写一个监听器
实现监听器的接口
// 统计网站在线人数,统计Session public class OnlineCountListener implements HttpSessionListener { // 创建session监听 // 一旦创建一个Session就会触发一次这个事件 public void sessionCreated(HttpSessionEvent httpSessionEvent) { ServletContext ctx = httpSessionEvent.getSession().getServletContext(); 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 httpSessionEvent) { ServletContext ctx = httpSessionEvent.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.自动销毁 <session-config> <session-timeout>1</session-timeout> </session-config> 2.手动销毁 httpSessionEvent.getSession().invalidate() */ } }
-
web.xml中注册监听器
<!--注册监听器--> <listener> <listener-class>com.hao.listener.OnlineCountListener</listener-class> </listener>
-
看情况是否使用
13、过滤器,监听器的常见使用
用户登录之后才能进入主页!用户注销之后就不能进入主页
-
用户登录之后,向Session中放入用户的数据
-
进入主页的时候要判断用户是否已经登录(在过滤器中实现)
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; if (request.getSession().getAttribute("USER_SESSION") == null) { response.sendRedirect("/error/error.jsp"); } filterChain.doFilter(req, resp); }
源代码:
Constant
package com.hao.util;
/**
* @author 许浩
* @date 2020/7/17 - 20:28
*/
public class Constant {
public final static String USER_SESSION = "USER_SESSION";
}
SysFilter
package com.hao.filter;
import com.hao.util.Constant;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 许浩
* @date 2020/7/17 - 20:56
*/
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (request.getSession().getAttribute(Constant.USER_SESSION) == null) {
response.sendRedirect("/error/error.jsp");
}
filterChain.doFilter(req, resp);
}
public void destroy() {
}
}
LoginServlet
package com.hao.servlet;
import com.hao.util.Constant;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 许浩
* @date 2020/7/17 - 20:26
*/
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得前端请求的参数
String username = req.getParameter("username");
if (username.equals("admin")) { //登录成功
req.getSession().setAttribute(Constant.USER_SESSION, req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
} else { //登录失败
resp.sendRedirect("/error/error.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
LogoutServlet
package com.hao.servlet;
import com.hao.util.Constant;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 许浩
* @date 2020/7/17 - 20:41
*/
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
if (user_session != null) {
req.getSession().removeAttribute(Constant.USER_SESSION);
resp.sendRedirect("/login.jsp");
} else {
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
success.jsp,login.jsp,error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>success</h1>
<p>
<a href="/servlet/logout">注销</a>
</p>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<form action="/servlet/login" method="get">
用户名:<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>错误</h1>
<h3>用户名错误</h3>
<a href="/login.jsp">返回登录页面</a>
</body>
</html>
xml
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.hao.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>com.hao.servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Logout</servlet-name>
<url-pattern>/servlet/logout</url-pattern>
</servlet-mapping>
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.hao.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping>
14、JDBC
需要jar包的支持:
- java.sql
- javax.sql
- mysql-connection.java
JDBC固定步骤:
- 加载驱动
- 连接数据库
- 想数据库方式sql对象
- 编写sql
- 执行sql
- 关闭连接
package com.hao.test;
import java.sql.*;
/**
* @author 许浩
* @date 2020/7/18 - 19:49
*/
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "0927";
//1.加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写sql
String sql = "select * from users";
//4.向数据库发送sql对象preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.执行查询,返回结果集resultSet
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("id=" + resultSet.getObject("id"));
System.out.println("username=" + resultSet.getObject("username"));
System.out.println("password=" + resultSet.getObject("password"));
System.out.println("email=" + resultSet.getObject("email"));
System.out.println("birthday=" + resultSet.getObject("birthday"));
}
//6.关闭连接
resultSet.close();
preparedStatement.close();
connection.close();
}
}
事务
ACID:保证数据的安全
开启事务 connection.setAutoCommit(false);
事务提交 connection.commit();
事务回滚 connection.rollback();
关闭事务
Junit单元测试
依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>