https://tomcat.apache.org/download-90.cgi
解压后就可以直接使用
解压后文件目录
bin | 启动关闭的脚本 |
---|---|
conf | 配置文件 |
lib | 依赖的jar包 |
logs | 日志文件 |
temp | 缓存 |
webapps | 存放网站文件的 |
works | 工作目录 |
启动和关闭
- bin目录的start.bat打开
- bin目录的shutdown.bat关闭
- 或者在命令行(安装根目录)输入命令catalina run
首先java环境变量必须配置完整
服务相关的配置server.xml
可配置的端口号
- 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">
将一个网站放在,放到服务器(Tomcat)中指定的web应用的文件夹(webapps)中,就可以访问
网站应该有的结构
--Webapps Tomcat服务器的web目录
-Root
-zj
-WEB-INF
-classes java程序
-lib jar包
-web.xml 网页配置文件
-index.html 默认首页
-static
-css
-style.css
-js
-img
修改/conf目录下logging.properties文件,设置java.util.logging.ConsoleHandler.encoding 为 GBK(windows默认编码),即:java.util.logging.ConsoleHandler.encoding = GBK
http(超文本传输协议),是一个简单的请求-响应协议,他通常运行在tcp之上
- http/1.0:客户端和服务器连接后,只能获得一个web资源,断开连接
- http/1.1:客户端和服务器连接后,可以获得多个资源
请求行
Request URL: https://www.baidu.com/
Request Method: GET
Status Code: 200 OK
Remote Address: 36.152.44.96:443
请求头:
Accept: text/html 告诉浏览器他所支持的类型
Accept-Encoding: gzip, deflate, br 告诉浏览器他所支持的编码格式
Accept-Language: zh-CN,zh;q=0.9 告诉浏览器他的语言环境
Connection: keep-alive 告诉浏览器,请求完成是断开还是保持连接
响应头:
Cache-Control: private 缓存控制
Connection: keep-alive 连接保持
Content-Encoding: gzip 编码
Content-Type: text/html 类型
Refresh: 告诉浏览器多久刷新一次
Location 让网页重新定位
响应状态码
为什么要学习Maven
我们目前用来方便导入jar包
他的高级之处在于,他会为你导入这个jar包所依赖的其他jar包
Maven的核心思想:约定大于配置
- 有约束,不要去违反
Maven会规定好去如何编写我们的java代码,必须按照这个规范来
根据自己的idea版本下载maven版本,查找maven发布时间在IDEA版本之前的
历史版本时间查询:https://maven.apache.org/docs/history.html
指定下载:https://archive.apache.org/dist/maven/maven-3/
我的idea版本2021.1.3
这里我选择:apache-maven-3.6.3-bin.zip文件
不兼容可能会导致非预期的异常(比如,使用3.8.6时遇到的junit依赖无法下载,maven窗口只有Lifecycle目录)
解压放在适当的位置
M2_HOME:D:\Environment\apache-maven-3.6.3-bin\apache-maven-3.6.3\bin
MAVEN_HOME:D:\Environment\apache-maven-3.6.3-bin\apache-maven-3.6.3
path中增加:%MAVEN_HOME%\bin
cmd中mvn-version测试是否成功
M2_HOME其他软件可能会用
主要为了加快访问速度
修改conf—>settings.xml文件,增加镜像
<mirror>
<id>alimavenid>
<mirrorOf>centralmirrorOf>
<name>aliyun mavenname>
<url>http://maven.aliyun.com/nexus/content/repositories/central/url>
mirror>
settings.xml中增加如下字段
<localRepository>D:\Environment\apache-maven-3.8.6-bin\apache-maven-3.8.6\maven-repolocalRepository>
//目录结构
src---
main---
webapp--- 放置网站源代码的
WEB-INF---
WEB.XML 网站配置文件
index.jsp 网站首页或其他网页
选择模板为maven-archetype-webapp
groupid :为组id,一般为公司域名倒着写
artifactid:和工程名一样,javaweb-01-maven(建议写法)
maven home path:选择maven的安装路径
user settings file:选择安装目录里的setting.xml文件地址
Local repository:选择定义好的maven仓库地址
必须要设置如下内容(在设置中搜索maven)
- maven home path
- User settings file
- Local repository
可以看出maven的标准目录结构
//目录结构
src---
main---
java-- 放置java源代码的
resources-- 放置一些配置文件和资源
test---
java-- 测试使用
但是没有webapp文件夹,他旨在web应用下才有
把上面两个目录结构结合结合起来
在模板创建的工程中,增加两个目录java和resources
右键目录文件夹,选择make directory as,里面标记一下文件夹颜色
//目录结构
src---
main---
java-- 放置java源代码的
resources-- 放置一些配置文件和资源
webapp--- 放置网站源代码的
WEB-INF---
WEB.XML 网站配置文件
index.jsp 网站首页或其他网页
test---
java-- 测试使用
1、run菜单------点击Edit Configuration或者上方工具栏中add Configuration,打开run/debug Configurations窗口
2、点击+号添加一个Tomcat
- name:随便写一个名字
- Application server:选择tomcat程序所在的主目录
- http port:8080
3、这是会警告:No artifacts marked for deployment
- 处理,还是该窗口,选择选项卡deployment(部署)
- +号添加一个artifact
- 选择---工程名子:war---这一项
4、鼠标往下滚动,会有一个Application context 的选项
5、Tomcat的output窗口汉字乱码解决
菜单help------Edit custom VM Options----------里面添加代码-Dfile.encoding=UTF-8
pom.xml时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.0modelVersion>
<groupId>com.dabangroupId>
<artifactId>javaweb-01-mavenartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>javaweb-01-maven Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
dependencies>
<build>
<finalName>javaweb-01-mavenfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
pom的build中增加如下代码,使得非约定文件夹中的资源可以正常导出
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
最好使用tomcat安装包里的webapps中的root里的web.xml内容
<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">
<display-name>Welcome to Tomcatdisplay-name>
<description>
Welcome to Tomcat
description>
web-app>
Servlet是一门动态web的开发技术
servlet是一个接口,想要开发servlet程序,只需要两点
- 编写一个类,实现servlet接口
- 把开发好的java类部署到web服务器中
1、构建一个普通的maven项目(不带模板),删掉里面的src目录
是他只作为一个父maven,我们的学习都在这个项目里面建立moudel,这空工程就是maven主工程,将所有的依赖都导在父工程中,子工程就可以直接使用
2、关于maven父子工程的理解
<modules>
<module>servlet-01module>
modules>
<parent>
<artifactId>javaweb-02-servletartifactId>
<groupId>com.dabangroupId>
<version>1.0-SNAPSHOTversion>
parent>
3、把子项目的web.xml换成tomcat安装包里的webapps中的root里的web.xml内容
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
web-app>
4、main目录下面补全java目录和resources目录,并标记
5、编写一个Servlet程序
java下创建一个包,包下创建一个普通类,并继承HttpServlet
package com.daban.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.println("hello,servlet!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6、编写servlet的映射
为什么要映射:我们写的是java程序,但要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中住注册我们写的servlet,还需要给他一个浏览器需要访问的路径
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.daban.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hurl-pattern>
servlet-mapping>
7、配置Tomcat
参考3.7
工作流程
Web Client 向Servlet容器(Tomcat)发出Http请求
Servlet容器接收Web Client的请求
Servlet容器创建一个HttpRequest对象,将Web Client请求的信息封装到这个对象中。
Servlet容器创建一个HttpResponse对象
Servlet容器调用HttpServlet对象的service方法,把HttpRequest对象与HttpResponse对象作为参数传给 HttpServlet 对象。
HttpServlet调用HttpRequest对象的有关方法,获取Http请求信息。
HttpServlet调用HttpResponse对象的有关方法,生成响应数据。
Servlet容器把HttpServlet的响应结果传给Web Client。
处理请求流程
用户点击一个链接,指向了一个servlet而不是一个静态页面。
容器“看出”这个请求是一个Servlet,所以它创建了两个对象HttpServletRequest和HttpServletResponse。
容器根据请求中的URL找到正确的Servlet,为这个请求创建或分配一个线程,并把请求和响应对象传递给这个Servlet线程。
容器调用Servlet的service()方法。根据请求的不同类型,service()方法会调用doGet()或doPost()方法。这里假设调用doGet()方法。
doGet()方法生成动态页面,并把这个页面“塞到”响应对象里,需要注意的是,容器还有响应对象的一个引用!
线程结束,容器把响应对象转换为一个HTTP响应,并把它发回给客户,然后删除请求和响应对象。
一个servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hurl-pattern>
servlet-mapping>
一个servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hurl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/h2url-pattern>
servlet-mapping>
一个servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/h/*url-pattern>
servlet-mapping>
默认请求路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
指定一些后缀或者前缀
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/b.zhjurl-pattern>
servlet-mapping>
web容器在启动时,会给每一个web程序创建一个ServletContext对象
在一个servlet中保存数据,在另一个servlet中拿到数据
//保存数据
package com.daban.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
ServletContext servletContext = this.getServletContext();
String username = "zhj";
servletContext.setAttribute("username",username);
writer.println("我是动态网页");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
//获得数据
package com.daban.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class GetContext extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String username =(String)servletContext.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
writer.println(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.daban.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
<servlet>
<servlet-name>hello1servlet-name>
<servlet-class>com.daban.servlet.GetContextservlet-class>
servlet>
<servlet-mapping>
<servlet-name>hello1servlet-name>
<url-pattern>/hello1url-pattern>
servlet-mapping>
package com.daban.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class GetGP extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
//用这个方法去获取web.xml中的标签的内容
String username =servletContext.getInitParameter("url");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
writer.println(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<context-param>
<param-name>urlparam-name>
<param-value>jdbc:mysql:localhost:3306param-value>
context-param>
请求转发url显示不变,但网页返回的内容确实转发的地址返回的内容
package com.daban.servlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ReqDispatcher extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
//设置请求转发的地址
RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/gp");
//实现请求转发
requestDispatcher.forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>rdservlet-name>
<servlet-class>com.daban.servlet.ReqDispatcherservlet-class>
servlet>
<servlet-mapping>
<servlet-name>rdservlet-name>
<url-pattern>/rdurl-pattern>
servlet-mapping>
在resources目录下创建的文件可以正常部署到目标文件,在其他位置创建的需要在该模块的pom中添加
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
读取资源文件
package com.daban.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ServletDemo05 extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//这地址为部署后文件的相对地址
InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String user = properties.getProperty("username");
String pwd = properties.getProperty("password");
resp.getWriter().println(user);
resp.getWriter().println(pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>ppservlet-name>
<servlet-class>com.daban.servlet.ServletDemo05servlet-class>
servlet>
<servlet-mapping>
<servlet-name>ppservlet-name>
<url-pattern>/ppurl-pattern>
servlet-mapping>
username = zhj
password = 123456
web服务器接收到客户端的http请求,针对这个请求,分别创建两个对象HttpServletResponse(响应)和HttpServletRequest(请求)
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
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);
中文文件名不显示处理filename = URLEncoder.encode(filename,“utf-8”);
package com.daban.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setContentType("pdf/html");
//要获取下载文件的路径
String realPath = this.getServletContext().getRealPath("WEB-INF/classes/123.pdf");
System.out.println(realPath);
//下载文件名是什么
String filename = realPath.substring(realPath.lastIndexOf('\\') + 1);
//让浏览器能够支持我们需要下载的东西
resp.setHeader("Content-Disposition","attachment;filename="+filename);
//获取文件下载的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
//创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//获取OutputStream对象
ServletOutputStream outputStream = resp.getOutputStream();
//将FileOutputStream流写入到buffer缓冲区
//使用OutputStream将缓冲区中的数据输出到客户端
while ((len = fileInputStream.read(buffer))>0){
outputStream.write(buffer,0,len);
}
fileInputStream.close();
outputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.daban.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器自动刷新
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(300,100,BufferedImage.TYPE_INT_RGB);
//得到图形
Graphics graphics = image.getGraphics();//类似笔
graphics.setColor(Color.BLUE);
graphics.fillRect(0,0,300,100);
graphics.setColor(Color.white);
graphics.setFont(new Font(null,Font.BOLD,100));
graphics.drawString(makeNum(),0,80);//左下角为基准的坐标
//告诉浏览器这个请求使用图片方式打开
resp.setContentType("image/jpg");
//不让浏览器缓存
resp.addDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
public String makeNum(){
Random random = new Random();
String num = random.nextInt(100000)+"";
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < 5-num.length(); i++) {
stringBuffer.append("0");
}
// System.out.println(stringBuffer+num);
return stringBuffer+num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
一个web程序收到客户端的请求,他会通知客户端去访问另一个web程序的过程叫重定向
resp.sendRedirect("/d/image");//注意前面的斜杠不能少
<%@ page pageEncoding="UTF-8" %>
Hello World!
<%--此处的路径也可以写死,"/d/login"--%>
package com.daban.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入请求");
ServletContext context = this.getServletContext();
String username = req.getParameter("username");
context.setAttribute("username",username);
String password = req.getParameter("password");
context.setAttribute("password",password);
if(username.equals("zhj") && password.equals("123456")){
resp.sendRedirect("/d/success");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Success.java
package com.daban.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Success extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
ServletContext context = this.getServletContext();
String username =(String)context.getAttribute("username");
String password =(String)context.getAttribute("password");
resp.getWriter().print("登录成功
");
resp.getWriter().print("用户名:"+username);
resp.getWriter().print("密码:"+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
HttpServletRequest代表客户端的请求,用户通过HTTP协议访问服务器,请求中的所有信息会被封装到
HttpServletRequest中,通过这个HttpServletRequest的方法,获取客户端的所有信息
package com.daban.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//后台打印输出是乱码
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobby");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
//不使用ServletContext的请求转发,而使用req的请求转发
req.getRequestDispatcher("/success.jsp").forward(req,resp);
//使用servletcontext请求转发时,注意路径和重定向的区别
// ServletContext servletContext = this.getServletContext();
// servletContext.getRequestDispatcher("/success.jsp").forward(req,resp);
// //使用重定向时,注意路径和请求转发的区别
// resp.sendRedirect("/request/success.jsp");
}
}
resq.setCharacterEncoding("utf-8");
req.setCharacterEncoding("utf-8");
URLEncoder.encode("字符串","utf-8");
URLDecoder.decode("字符串","utf-8");
从请求中拿到cookie信息
服务器响应给客户端cookie
package com.daban.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
//服务器从客户端端获取cookie
Cookie[] cookies = req.getCookies();
boolean isFirst = true;
//有些浏览器一开始没有cookie,所以要判断
if(cookies!=null){
for (Cookie cookie : cookies) {
if(cookie.getName().equals("lastLoginTime")){
String val = cookie.getValue();//获得的值为字符串
Long valLong = Long.parseLong(val);//将字符串变成Long
Date date = new Date(valLong);//将Long型的时间戳变成时间对象
resp.getWriter().print("你上次登录的时间为:"+date.toLocaleString());
isFirst = false;
break;
}
}
if(isFirst){
resp.getWriter().print("您第一次登录");
}
}else {
resp.getWriter().print("您第一次登录");
}
//服务器给客户端响应一个cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
cookie.setMaxAge(30);//过期时间为秒
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
什么时session
HttpSession session = req.getSession();//获取一个sesison对象
session.setAttribute("name","zhj");//设置session中的值为字符串
int[] array = {1,2,3};
session.setAttribute("array",array);//设置session中的值为对象(数组)
int[] array =(int[]) session.getAttribute("array");//另一个servlet可以获取session中的值
session.removeAttribute("array");//移除session相应数据
session.invalidate();//注销session,此时sessionid会变化
web.xml中设置session,也可以设置cookie
<session-config>
<session-timeout>10session-timeout>
session-config>
Java Server Pages:Java服务器端页面。用于动态web技术
最大特点:
他会把jsp转换为一个java类(C:\Users\ZHJ\AppData\Local\JetBrains\IntelliJIdea2021.1\tomcat\6e4aabb0-948b-413a-9c8d-497d54921c6f\work\Catalina\localhost\c\org\apache\jsp)
浏览器向服务器发送请求,不管访问什么资源,其实是访问servlet
index_jsp extends HttpJspBase extends HttpServlet,该类实质上是继承了HttpServlet
转换的java类其实是一个servlet
//源码
public void _jspInit() {}
public void _jspDestroy() {}
public void _jspService(HttpServletRequest request, HttpServletResponse response){
// 判断请求类型
// .....
// 内置一些对象,这些对象可以在jsp中直接使用
final javax.servlet.jsp.PageContext pageContext;// 页面上下文
javax.servlet.http.HttpSession session = null; // Session
final javax.servlet.ServletContext application; // 可以存放数据的ServletContext
final javax.servlet.ServletConfig config; // config
javax.servlet.jsp.JspWriter out = null; // 输出对象
final java.lang.Object page = this; // 当前页
//
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;
转换规则:
依赖
<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.3version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jsp.jstlgroupId>
<artifactId>jstl-apiartifactId>
<version>1.2version>
<scope>providedscope>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
<scope>providedscope>
dependency>
dependencies>
建立maven项目时,使用另种方式建立。先建立普通maven项目(非模板创建),然后右键项目,选择add framework support,增加一个框架,选择web框架。这样创立的项目web文件夹在src文件夹外。
jsp表达式
<%--jsp表达式
用来将程序输出到客户端--%>
<%=new java.util.Date() %>
两种取值的区别
<%--找不到变量会不显示--%>
${name5}
<%--找不到变量会显示null--%>
<%=name5%>
jsp脚本片段
<%
int sum = 0;
for (int i = 0; i < 10; i++) {
sum+=i;
}
out.print("sum="+sum+"
");//一般输出
%>
<%="sum="+sum+"
" %>//表达式输出
jsp的for循环
<%
for (int i = 0; i < 10; i++) {
%>
我是h1标签 <%=i%>
<%
}
%>
jsp声明
转换后的类的全局变量定义
<%!这里面定义的内容将出现在_jspService函数的外部%>
jsp的注释不会在客户端显示,html中的注释会在客户端显示
页面发生错误,显示指定的网页
<%@page errorPage="error/500.jsp" %>
定制错误页面在web.xml中配置
<error-page>
<error-code>404error-code>
<location>/error/404.jsplocation>
error-page>
<error-page>
<error-code>500error-code>
<location>/error/500.jsplocation>
error-page>
三个指令
<%@ page ...... %>//页面相关
<%@ include file=""%>//包含公共的页面文件,header和footer等
<%--这样方式包含页面,是把页面用标签全部拼接,生成一个页面--%>
<%@ include file="common/header.jsp"%>
项目主题
<%@ include file="common/footer.jsp"%>
<%--这样方式包含页面,是把页面真正的包含,本质是三个页面--%>
项目主题
四种的作用域不一样
pageContext.setAttribute("name1","山鸡1");//保存的数据只在一个页面中有效
request.setAttribute("name2","山鸡2");//保存的数据只在一次请求中有效,请求转发携带数据
session.setAttribute("name3","山鸡3");//保存的数据只在一次会话中有效,从打开浏览器到关闭
application.setAttribute("name4","山鸡4");//保存的数据只在一个服务器中有效,从打开服务器到关闭
EL表达式 ${ }
jsp标签
JSTL表达式
jstl标签库的使用就是为了弥补html的不足,他自定义了许多标签,标签的功能和java代码一样
JSTL标签库的使用步骤
<%
request.setAttribute("name","g");
request.setAttribute("name1","g1");
ArrayList list = new ArrayList<>();
list.add("老王1");
list.add("老王2");
list.add("老王3");
list.add("老王4");
request.setAttribute("mylist",list);
//在使用${}时,java中定义的变量无法识别,需要setAttribute
%>
实体类
特定的写法:
一般用来和数据库的字段做映射
表—>类
字段–>属性
行记录–>对象
<%--相当于Person person = new Person()--%>
<%--相当于person.setXXX();--%>
<%--相当于person.getXXX();--%>
什么是MVC:Modle view Controller
过滤器用来过滤网站的数据
Filter开发步骤
//过滤器写法
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//过滤代码.....
//让请求继续执行,不写的话,程序会在此处停止
filterChain.doFilter(servletRequest,servletResponse);
}
<filter>
<filter-name>flfilter-name>
<filter-class>com.daban.filter.CharacterEncodingFilterfilter-class>
filter>
<filter-mapping>
<filter-name>flfilter-name>
<url-pattern>/servlet/*url-pattern>//servlet路径下的所有请求都过滤
filter-mapping>
1、实现监听器的接口
package com.daban;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class listener implements HttpSessionListener {
//一但创建一个session就会触发该事件
public void sessionCreated(HttpSessionEvent se) {
ServletContext servletContext = se.getSession().getServletContext();
System.out.println("session创建");
Integer count =(Integer) servletContext.getAttribute("count");
if(count==null){
count = 1;
}else{
count++;
}
servletContext.setAttribute("count",count);
}
/**注销session方式:
*
* 1
*
*
* 或者se.getSession().invalidate();
*/
//一但注销一个session就会触发该事件
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext servletContext = se.getSession().getServletContext();
System.out.println("session注销了");
Integer count =(Integer) servletContext.getAttribute("count");
if(count==null){
count = 0;
}else{
count--;
}
servletContext.setAttribute("count",count);
}
}
2、web.xml中注册监听器
<listener>
<listener-class>com.daban.listenerlistener-class>
listener>
在GUI编程中使用较多
package com.daban;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
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(255,0,0));
frame.add(panel);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
设计一个登录界面,用户登录才能进入界面,注销则无法进入
两种实现
if(request.getSession().getAttribute("USER_SESSION")==null){
response.sendRedirect("/login.jsp");//重定向新地址
pageContext.forward("/login.jsp");//地址不会变
过滤器中实现
login.java
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("username");
if(name.equals("admin")){
req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
}else {
resp.sendRedirect("/sys/error.jsp");
}
}
logout.java
Object user_session = req.getSession().getAttribute("USER_SESSION");
if(user_session!=null){
req.getSession().removeAttribute("USER_SESSION");
}
resp.sendRedirect("/login.jsp");
SysFilter.java
//需要转型,不然该类型获取不到session
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
Object user_session = request.getSession().getAttribute("USER_SESSION");
System.out.println(user_session);
if(user_session==null){
response.sendRedirect("/login.jsp");
}
filterChain.doFilter(servletRequest,servletResponse);
https://gitee.com/daban2009/smbms
commons-io-2.11.0.jar
下载地址:https://mvnrepository.com/artifact/commons-io/commons-io/2.11.0
commons-fileupload-1.4.jar
下载地址:https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload/1.4
//用于判断是普通表单(false),还是带文件上传的表单(true)
boolean isMultipartContent(HttpServletRequest request)
//将表单提交的数据封装成FileItem
List<FileItem> parseRequest(HttpServletRequest request)
表单如果包含一个文件上传项,这个表单的enctype属性就必须设置为multipart/form-data
例:
【常用方法】
boolean isFormField(),判断FileItem对象封装的数据每一项是一个普通文本表单(True),还是文件表单(false)
String getFieldName(),返回表单标签name属性的值
String getString() ,将FileItem对象中的数据以字符串返回
String getName(),获得文件上传字段中的文件名
InputStream getInputStream(),以流的形式返回上传文件的数据内容
delete(),清空FileItem对象中存放的主体内容,如果主体内容保存在临时文件,则删除该临时文件
1、创建(new)DiskFileItemFactory对象,并设置该对象相关参数(也有默认值)
2、创建(new)ServletFileUpload对象,传递参数为DiskFileItemFactory对象
3、将请求解析成一个FileItem列表(servletFileUpload.parseRequest(request))
4、遍历FileItem列表,使用isFormField()判断为文件表单项,则进行流处理
5、进行流处理fileItem.getInputStream()得到输入流,new一个FileOutputStream。可以进行写入
package com.daban.servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
@WebServlet(name = "FileServlet", value = "/upload.do")
public class FileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("进入sevrlet");
//判断上传文件是普通表单还是文件表单
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 tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tempfile = new File(tempPath);
if(!tempfile.exists()){
tempfile.mkdir();//不存在就创建
}
//处理上传文件,我们可以使用request.getInputStream()获取,十分麻烦
//但是建议使用common-fileupload来完成,他需要依赖于commons-io组件
//1、创建DiskFileItemFactory对象,处理文件上传路径或大小限制
DiskFileItemFactory diskFileItemFactory = getDiskFileItemFactory(tempfile);
//2、获取ServletFileUpload
ServletFileUpload servletFileUpload = getServletFileUpload(diskFileItemFactory);
//3、处理上传文件
String msg = uploadParseRequest(servletFileUpload, request, uploadPath);
request.setAttribute("msg",msg);
request.getRequestDispatcher("info.jsp").forward(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public DiskFileItemFactory getDiskFileItemFactory(File tempfile){
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(tempfile);//临时保存的目录,
diskFileItemFactory.setSizeThreshold(1024 *1024);//缓冲区大小为1M
return diskFileItemFactory;
}
public ServletFileUpload getServletFileUpload(DiskFileItemFactory diskFileItemFactory){
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setProgressListener(new ProgressListener() {
@Override
public void update(long l, long l1, int i) {
System.out.println("总大小:"+l1+"已上传:"+l +"--"+i);
}
});
servletFileUpload.setHeaderEncoding("utf-8");//处理乱码问题
servletFileUpload.setFileSizeMax(1024 * 1024 * 1000);//设置单个文件最大值
servletFileUpload.setSizeMax(1024 * 1024 * 1000);//设置总共上传文件最大值
return servletFileUpload;
}
public String uploadParseRequest(ServletFileUpload servletFileUpload,HttpServletRequest request,String uploadPath){
String msg = "";
try {
List<FileItem> fileItems = servletFileUpload.parseRequest(request);
for (FileItem fileItem :fileItems){
if(fileItem.isFormField()){
String name = fileItem.getFieldName();
String value = fileItem.getString("utf-8");
System.out.println(name+":"+value);
}else {
String uploadFileName = fileItem.getName();//全名
System.out.println("上传文件名为:"+uploadFileName);
if(uploadFileName.trim().equals("")|| uploadFileName == null){
continue;
}
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);
System.out.println("文件信息 [文件名:"+fileName+"----文件类型:"+fileExtName+"]");
//可以使用uuid类,保证文件名字的唯一
//UUID.randomUUID(),随机生成一个唯一识别的通用码
String uuidPath = UUID.randomUUID().toString();
//存放地址处理
String realPath = uploadPath+"/"+uuidPath;
File realPathFile = new File(realPath);
if(!realPathFile.exists()){
realPathFile.mkdir();
}
InputStream inputStream = fileItem.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(realPath + "/" + fileName);
byte[] buffer = new byte[1024 * 1024];
int len = 0;
while ((len=inputStream.read(buffer))>0){
fileOutputStream.write(buffer,0,len);
}
fileOutputStream.close();
inputStream.close();
msg = "上传成功";
fileItem.delete();
}
}
} catch (FileUploadException | IOException e) {
e.printStackTrace();
}
return msg;
}
}
mail-1.4.7.jar https://mvnrepository.com/artifact/javax.mail/mail/1.4.7
activation-1.1.1.jar https://mvnrepository.com/artifact/javax.activation/activation/1.1.1
首次尝试邮箱发送失败,失败原因:No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
修改配置
①修改文件:D:\Java\jdk1.8.0_322\jre\lib\security\java.security
②删除:SSLv3, TLSv1, TLSv1.1
这几个参数,
package com.daban;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class mailDemo01 {
public static String code = "授权码";
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");
properties.setProperty("mail.transport.protocol","smtp");
properties.setProperty("mail.smtp.auth","true");
//QQ邮箱需要如下代码
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
//发送邮件的5个步骤
//1、创建session对象
//QQ才有
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("452486754@qq.com",code);
}
});
session.setDebug(true);
//2、通过session得到transport对象
Transport transport = session.getTransport();
//3、使用邮箱的用户名和授权码链接上邮件服务器
transport.connect("smtp.qq.com","452486754@qq.com",code);
//4、创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("452486754@qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("daban2009@sina.com"));
message.setSubject("我是一个简单邮件");
message.setContent("使用真实密码登陆","text/html;charset=utf-8");
//5、发送邮件
transport.sendMessage(message,message.getAllRecipients());
}
}
package com.daban;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
public class mailDemo02 {
public static String code = "mbvgjlqvffsxbjdi";
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
// properties.setProperty("mail.host","smtp.qq.com");//非必须
properties.setProperty("mail.transport.protocol","smtp");
// properties.setProperty("mail.smtp.auth","true");//非必须
//QQ邮箱需要如下代码
// MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
// mailSSLSocketFactory.setTrustAllHosts(true);
// properties.put("mail.smtp.ssl.enable","true");
// properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
//发送邮件的5个步骤
//1、创建session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("452486754@qq.com",code);
}
});
session.setDebug(true);
//2、通过session得到transport对象
Transport transport = session.getTransport();
//3、使用邮箱的用户名和授权码链接上邮件服务器
transport.connect("smtp.qq.com","452486754@qq.com",code);
//4、创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("452486754@qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("daban2009@sina.com"));
message.setSubject("我是一个嵌入资源邮件");
//4.1准备一个图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new FileDataSource("D:\\Java\\JavaProject\\功能扩展\\mail-java\\src\\a.webp"));
image.setDataHandler(dataHandler);
image.setContentID("a.webp");
//4.2准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一个带图片的邮件","text/html;charset=utf-8");
//4.3描述数据关系
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(image);
mimeMultipart.addBodyPart(text);
mimeMultipart.setSubType("related");
//4.4设置到消息中保存修改
message.setContent(mimeMultipart);
message.saveChanges();
//5、发送邮件
transport.sendMessage(message,message.getAllRecipients());
}
}
package com.daban;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
public class mailDemo03 {
public static String code = "mbvgjlqvffsxbjdi";
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol","smtp");
//发送邮件的5个步骤
//1、创建session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("452486754@qq.com",code);
}
});
session.setDebug(true);
//2、通过session得到transport对象
Transport transport = session.getTransport();
//3、使用邮箱的用户名和授权码链接上邮件服务器
transport.connect("smtp.qq.com","452486754@qq.com",code);
//4、创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("452486754@qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("daban2009@sina.com"));
message.setSubject("我是一个嵌入资源加附件邮件");
//4.1准备一个图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new FileDataSource("D:\\Java\\JavaProject\\功能扩展\\mail-java\\src\\a.webp"));
image.setDataHandler(dataHandler);
image.setContentID("a.webp");
//4.2准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一个带图片的邮件","text/html;charset=utf-8");
//准备一个附件
MimeBodyPart att = new MimeBodyPart();
DataHandler dataHandlerAtt = new DataHandler(new FileDataSource("D:\\Java\\JavaProject\\功能扩展\\mail-java\\src\\网页乱码问题解决.md"));
att.setDataHandler(dataHandlerAtt);
att.setFileName("网页乱码问题解决.md");
//4.3描述数据关系,将各部分加入MimeMultipart
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(image);
mimeMultipart.addBodyPart(text);
mimeMultipart.addBodyPart(att);//加入附件
mimeMultipart.setSubType("mixed");//三种alternative,related,mixed
//4.4设置到消息中保存修改
message.setContent(mimeMultipart);
message.saveChanges();
//5、发送邮件
transport.sendMessage(message,message.getAllRecipients());
}
}
RegisterServlet.java
package com.daban.servlet;
import com.daban.pojo.User;
import com.daban.utils.SendMail;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "registerServlet", value = "/registerServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入");
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username, password, email);
SendMail sendMail = new SendMail(user);
sendMail.start();
req.setAttribute("msg","注册成功,请在邮箱中查看注册信息!");
req.getRequestDispatcher("info.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
SendMail.java
package com.daban.utils;
import com.daban.pojo.User;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendMail extends Thread{
private User user;
public SendMail(User user){
this.user = user;
}
public static String code = "mbvgjlqvffsxbjdi";
@Override
public void run() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol","smtp");
//发送邮件的5个步骤
//1、创建session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("452486754@qq.com",code);
}
});
session.setDebug(true);
//2、通过session得到transport对象
Transport transport = null;
try {
transport = session.getTransport();
//3、使用邮箱的用户名和授权码链接上邮件服务器
transport.connect("smtp.qq.com","452486754@qq.com",code);
//4、创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("452486754@qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));
message.setSubject("邮件发送测试");
String ms = user.getUsername()+"用户:恭喜您,注册成功,您的密码为:"+user.getPassword()+",请妥善保管";
message.setContent(ms,"text/html;charset=utf-8");
//5、发送邮件
transport.sendMessage(message,message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
application.properties
spring.mail.username=452486754@qq.com
spring.mail.password=授权码
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.enable=true
package com.example.springdemo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringdemoApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//不带附件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("我是主题");
message.setText("我是正文");
message.setFrom("452486754@qq.com");
message.setTo("daban2009@sina.com");
mailSender.send(message);
}
@Test
void test2() throws Exception {
//带附件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setSubject("我是主题");
mimeMessageHelper.setText("我是正文");
//附件
mimeMessageHelper.addAttachment("a.webp",new File("D:\\Java\\JavaProject\\springdemo\\a.webp"));
mimeMessageHelper.setFrom("452486754@qq.com");
mimeMessageHelper.setTo("daban2009@sina.com");
mailSender.send(mimeMessage);
}
}