JavaWeb
java Web
1、基本概念
1.1、前言
web开发:
web,网页的意思,www.baidu.com
静态web
html,css
提供给所有人看的数据始终不会发生变化
动态web
淘宝,几乎是所有的网站
提供给所有人看的数据始终会发生变化,每个人在不同的事件,不同的地点看到的信息各不相同
技术栈:Seriet/JSP,ASP,PHP
在java中,动态web资源开发的技术统称为javaWeb
1.2、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.3、静态web
*.htm *.html这些都是网页的后缀,如果服务器上一直存在这些东西,我们就可以直接进行读取
静态web存在的缺点
Web页面无法动态更新,所有用户看到都是同一个页面
轮播图,点击特效:伪动态
JavaScript(实际开发中,它用的最多)
VBScript
它无法和数据库交互(数据无法持久化,用户无法交互)
1.4、动态web
页面会动态展示:"Web的页面展示的效果因人而已"
缺点:
加入服务器的动态Web资源出现了错误,我们需要重新编写我们的后台程序,重新发布,停机维护
优点:
Web页面可以动态更新,所有用户看到都不是同一个页面
它可以与数据库交互(数据持久化:注册,商品信息,用户信息)
新手村->魔鬼训练(分析原理,看源码)->PK场
2、Web服务器
2.1、技术讲解
ASP:
微软:国内最早流行的就是ASP
在HTML中嵌入了VB的脚本,ASP+COM;
在ASP开发中,基本一个页面都有几千行的业务代码,页面及其混乱
维护成本高
C#
iis
<h1>
<h1>
<%
System.out.println("hello")
%>
<h1>
<h1>
PHP:
php开发速度很快,功能很强大,跨平台,代码很简单(70%,WP)
无法承载大访问量的情况下(局限性)
JSP/Servlet:
B/S:浏览器和服务器
C/S:客户端和服务器
sun公司主推的B/S架构
基于Java语言的(所有的大公司,或者一些开源的组件,都是用java写的)
可以承载三高问题带来的影响(高可用,高性能,高并发)
语法像ASP,ASP-->JSP,加强市场的竞争度
2.2、web服务器
服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息
IIS
微软的:ASP...Windows中自带的
Tomcat
面向百度编程:
Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为比较流行的Web 应用服务器。
Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。对于一个java初学web者来说,它是最佳的选择
Tomcat 实际上运行JSP 页面和Servlet。Tomcat最新版本为10.0.14。
工作3-5年之后,可以尝试手写Tomcat服务器
下载tomcat:
1.安装or解压
2.了解配置文件即目录结构
3.这个东西的作用
3、Tomcat
3.1、安装Tomcat
tomcat官网:Apache Tomcat® - Welcome!
3.2、Tomcat启动和配置
文件夹作用
启动,关闭Tomcat
startup.bat闪退问题
tomcat点击startup.bat出现闪退,启动不成功的解决办法_Of_the的博客-CSDN博客_tomcat的startup闪退
访问测试:localhost:8080(默认端口号8080)
可能遇到的问题:
1.Java环境变量没有配置
2.闪退问题:需要配置兼容性
3.乱码问题:配置文件中设置
3.3、配置
可以配置启动的端口号
tomcat的默认端口号为:8080
mysql:3306
http:80
https:443
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
可以配置主机的名称
默认的主机名为:localhost
默认网站应用存放的位置为:webapps
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
高难度面试题:
请你谈一谈网站是如何进行访问的
1.输入一个域名
2.检查本机的C:\Windows\System32\drivers\etc\hosts配置文件下有没有这个域名的映射
1.有:直接返回对应的ip地址,这个地址中,有我们需要访问的web程序,可以直接访问
127.0.0.1 www.qinjiang.com
2.没有:去DNS服务器找,找到的话就返回,找不到就返回找不到
3.可以配置一下环境变量(可选项)
3.4、发布一个web网站
不会就先模仿
将自己写的网站,放到服务器(Tomcat)中指定的web应用的文件夹(webapps)下,就可以访问了
一个网站发布到Tomcat上的原理
网站应该有的结构
--webapps:Tomcat服务器的web目录
--ROOT
--kuangstudy:网站的目录名
- WEB-INF
-classes:java程序
-lib:web应用所依赖的jar包
-web.xml:网站配置文件
- index.html/index.jsp 默认的首页
- 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请求
客户端---发请求(Request)---服务器
百度:
Request URL: https://www.baidu.com/
Request Method: GET get方法 post方法
Status Code: 200 OK 状态码:200
Remote Address: 112.80.248.76:443
Referrer Policy: strict-origin-when-cross-origin
Accept:text/html,application/xhtml+xml
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,und;q=0.8 语言
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 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 ISO8859-1
Accept-Language: 告诉浏览器,它的语言环境
Cache-Control: 缓存控制
Connection: 告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../.
Refrush:告诉客户端,多久刷新一次
Location:让网页重新定位
2.响应状态码(重点)
200请求响应成功 200
3xx:请求重定向
重定向:你重新到我给你的新位置去
4xx找不到资源 404
资源不存在
5xx:服务器代码错误 500 502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车的一瞬间到页面能够展示回来,经历了什么?
5、Maven
我为什么要学习这个技术?
1.在javaweb开发中,需要使用大量的jar包
2.如何能够让一个东西自动帮我们导入和配置这个jar包,由此,Maven诞生了
5.1、Mave项目架构管理工具
我们目前用来就是方便导入jar包的
Maven和核心思想:约定大于配置
有约束,不要去违反。
Maven会规定好你如何去编写我们的java代码,必须要按照这个规范来
5.2、下载安装Maven
官网:Maven – Welcome to Apache Maven
下载完成后解压即可
5.3、配置环境变量
在我们的系统环境变量中
配置如下配置:
M2_HOME maven目录下的bin目录
MAVEN_HOME maven的目录
在系统的path中配置%MAVEN_HOME%\bin
测试Maven是否安装成功,保证必须配置完毕
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>
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
5.5、本地仓库
在本地的仓库,远程仓库;
建立一个本地仓库:localRepository
<localRepository>C:\Maven\apache-maven-3.8.5\maven-repo</localRepository>
5.6、在IDEA中使用Maven
1.启动IDEA
2.创建一个MavenWeb项目
3.等待项目初始化完毕
4.观察Maven库中多了什么东西
5.IDEA中的Maven设置
注意:IDEA项目创建成功后,看一眼Maven的配置
6.到这里,Maven在IDEA中的配置和使用就OK了!
5.7、创建一个普通的Maven项目
一个干净的Maven项目
这个只有在Web应用下才会有
5.8、标记文件夹功能
5.9、在IDEA中配置Tomcat
解决警告问题
必须要的配置:为什么会有这个问题:我们访问一个网站,需要指定一个文件夹名字
没有war包的问题
首先要保证pom.xml里面配置了
<packaging>war</packaging>
注意:这里要保证war只能有一个,不然会把所有存在的war全部打包会很慢 ,是哪个项目就打哪个项目的war包
未指定服务器错误:Error: Application Server not specified
5.10、pom文件
pom.xml是Maven核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--Maven版本和头文件-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--这里就是我们刚才配置的GAV-->
<groupId>com.kuang</groupId>
<artifactId>javaweb-01-maven</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.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!-- 项目依赖-->
<dependencies>
<dependency>
<!--具体依赖的jar包配置文件-->
<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>
建议不要用web模板创建Maven项目,建议手动创建
Maven的高级之处在于,他会帮你导入这个JAR包所依赖的其他JAR包
Maven由于他的约定大于配置,我们之后可能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<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.11、IDEA操作**
5.12、解决遇到的问题
1.Maven3.6.2 Maven无法自动导入包,build报错
原因:IDEA版本与Maven版本不兼容
解决办法
降级为3.6.1
2.Maven默认web项目中的web.xml版本问题
替换webapp版本和tomcat一致
5.13、Maven仓库的使用
问题:请求路径
<url-pattern>/kuangshen</url-pattern>
报错500
解决方法:用tomcat10的朋友们会报500,重新下一个tomcat9重新配置一下就好了
6、Servlet
6.1、Maven仓库的使用
Servlet就是sun公司开发动态web的一门技术
Sun在这些API中提供了接口叫做:Servlet,如果你想开发一个Servlet程序,只需要完成两个小步骤:
编写一个类,实现Servlet接口
把开发好的Java类部署到web服务器中
把实现了Servlet接口的Java程序叫做Servlet
6.2、HelloServlet
Servlet接口Sun公司有两个默认的实现类:HttpServlet
1.构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建立Module,这个空的工程就是Maven的主工程
2.关于Maven父子工程的理解:
父项目会有
<modules>
<module>servlet-01</module>
</modules>
子项目会有
<parent>
<artifactId>javaweb-02-servlet</artifactId>
<groupId>com.kuang</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
父项目中的jar包子项目可以直接使用
son extends father
3.Maven环境优化
1.修改web.xml为最新的
2.将maven的结构搭建完整
4.编写一个Servlet程序
1.编写一个普通类
2.实现Servlet接口,这里我们直接基础HttpServlet,GenericServlet
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);
}
}
5.编写Servlet的映射
为什么需要映射:我们写的是Java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需给他一个浏览器能够访问的路径;
<!--注册Servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
6.配置Tomcat
注意:配置项目发布的路径
7.启动测试
6.3、Servlet原理
Servlet是由Web服务器调用,web服务器在收到浏览器请求之后,会:
6.4、Mapping问题
1.一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
2一个Servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/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>
3.一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
4.默认请求路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
5.指定一些后缀或者前缀等等
<!--注意点:*前面不能加映射的路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.qinjiang</url-pattern>
</servlet-mapping>
6.优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求
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 HttpServlet {
@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;charset=utf-8");
resp.getWriter().print("名字:" + username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.kuang.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.kuang.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
2.获取初始化参数
<!--配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
public class ServletDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3.请求转发
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入了ServletDemo04");
// RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
// requestDispatcher.forward(req,resp);//调用forward实现请求转发:
context.getRequestDispatcher("/gp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4.读取资源文件
Properties
在java目录下新建properties
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
在resources目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:
思路:需要一个文件流:
username=wanjinxin
password=1314520
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");
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.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);
}
}
访问测试即可ok
6.6、HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
如果要获取客户端请求过来的参数:找HttpServletRequest
如果要给客户端响应一些信息:找HttpServletResponse
1、简单分类
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
void addIntHeader(String var1, int var2);
响应的状态码
int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2、常见应用
1.向浏览器输出消息(一直在讲,就不说了)
2.下载文件
1.要获取下载文件的路径
2.下载的文件名是啥
3.设置想办法让浏览器能够支持下载我们需要的东西
4.获取下载文件的输入流
5.创建缓冲区
6.获取OutputStream对象
7.将FileOutputStream流写入到buffer缓冲区
8.使用OutputStream将缓冲区中的数据输出到客户端
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.要获取下载文件的路径
// String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/1.png");
String realPath = "C:\\MyDownLoad\\JavaLearn\\javaweb-02-servlet\\response\\target\\response\\WEB-INF\\classes\\1.png";
System.out.println("下载的文件的路径:" + realPath);
//2.下载的文件名是啥
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
//3.设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码
resp.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
//4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
//5.创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7.将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3、验证码功能
验证码怎么来的?
前端实现
后端实现,需要哟感到java的图片类,生产一个图片
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器5秒自动刷新一次;
resp.setHeader("refresh", "3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_3BYTE_BGR);
//得到图片
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 < 8 - num.length(); i++) {
sb.append("0");
}
num = sb.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4、实现重定向(重点)
一个web资源收到客户端请求后,他会通知客户端去访问另一个web资源C,这个过程叫重定向
常见场景:
用户登录
void sendRedirect(String var1) throws IOException;
测试:
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setHeader("Location","/response_war/img");
// resp.setStatus(302);
resp.sendRedirect("/response_war/img");//重定向
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
面试题:请你聊聊重定向和转发的区别?
相同点:
页面都会实现跳转
不同点:
请求转发的时候,url不会产生变化 307
重定向的时候,url地址栏会发生变化 302
总结:1.转发是一次请求,重定向是两次2.转发不会改变url,重定向会改变3.请求转发是在服务器内部完成的,而重定向是在客户端完成的4.转发的url必须是当前web工程内部的地址,重定向可以是任意地址
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 {
doGet(req, resp);
}
}
<html>
<body>
<%@ page contentType="text/html; charset=UTF-8" %>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${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>Success</h1>
</body>
</html>
6.7、HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息
1、获取前端参数,请求转发
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobbies");
//后台接收中文乱码问题
System.out.println("=========================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
System.out.println("=========================");
//通过请求转发
//这里的/代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
7、Cookie、Session
7.1、会话
会话:用户打开了一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
有状态会话: 一个同学来过教师,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;
你能怎么证明你是西开的学生?
你 西开
1.发票 西开给你开发票
2.学校登记 西开标记你来过了
一个网站,怎么证明你来过?
客户端 服务端
1.服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了;cookie
2.服务器等级你来过了,下次你来的时候我来匹配你;session
7.2、保存会话的两种技术
cookie
客户端技术(响应,请求)
session
服务器技术,利用这个技术,可以保存用户的会话信息?我们可以把信息或者数据放在Session中
常见场景:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!
7.3、Cookie
1.从请求中拿到cookie信息
2.服务器响应给客户端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
//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器,告诉你,你来的时间,把这个时间封装成为一个信件,你下次来,我就知道你来了
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//客户端给服务端发送一个cookie
Cookie[] cookies = req.getCookies();//这里返回数组,说明Cookie可能存在多个
//判断Cookie是否存在
if(cookies!=null){
//如果存在怎么办
out.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie 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有效期为1天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
cookie:一半会保存再本地的用户目录下appdata
一个网站cookie是否存在上线!聊聊细节问题
一个Cookie只能保存一个信息
一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
Cookie大小有限制4kb
300个cookie浏览器上限
删除Cookie
不设置有效期,关闭浏览器,自动失效;
设置有效期时间为0;
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有效期设置为0,立马过期
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
中文数据传递
URLEncoder.encode("秦疆","utf-8")
URLDecoder.decode(cookie.getValue(),"UTF-8")
//中文数据传递
public class CookieDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器,告诉你,你来的时间,把这个时间封装成为一个信件,你下次来,我就知道你来了
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//客户端给服务端发送一个cookie
Cookie[] cookies = req.getCookies();//这里返回数组,说明Cookie可能存在多个
//判断Cookie是否存在
if(cookies!=null){
//如果存在怎么办
out.write("name:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if(cookie.getName().equals("name")){
//获取cookie中的值
//解码
out.write(URLDecoder.decode(cookie.getValue(),"UTF-8"));
}
}
}else{
out.write("这是您第一次访问本站");
}
//编码
Cookie cookie = new Cookie("name", URLEncoder.encode("万金鑫","utf-8"));
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
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("万金鑫",1));
//获取Session的ID
String sessionId = session.getId();
//判断Session是不是新创建
if(session.isNew()){
resp.getWriter().write("session创建成功,ID:" + sessionId);
}else{
resp.getWriter().write("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);
}
}
获取Session:
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();
Person person = (Person)session.getAttribute("name");
System.out.println(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
手动注销Session:
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销Session
session.invalidate();
System.out.println("Session注销成功");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
会话自动过期:web.xml配置
<!--设置Session默认的失效时间-->
<session-config>
<!--15分钟后Session自动失效,以分钟为单位-->
<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原理
思路:JSP到底怎么执行的
代码层面没有任何问题
服务器内部工作
tomcat中有一个work目录
我电脑的地址
C:\Users\83825\AppData\Local\JetBrains\IntelliJIdea2021.3\tomcat\4a6b619f-5808-4a68-85fc-4a0591f81702\work\Catalina\localhost\javaweb_01_maven_war\org\apache\jsp
发现页面转变成了java程序
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet
JSP最终也会被转换成为一个Java类
JSP本质上就是一个Servlet
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(HttpServletRequest request, HttpServletResponse response)
1.判断请求
2.内置一些对象
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//响应
3.输出页面前增加的代码
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;
4.以上的这些对象我们可以在JSP页面中直接使用
在JSP页面中,
只要是JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为:
out.write("<html>\r\n");
这样的格式输出到前端
8.3、JS基础语法
任何语言都有自己的语法,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>");
%>
脚本片段的再实现
<%--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);
%>
<p>这是一个JSP文档</p>
<%
int y = 2;
out.println(y);
%>
<hr>
<%--在代码中嵌入HTML元素--%>
<%
for (int i = 0; i < 5; i++) {
%>
<h1>Hello,World<%=i%></h1>
<%
}
%>
JSP声明
<%!
static {
System.out.println("Loading Servlet!");
}
private int globalVar = 0;
public void kuang(){
System.out.println("进入了方法Kuang!");
}
%>
JSP声明:会被编译到JSP生成Java的类中!其他的,就会被生成到_jspService方法中!
在JSP,嵌入java代码中即可!
<%%>
<%=%>
<%!%>
<%--注释--%>
JSP的注释,不会在客户端显示,HTML就会!
8.4、JSP指令
<%@ page args.... %>
<%@ include file="" %>
<%--@include会将两个页面合二为一--%>
<%@ include file="common/header.jsp"%>
<h1>网页主体</h1>
<%@ include file="common/footer.jsp"%>
<hr>
<%--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:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据;
<%--
//scope:作用域
public void setAttribute(String name, Object attribute, int scope) {
switch(scope) {
case 1:
this.mPage.put(name, attribute);
break;
case 2:
this.mRequest.put(name, attribute);
break;
case 3:
this.mSession.put(name, attribute);
break;
case 4:
this.mApp.put(name, attribute);
break;
default:
throw new IllegalArgumentException("Bad scope " + scope);
}
}
public static final int PAGE_SCOPE = 1;
public static final int REQUEST_SCOPE = 2;
public static final int SESSION_SCOPE = 3;
public static final int APPLICATION_SCOPE = 4;
--%>
<%
//通过pageContext取出我们保存的值,通过序号的方式来
//从底层到高层 page->request->session->application
//JVM:双亲委派机制
//session.setAttribute("hello1","hello1");
pageContext.setAttribute("hello1","hello1",PageContext.SESSION_SCOPE);
%>
类比学习:双亲委派机制
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 />--%>
http://localhost:8080/javaweb_jsp_war_exploded/jsptag.jsp?name=kuang&age=12
<jsp:forward page="jsptag2.jsp">
<jsp:param name="name" value="kuangshen"></jsp:param>
<jsp:param name="age" value="12"></jsp:param>
</jsp:forward>
JSTL表达式
JSTL标签库的使用就是为了弥补HTML标签的不足;它自定义许多标签,可以供我们使用,标签的功能和Java代码一样!
格式化标签
SQL标签
XML标签
核心标签(掌握部分)
核心标签是最常用的 JSTL标签。引用核心标签库的语法如下:
<%@ 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" %>
<%--引入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="登录">
<%--判断提交的用户名是管理员,则登录成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="管理员欢迎您!"/>
</c:if>
<c:out value="${isAdmin}"/>
</form>
</body>
</html>
c:choose
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<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>=70}">
你的成绩为一般
</c:when>
<c:when test="${score>=60}">
你的成绩为及格
</c:when>
</c:choose>
</body>
</html>
c:forEach
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
ArrayList<String> peoples = new ArrayList<>();
peoples.add(0,"张三");
peoples.add(1,"李四");
peoples.add(2,"王五");
peoples.add(3,"赵六");
peoples.add(4,"田七");
request.setAttribute("list",peoples);
%>
<%--
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>
</body>
</html>
9、JavaBean
实体类
JavaBean有特定的写法:
必须要有一个无参构造
属性必须私有化
必须有对应的get/set方法
一般用来和数据库的字段做映射 ORM;
ORM:对象关系映射
表--->类
字段--->属性
行记录---->对象
people表
id | name | age | address |
1 | 秦疆1号 | 3 | 西安 |
2 | 秦疆2号 | 18 | 西安 |
3 | 秦疆3号 | 100 | 西安 |
//实体类 我们一般都是和数据库中的表结构一一对应!
public class People {
//last_id
//lastID
private int id;
private String name;
private int age;
private String address;
public People() {
}
public People(int id, String name, int age, String address) {
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "People{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
<%@ page import="com.kuang.pojo.People" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
// People people = new People();
// people.setId(1);
// people.setName("小狂神呀");
// people.setAge(3);
// people.setAddress("西安");
%>
<jsp:useBean id="people" class="com.kuang.pojo.People" scope="page"/>
<jsp:setProperty name="people" property="id" value="1"/>
<jsp:setProperty name="people" property="name" value="小狂神呀"/>
<jsp:setProperty name="people" property="age" value="3"/>
<jsp:setProperty name="people" property="address" value="西安"/>
id: <jsp:getProperty name="people" property="id"/>
姓名: <jsp:getProperty name="people" property="name"/>
年龄: <jsp:getProperty name="people" property="age"/>
地址: <jsp:getProperty name="people" property="address"/>
</body>
</html>
过滤器
文件上传
邮件发送
JDBC复习:如何使用JDBC,JDBCcrud,JDBC事务
10、MVC三层架构
什么是MVC:Model view Controller 模型、视图、控制器
让JSP,Servlet职责更清晰
10.1、早些年架构
用户直接访问控制层,控制层就可以 直接操作数据库;
servlet--CRUD--数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的
程序猿调用
|
JDBC
|
MYysql Oracle SqlServer ...
10.2、MVC三层架构
Model
业务处理:业务逻辑(Service)
数据持久层:CRUD(Dao)
View
展示数据
提供链接发起Servlet请求(a,form,img...)
Controller
接收用户的请请求:(req:请求参数、Session信息....)
交给业务层处理对应的代码
控制视图的跳转
登录--->接收用户的登录请求--->处理用户的请求(获取用户登录的参数,username,password)--->交给业务层处理登录业务(判断用户密码是否正确:Dao)--->Dao层查询用户名和密码是否正确-->数据库
11、Fileter(重点)
Filter:过滤器,用来过滤网站的数据;
处理中文乱码
登录验证
Filter开发步骤:
1.导包
2.编写过滤器
1.导包不要错
2.实现Filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter {
//初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现!
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
//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("CharacterEncodingFilter执行前....");
chain.doFilter(request, response);//让我们的请求继续走,如果不写,程序到这里就被拦截停止了!
System.out.println("CharacterEncodingFilter执行后....");
}
//销毁:web服务器关闭的时候,过滤就会销毁
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}
3.在web.xml中配置Filter
<?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">
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.kuang.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>CharacterEncodingFilter</filter-name>
<filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!--只要是/servlet的任何请求,都会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
</web-app>
12、监听器
实现一个监听器的接口;(有N种)
1.编写一个监听器
实现监听器的接口
//统计网站在线人数:统计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.手动销毁 se.getSession().invalidate();
2.自动销毁
*/
}
2.web.xml中注册监听器
<!--注册监听器-->
<listener>
<listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
3.看情况是否使用
13、过滤器、监听器常见应用
监听器:GUI编程中经常使用;
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame("中秋节快乐");//新建一个窗体
Panel panel = new Panel(null);//面板
frame.setLayout(null);//设置窗体的布局
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(0,0,255));//设置背景颜色
panel.setBounds(50,50,300,300);
panel.setBackground(new Color(0,255,0));//设置背景颜色
frame.add(panel);
frame.setVisible(true);
//监听时间,监听关闭事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
}
});
}
}
用户登录之后才能进入主页!用户注销后就不能进入主页了!
1.用户登录之后,向Session中放入用户的数据
2.进入主页的时候要判断用户是否已经登录;
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
/*
if (request.getSession().getAttribute(Constant.USER_SESSION))
*/
//ServletRequest HttpServletRequest
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
response.sendRedirect("/error.jsp");
}
chain.doFilter(request,response);
}
public void destroy() {
}
}
14、JDBC
什么是JDBC:java连接数据库
需要jar包的支持
java.sql
javax.sql
mysql-connecter-java...连接驱动(必须要导入)
实验环境搭建
CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
`email` VARCHAR(60),
`birthday` DATE
);
INSERT INTO users(id,`name`,`password`,`email`,`birthday`)
VALUES(1,'张三','123456','zs@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,`email`,`birthday`)
VALUES(2,'李四','123456','ls@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,`email`,`birthday`)
VALUES(3,'王五','123456','ww@qq.com','2000-01-01');
SELECT * FROM `users`;
导入数据库依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
IDEA连接数据库
JDBC固定步骤
1.加载驱动
2.连接数据库,代表数据库
3.向数据库发送SQL的对象Statement:CRUD
4.编写SQL(根据业务,不同的SQL)
5.执行SQL
6.关闭连接
public class TestJdbc {
public static void main(String[] args) throws SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//1.加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//3.向数据库发送SQL的对象Statement,prepareStatement:CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql = "select * from users;";
//5.执行SQL
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//6.关闭连接,释放资源(一定要做)先开后关
rs.close();
statement.close();
connection.close();
}
}
预编译SQL
public class Testjdbc2 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//3.编写SQL
String sql = "insert into users(id, name, password, email, birthday) values (?,?,?,?,?)";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,4);//给第1个占位符?的值赋值为1
preparedStatement.setString(2,"狂神说Java");//给第2个占位符?的值赋值为狂神说Java
preparedStatement.setString(3,"123456");//给第3个占位符?的值赋值为123456
preparedStatement.setString(4,"24736743@qq.com");//给第4个占位符?的值赋值为24736743@qq.com
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第5个占位符?的值赋值为new Date(new java.util.Date().getTime())
//5.执行SQL
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("插入成功");
}
//6.关闭连接,释放资源(一定要做)先开后关
preparedStatement.close();
connection.close();
}
}
事务
要么都成功,要么都失败!
ACID原则:保证数据的安全
开启事务
事务提交 commit()
事务回滚 rollback()
关闭事务
转账:
A:1000
B:1000
A(900) --100--> B(1100)
Junit单元测试
依赖
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
简单使用
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行
public class Testjdbc3 {
@Test
public void test(){
System.out.println("Hello");
}
}
public class Testjdbc3 {
@Test
public void test(){
System.out.println(1/0);
}
}
失败的时候是红色:
搭建一个环境
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(40),
`money` FLOAT
);
INSERT INTO account(`name`,money) VALUES('A',1000);
INSERT INTO account(`name`,money) VALUES('B',1000);
start transaction;#开启事务
update account set money = money-100 where name ='A';
update account set money = money+100 where name ='B';
commit;
rollback ;
public class Testjdbc3 {
@Test
public void test() throws SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection connection = null;
//1.加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url,username,password);
//3.通知数据库开启事务,false是开启
connection.setAutoCommit(false);
String sql = "update account set money = money-100 where name ='A';";
connection.prepareStatement(sql).executeUpdate();
//制造错误
// int test = 1/0;
String sql2 = "update account set money = money+100 where name ='B';";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上两条SQL都执行成功了,就提交事务!
System.out.println("提交成功");
} catch (ClassNotFoundException e) {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
e.printStackTrace();
} finally {
connection.close();
}
}
}
文件传输原理
创建空项目Empty Project需要设置:
创建new Module没有Web application解决方案
1.工具栏选中Help-Edit Custom Properties
加入这句代码
# custom IntelliJ IDEA properties
javaee.legacy.project.wizard=true
保存,重启idea。
1.准备工作
对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的。
一般采用Apache的开源工具common-fileupload这个文件上传组件。
common-fileupload是依赖于common-io这个包的,所以还需要下载这个包
我们下载最新的jar包:
https://mvnrepository.com/artifact/commons-io/commons-io
https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload
在JavaWeb项目中导入Jar包:
在项目中创建一个lib目录,把jar包放进去
并把lib文件夹添加到项目类库里面去
就可以看到源码了
或者在Project Structure Libraries里面直接添加
但一定要注意这个,提示是否把lib的东西打包出去
再看看项目发布Artifacts,发现确实没有导入的包
点击导入
导入成功
2、使用类介绍
【文件上传注意事项】
1、为保证服务器的安全,上传的文件应放在外界无法访问的目录下,如WEN-INF。
2、为防止同名文件产生覆盖现象,要为文件指定一个唯一的文件名。
3、要对上传文件的大小进行限制。
4、限制上传文件的类型,收到文件时,判断文件名十分合法。
【需要用到的类详解】
ServletFileUpload负责处理上传的文件数据,并将表单中的每个输入项封装成一个FileItem对象,在使用ServletFileUpload对象解析请求时需要DiskFileItemFactory对象。所以,我们需要在进行解析工作前构造好DiskFileItemFactory对象,通过ServletFileItem对象的构造方法或setFileItemFactory()设置ServletFileUpload对象的fileItemFactory属性。
FileItem类
<%--通过表单上传文件
get:上传文件大小有限制
post:上传文件大小没有限制
--%>
<form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
上传用户:<input type="text" name="username"><br/>
<p><input type="file" name = "file1"></p>
<p><input type="file" name = "file2"></p>
<p><input type="submit">|<input type="reset"></p>
</form>
get上传文件大小有限制,post上传文件大小没有限制,必须用post方法!
浏览器的表单类型为multipart/form-data的话,服务器想获取数据就要通过流
常用方法介绍
ServletFileUpload类
直接newServlet
public class FileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//判断上传的文件是普通表单还是文件表单
if(!ServletFileUpload.isMultipartContent(request)){
return;//终止方法运行,说明这是一个普通的表单,直接返回
}
//创建上传文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件;
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(uploadPath);
if(!uploadFile.exists()){
uploadFile.mkdir();//创建这个目录
}
//缓存,临时文件
//临时路径,假如文件超过了预期的大小,我们就把它放到一个临时文件中,过几天自动删除,或者提醒用户转存为永久文件
String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
File tmpfile = new File(tmpPath);
if(!tmpfile.exists()){
uploadFile.mkdir();//创建这个临时目录
}
try {
//1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制的;
DiskFileItemFactory factory = getDiskFileItemFactory(tmpfile);
//2.获取ServletFileUpLoad
ServletFileUpload upload = getServletFileLoad(factory);
//3.处理上传的文件
String msg = uploadParseRequest(upload,request,uploadPath);
request.setAttribute("msg",msg);
request.getRequestDispatcher("/info.jsp").forward(request,response);
} catch (FileUploadException e) {
e.printStackTrace();
}
}
public static DiskFileItemFactory getDiskFileItemFactory(File tmpfile){
//处理上传的文件,一般都需要通过流来获取,我们可以使用request.getInputStream(),原生态的文件上传流获取,十分麻烦
//但是我们都建议使用Apache的文件上传组件来实现,common-fileupload,它需要依赖于commons-io组件;
DiskFileItemFactory factory = new DiskFileItemFactory();
//通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将它放到临时文件中;
factory.setSizeThreshold(1024*1024);//缓存区大小为1M
factory.setRepository(tmpfile);//临时目录的保存目录,需要一个File
return factory;
}
public static ServletFileUpload getServletFileLoad(DiskFileItemFactory factory){
ServletFileUpload upload = new ServletFileUpload(factory);
//可忽略的设置
//监听文件上传进度
upload.setProgressListener(new ProgressListener() {
@Override
//pBytesRead:已经读取到的文件大小
//pContentLength:文件大小
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小:" + pContentLength + "已上传:" + pBytesRead);
}
});
//设置编码,处理乱码问题
upload.setHeaderEncoding("UTF-8");
//设置单个文件的最大值
upload.setFileSizeMax(1024*1024*10);
//设置总共能够上传文件的大小
//1024 = 1kb * 1024= 1M * 10 = 10M
upload.setSizeMax(1024*1024*10);
return upload;
}
public static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest request,String uploadPath) throws FileUploadException, IOException {
String msg = null;
//把前端请求解析,封装成一个FileName对象,需要从ServletFileUpLoad对象中获取
List<FileItem> fileItems = upload.parseRequest(request);
//fileItem 每一个表单对象
for (FileItem fileItem : fileItems) {
if(fileItem.isFormField()){
//判断上传的文件是普通的表单还是带文件的表单
//getFieldName指的是前端表单控件的name
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");//处理乱码
System.out.println(name+":"+value);
}else{//判断它是上传的文件
//====================处理文件=========================//
//拿到文件的名字
String uploadFileName = fileItem.getName();
//可能存在文件名不合法的情况
if(uploadFileName.trim().equals("")||uploadFileName == null){
continue;
}
//获得上传的文件名/images/girl/paojie.png
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
//获得文件的后缀名
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
//如果文件后缀名fileExtName不是我们所需要的就直接return,不处理,告诉用户文件类型不对。
//可以使用UUID(唯一识别的通用码),保证文件名唯一;
//UUID.randomUUID(),随机生成一个唯一识别的通用码;
//网络传输中的东西,都需要序列化
//POJO,实体类,如果想要在多个电脑上运行传输,需要把对象都序列化了
//JNI = Java Native Interface java本地化接口
//implements Serializable:标记接口,JVM--->Java栈 本地方法栈 native-->C++
String uuidPath = UUID.randomUUID().toString();
//====================存放地址=========================//
//存到哪?upLoadPath
//文件真实存在的路径 realPath
String realPath = uploadPath+"/"+uuidPath;
//给每个文件创建一个对应的文件夹
File realPathFile = new File(realPath);
if(!realPathFile.exists()){
realPathFile.mkdir();
}
//====================文件传输=========================//
//获得文件上传的流
InputStream inputStream = fileItem.getInputStream();
//创建一个文件输出流
//realPath = 真实的文件夹;
//差了一个文件:加上输出文件的名字+"/"+uuidFileName
FileOutputStream fos = new FileOutputStream(realPath+"/"+fileName);
//创建一个缓冲区
byte[] buffer = new byte[1024*1024];
//判断是否读取完毕
int len = 0;
//如果大于0说明还存在数据;
while((len = inputStream.read(buffer))>0){
fos.write(buffer,0,len);
}
System.out.println("上传的文件名" + fileName);
System.out.println("文件信息:" + "[文件名:" + fileName + "文件类型:" + fileExtName + "]");
//关闭流
fos.close();
inputStream.close();
msg = "文件上传成功!";
fileItem.delete();//上传文件成功,清除临时文件
}
}
return msg;
}
}
邮件发送原理及实现
要在网络上实现邮件功能,必须要有专门的邮件服务器
传输协议
SMTP协议
发送邮件:
我们通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)
POP3协议
接收邮件:
我们通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。
(1)张三通过smtp协议连接到Smtp服务器,然后发送一封邮件给网易的邮件服务器
(2)网易分析发现需要去QQ的邮件服务器,通过smtp协议将邮件转投给QQ的Smtp服务器
(3)QQ将接收到的邮件存储在lisi@qq.com这个邮件账号的空间中
(4)李四通过Pop3协议连接到Pop3服务器收取邮件
(5)从lisi@qq.com这个邮件账号的空间中取出邮件
(6)Pop3服务器将取出来的邮件送到李四手中
注意
有可能你收件人地址,发件人地址等信息都正确了,控制台也打印了正确的信息,但是在收件箱就是收不到信息。
这是因为可能收件箱服务器拒收了你发的邮件(比如认为你的邮件是广告),这时候可能在垃圾箱里能找到,可能找不到。
解决办法是重复的邮件内容不要多次发送,或者更换收件箱试试
Java发送邮件
概述
我们将用代码完成邮件的发送,这在实际项目中应用非常广泛
使用Java发送 E-mail 十分简单,但是首先你应该准备JavaMail API和Java Activation Framework 。(发送邮件的支持包)
得到两个jar包:
mail.jar
activation.jar
JavaMail 是sun公司(现以被甲骨文收购)为方便Java开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发包,
它支持一些常用的邮件协议,如前面所讲的SMTP,POP3,IMAP,还有MIME(附件和图片)等。
我们在使用JavaMail API 编写邮件时,无须考虑邮件的底层实现细节,只要调用JavaMail 开发包中相应的API类就可以了。
我们可以先尝试发送一封简单的邮件,确保电脑可以连接网络。
1.创建包含邮件服务器的网络连接信息的Session对象。
2.创建代表邮件内容的Message对象
3.创建Transport对象,连接服务器,发送Message,关闭连接
主要有四个核心类,我们在编写程序时,记住这四个核心类,就很容易编写出Java邮件处理程序。
Session:定义整个程序,所有的信息。比如:smtp.qq.com、邮箱账号、密码
Transport:发送邮件
Message:信息的内容。对应:收件人、主题、正文
导包
权限
QQ邮箱中获取对应的权限
QQ邮箱需要安全验证,我们需要获取他对应的权限;
QQ邮箱–>邮箱设置–>账户
点击开启,获得16位的授权码
简单的文本文件
//发送一封简单的邮件
public class MailTest1 {
public static void main(String[] args) throws Exception {
//Properties中 设置属性
Properties prop=new Properties();
prop.setProperty("mail.host","smtp.qq.com");///设置QQ邮件服务器
prop.setProperty("mail.transport.protocol","smtp");///邮件发送协议
prop.setProperty("mail.smtp.auth","true");//需要验证用户密码
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,原因:大厂。其他邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");//使用安全的连接为true
prop.put("mail.smtp.ssl.socketFactory",sf);//socket工厂,使用自己的socket工厂
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用程序所需要的环境信息的session对象
//QQ才有!其他邮箱就不用
Session session= Session.getDefaultInstance(prop, new Authenticator() {//获取默认的实例
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮箱、授权码
return new PasswordAuthentication("838251031@qq.com","****************");
}
});
//开启session的debug模式,这样可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","838251031@qq.com","fywuuzerbcfabegi");
//4.创建邮件:写邮件
//注意需要传递Session,要知道信息从哪里来;
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("838251031@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress("838251031@qq.com"));
//邮件的标题 只包含文本的简单邮件
message.setSubject("发送的标题");
//邮件的文本内容
message.setContent("<h1 style=\"color: red\">你好</h1>","text/html;charset=UTF-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接,一切网络都需要关闭
ts.close();
}
}
带图片和附件的邮件
两个类
先认识两个类一个名词:
MIME(多用途互联网邮件扩展类型)
MimeBodyPart类 (内容的主体)
javax.mail.internet.MimeBodyPart类
表示的是一个MIME消息,它和MimeMessage类一样都是从Part接口继承过来。
MimeMultipart类 (内容的封装)
javax.mail.internet.MimeMultipart是抽象类
Multipart的实现子类,它用来组合多个MIME消息。
一个MimeMultipart对象可以包含多个代表MIME消息的MimeBodyPart对象
流程图
在MimeBodyPart中有三个属性
mixed:附件
related:内嵌资源
alternative:超文本正文
代码实现
public class MailTest2 {
public static void main(String[] args) throws Exception {
//Properties中 设置属性
Properties prop=new Properties();
prop.setProperty("mail.host","smtp.qq.com");///设置QQ邮件服务器
prop.setProperty("mail.transport.protocol","smtp");///邮件发送协议
prop.setProperty("mail.smtp.auth","true");//需要验证用户密码
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,原因:大厂。其他邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");//使用安全的连接为true
prop.put("mail.smtp.ssl.socketFactory",sf);//socket工厂,使用自己的socket工厂
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用程序所需要的环境信息的session对象
//QQ才有!其他邮箱就不用
Session session= Session.getDefaultInstance(prop, new Authenticator() {//获取默认的实例
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮箱、授权码
return new PasswordAuthentication("838251031@qq.com","fywuuzerbcfabegi");
}
});
//开启session的debug模式,这样可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","838251031@qq.com","fywuuzerbcfabegi");
//4.创建邮件:写邮件
//注意需要传递Session,要知道信息从哪里来;
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("838251031@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress("838251031@qq.com"));
//邮件的标题 只包含文本的简单邮件
message.setSubject("发送的标题");
//============================================================================================
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
//图片需要经过数据化的处理 DataHandler:数据处理 FileDataSource:加载文件的资源
DataHandler dh = new DataHandler(new FileDataSource("C:\\MyDownLoad\\JavaLearn\\filefunction\\mail-java\\src\\com\\1.webp"));
//在part中放入这个处理的图片数据
image.setDataHandler(dh);
//给这个part设置一个ID名字
image.setContentID("bz.jpg");
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一张正文<img src='cid:bz.jpg'>","text/html;charset=UTF-8");
//准备附件数据
MimeBodyPart body1= new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("C:\\MyDownLoad\\JavaLearn\\filefunction\\mail-java\\src\\com\\HelloWorld.txt")));
body1.setFileName("1.txt");
//描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(body1);
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("mixed");
//设置到消息中,保存修改
message.setContent(mm);
message.saveChanges();
//============================================================================================
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接,一切网络都需要关闭
ts.close();
}
}
JavaWeb发送邮件
现在很多的网站都提供有用户注册功能, 通常我们注册成功之后就会收到一封来自注册网站的邮件。邮件里面的内容可能包含了我们的注册的用户名和密码以及一个激活账户的超链接等信息。今天我们也来实现一个这样的功能,用户注册成功之后,就将用户的注册信息以Email的形式发送到用户的注册邮箱当中,实现发送邮件功能就得借助于JavaMail了。
思路:把收件人地址改成从前端接收过来的参数
代码实现:
1.先搭建框架
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/RegisterServlet" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
邮箱:<input type="text" name="email"><br/>
<input type="submit" value="注册">
</form>
</body>
</html>
2.实体类
public class User {
private String username;
private String password;
private String email;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
//方便调试
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
3.工具类
//网站3秒原则:用户体验
//多线程实现用户体验!(异步处理)
public class Sendemail extends Thread{
//用于给用户发送邮件的邮箱
private String from = "838251031@qq.com" ;
//邮箱的用户名
private String username = " 838251031@qq.com" ;
//邮箱的密码
private String password = "fywuuzerbcfabegi";
//发送邮件的服务器地址
private String host ="smtp.qq.com" ;
//导入一个类
private User user;
public Sendemail(User user) {
this.user = user;
}
@Override
public void run() {
try {
Properties prop = new Properties();
prop.setProperty("mail.host",host);///设置QQ邮件服务器
prop.setProperty("mail.transport.protocol","smtp");///邮件发送协议
prop.setProperty("mail.smtp.auth","true");//需要验证用户密码
//QQ邮箱需要设置SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
//使用javaMail发送邮件的5个步骤
//1.创建定义整个应用程序所需要的环境信息的session对象
Session session= Session.getDefaultInstance(prop,
new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
//开启session的debug模式,这样可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect(host,username,password);
//4.创建邮件:写文件
//注意需要传递session
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(from));
//指明邮件的收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));//从前端接收的
//邮件标题
message.setSubject("注册通知");
//邮件的文本内容
String info = "恭喜你("+user.getUsername()+")成功注册!"+"密码:"+user.getPassword();
message.setContent(info,"text/html;charset=UTF-8");
message.saveChanges();//保存更改
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
}catch (Exception e){
System.out.println(e);
}
}
}
4.Servlet类
//脚手架
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收用户请求,封装成对象
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username,password,email);
//用户注册成功之后,给用户发送一封邮件
//我们使用线程来专门发送邮件,防止出现耗时,和网站注册人数过多的情况;
Sendemail send = new Sendemail(user);
//如果是send.run(),就要等到执行发送完才会跳转页面,用户体验差
send.start();
//注册用户
req.setAttribute("message","注册成功,我们已经发了一封要了注册信息的电子邮件,请查收!如网络不稳定,请稍等");
req.getRequestDispatcher("info.jsp").forward(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
5.提示页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>网站温馨提示</h1>
${message}
</body>
</html>
通过Spring项目进行邮件发送
配置 application.properties文件
spring.mail.username=838251031@qq.com
spring.mail.password=fywuuzerbcfabegi
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
@SpringBootTest
class DemoApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
//简单邮件
@Test
void contextLoads() {
//发送邮件
//收件人
//内容
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("Spring邮件发送");
message.setText("Hello");
message.setFrom("838251031@qq.com");
message.setTo("838251031@qq.com");
mailSender.send(message);
}
//带附件的邮件
@Test
public void test2() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("Spring邮件发送");
helper.setText("<h1>Hello</h1>",true);//是否是html
//附件
helper.addAttachment("1.txt",new File("C:\\MyDownLoad\\JavaLearn\\demo\\src\\HelloWorld.txt"));
helper.addAttachment("2.jpg",new File("C:\\MyDownLoad\\JavaLearn\\demo\\src\\test.jpg"));
helper.setFrom("838251031@qq.com");
helper.setTo("838251031@qq.com");
mailSender.send(mimeMessage);
}
}