Java Web
一.基本概念
1.web开发:
- web,网页的意思,www.baidu.com.
- 静态web
- html,css
- 提供给所有人的数据不会发生变化!
- 动态web
- 淘宝等,几乎所有网站都用动态
- 提供给所有人看的数据会发生变化,每个人在不同的时间,不同的地点看到的信息各不相同!
- 技术栈:Servlet/jsp, ASP, PHP
在Java中,动态web资源开发技术统称为JavaWeb
2 web应用程序
web应用程序:可以提供浏览器访问的程序;
- a.html b.html 多个web资源,这些web资源可以被外界访问,对外界提供服务
- 你们能访问的任何一个网页或者资源,都存在与这个世界的某一个角落的计算机上。
- URL
- 这个统一的web资源会被放在同一个文件夹下,web应用程序->Tomcat:服务器
- 一个web应用由多部分组成(静态web,动态web)
- html,css,js
- jsp,servlet
- java程序
- jar包
- 配置文件(properites)
web应用程序编写完后,若想给外界访问,需要一个服务器来统一管理
3.静态Web
- *.html *.htm这些都是网页的后缀,如果服务器上一直存在这些东西,我们就可以进行读取。
- 静态web存在的缺点
- Web页面无法动态更新,所有用户看到的都是同一个页面
- 轮播图,点击特效:伪动态
- JavaScript【实际开发中,用的最多】
- 它无法和数据库交互(数据无法持久化,用户无法交互)
- Web页面无法动态更新,所有用户看到的都是同一个页面
4.动态web
页面会动态展示:Web的页面展示的效果因人而异;
缺点:
- 假如服务器的Web资源出现了错误,我们需要重新编写我们的后台程序,重新发布;
- 停机维护
优点
- Web页面可以动态更新,所有用户看到的都是同一个页面
- 它可以和数据库交互
新手村:魔鬼训练( 分析原理,看源码)--Pk
二.web服务器
1.技术讲解
ASP:
- 微软:国内最早流行的就是ASP;
- 在HTML中嵌入了VB的脚步,ASP+COM;
- 在ASP开发中,基本一个页面就有几千行的业务代码,页面极其混乱
- 维护成本高!
- c#
php:
- PHP开发速度很快,功能很强大,跨平台,代码很简单(70%,WP:开源的博客引擎,大部分用php)
- 无法承载大访问量的情况(局限性)
JSP/Servlet:
B/S:浏览器和服务器
C/S:客户端和服务器
- sun公司主推的B/S架构
- 基于Java语言的(所有的大公司,或者一些开源的组件,都是用Java写的)
- 可以承载三高问题带来的影响;
- 语法像ASP 学ASP可以转JSP
三高:高并发,高可用,高性能
2.web服务器
服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息;
IIS
微软的:ASP ... Windows中自带的
Tomcat
面向百度编程:
Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,由Apache、Sun 和其他一些公司及个人共同开发而成。由于有了Sun 的参与和支持,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 规范。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为比较流行的Web 应用服务器。
Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。对于一个初学者来说,他是最佳的选择
Tomcat 实际上运行JSP 页面和Servlet。它还是一个Servlet和JSP容器,Tomcat最新版本为10.0.23。
工作3-5年,可以尝试手写Tomcat服务器;
下载Tomcat:
- 安装or解压
- 了解配置文件和目录结构
- 了解作用
三.Tomcat
1.安装Tomcat
1.Tomcat官网 https://tomcat.apache.org
2.下载选择:
解压下载完得到的压缩包
文件内容解释:
2.Tomcat启动和配置
2.1 启动、关闭Tomcat
测试: http://localhost:8080/
2.2 可能遇到的问题
- Java环境变量没有配置
- 闪退问题:需要配置兼容性
- 乱码问题:配置文件中设置
3.配置
可以配置启动的端口号:
- tomcat的默认端口号:8080
- mysql:3306
- http:80
- https:442
可以配置主机的名称
- 默认的主机名为:localhost-127.0.0.1
- 默认的网站应用的存放位置为:webapps
高难度面试题:
请你谈谈网站是如何进行访问的!
- 输入一个域名,回车!
- 检查本机的C:\Windows\System32\drivers\etc\hosts 配置文件下有没有这个域名映射
- 有:直接返回对应的ip地址,在这个地址中,有我们需要访问的web程序,可以直接访问
- 没有:去DNS服务器找,找到的话就返回,找不到的话就返回找不到;
4.发布一个web网站
不会就先模仿
- 将自己写的网站,放到服务器(Tomcat)中指定的web应用的文件夹(webapps)下,就可以访问了
网站应该有的结构
--webapps:Tomcat服务器的web目录
-ROOT
-kk:网站的目录名
·WEB-INF
-classes:java程序
-lib:web应用所依赖的jar包
-web.xml:网站配置文件
-index.html 默认的首页
·static
-css
-style.css
-js
-img
-......
HTTP协议:面试
Maven:构建工具
- Maven安装包
Servlet入门
- HelloWorld!
- Servlet配置
- 原理
四.Http
1.什么是Http
HTTP(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP(网络协议)之上
- 文本:html,字符串,-....
- 超文本:图片、音乐,视频,定位,地图......
- 默认端口:80
Https(s):
- 默认端口:443
2.两个时代
- http1.0
- HTTP/1.0:客户端与web服务器连接,只能获得一个web资源
- http2.0
- HTTP/1.1:客户端与web服务器连接,可以获得多个web资源
3.Http请求
客户端--发请求--服务器
百度:
- Request URL:https://www.baidu.com/ 请求地址
- Request Method:GET GET方法/POST方法
- Status Code:200 OK 状态码:200
- Remote Address:180.101.50.188:443
3.1 请求行
- 请求中的请求方式:GET
- 请求方式:Get,Post
- get:请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全
- post:请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内容,安全,但不高效
3.2消息头
- Accept:告诉浏览器,它所支持的数据类型
- Accept-Encoding:支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
- Accept-Language:支持浏览器,它的语言环境
- Cache-Control:缓存控制
- Connection:告诉浏览器,请求完成是断开还是保持连接
- HOST:主机.....
4.Http响应
- 服务器--响应--客户端
百度:
4.1.响应体
- Accept:告诉浏览器,它所支持的数据类型
- Accept-Encoding:支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
- Accept-Language:支持浏览器,它的语言环境
- Cache-Control:缓存控制
- Connection:告诉浏览器,请求完成是断开还是保持连接
- HOST:主机.....
- Refresh:告诉客户端,多久刷新一次;
- Location:让网页重新定位
4.2响应状态码
200:请求响应成功 200
3xx:请求重定向
- 重定向:你重新到我给你的新位置去
4xx:找不到资源 404
- 资源不存在
5xx:服务器代码错误 500 502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址栏并回车的一瞬间到页面能够展示回来,经历了什么?
五,Maven
为什么要学习这个技术?
1.在JavaWeb开发中,需要使用大量的jar包,我们手动导入;
2.如何能够让一个东西自动帮我们导入和配置这个jar包
由此 Maven诞生了
1.Maven项目架构管理工具
我们目前用来就是方便导入jar包的!
Maven的核心思想:约定大于配置
- 有约束,不要去违反
Maven会规定好你该如何去编写我们的Java代码,必须按照这个规范来;
2.下载安装Maven
官网:Maven – Welcome to Apache Mavenhttps://maven.apache.org/
3.配置环境变量
右键此电脑,高级系统设置,环境变量
- M2_HOME maven目录下的bin目录 (maven目录\bin)
- MAVEN_HOME maven的目录
- 在系统的path中配置 %MAVEN_HOME%\bin
测试Maven是否安装成功
4. 阿里云镜像
- 镜像:mirrors
- 作用:加速我们的下载
- 国内建议使用阿里云的镜像
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
5.本地仓库
在本地的仓库,远程仓库
建议一个本地仓库:localRepository
<localRepository>E:/Maven/repositoryf</localRepository>
6.在IDEA中使用Maven
- 启动IDEA
- 创建一个Maven项目
- 等待项目初始化完毕
- 观察Maven仓库中多了什么东西?
- IDEA中的Maven设置
- IDEA项目创建成功后,看一眼Maven的配置
- 到这里,Maven在IDEA中的配置和使用就OK了
7.创建一个普通的Maven项目
直接创建
在web应用下
8.在IDEA标记文件夹功能
9.在IDEA配置Tomcat
点击fix后
解决了警告问题
必须要的配置:为什么会有这个问题:我们访问一个网站,需要指定一个文件夹名字 (在webapp下);
10.pom.xml文件
pom.xml是Maven的核心配置文件
maven由于他的约定大于配置,之后可能会遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
<build>
.......
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
......
</build>
11.IDEA操作
12.解决遇到的问题
- Maven 3.6.2(不兼容JDK 变为3.6.1)
- Tomcat 闪退
- IDEA中每次都要重复配置Maven (在IDEA中的全局默认配置中去配置)
- Maven项目中Tomcat无法配置
- Maven默认web项目中的web.xml版本问题
- Maven仓库的使用
六.Servlet
1.Servlet简介
- Servlet就是sun公司开发web的一门技术
- sun在这些API中提供一个接口叫做:Servlet,如果你想开发一个Servlet程序,只需要完成两个小步骤
- 编写一个类,实现Servlet接口
- 把开发好的java类部署到web服务器中
- 把实现了Servlet接口的Java程序叫做Servlet
2.HelloServlet
2.1构建一个Maven项目(空项目)
1.构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建立Model;这个空的工程就是Maven的主工程。(将依赖的web支持换到最新)
2.2 新建一个Module (添加web支持)
2.3关于Maven父子工程的理解
父项目中:
<modules>
<module>servlet-01</module>
<modules>
子项目中:
<parent>
</parent>
父项目中jar包 子项目可以直接用
son extends father
2.4 Maven环境优化
- 修改web.xml为最新的
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> </web-app>
- 将maven的结构搭建完整
- main下添加resources和java
- 将文件夹进行标注(java标记为蓝色)
2.5 编写一个Servlet程序
1.编写一个普通类
2.实现Servlet接口,这里直接继承HttpServlet
1212
2.6编写Servlet的映射
为什么需要映射:我们写的是Java程序,但是要通过浏览器访问,而浏览器要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需要给他一个浏览器能够访问的路径
2.7配置Tomcat
注意:配置项目发布的路径就可以了
2.8 启动测试
3.Servlet原理
Servlet是由Web服务器调用,Web服务器在收到浏览器的请求之后.会:
4.Mapping问题
1.一个Servlet可以指定一个映射路径(正常情况)
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/h1</url-pattern> </servlet-mapping>
2.一个Servlet可以指定多个映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/h1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/h3</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/h4</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>*.kk</url-pattern> </servlet-mapping>
应用:404没设置的页面 可以用/*将404页面进行装饰
6.优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求
7.自定义404
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.kk.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
新建一个ErrorServlet类
package com.kk.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 ErrorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");/*以html展示 并且以utf-8编码*/
PrintWriter writer = resp.getWriter();
writer.print("<strong>自定义404</strong>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
总结:
- 按照原理图理解Servlet的逻辑
- 会自定义404
5.ServletContext
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,他代表了当前的web应用;
5.1.共享数据:
我在这个Servket中保存的数据,可以在另一个Servlet中拿到
package com.kk.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 HelloWorld 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="kk"; //数据
context.setAttribute("username",username);//将一个数据保存在了ServletContext中,名字为:username 值username
System.out.println("Hello");
}
}
package com.kk.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 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");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?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_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.kk.servlet.HelloWorld</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.kk.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
</web-app>
测试访问:
需要先访问hello页面,数据传入后访问getc页面
5.2.获取初始化参数
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.kk.servlet.ServletDomo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
public class ServletDomo03 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 {
}
}
5.3.请求转发
public class ServletDomo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");
requestDispatcher.forward(req,resp); //调用forward实现请求转发;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
5.4 读取资源文件
Properties
- 在java目录下新建properties
- 在resources目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为类路径
public class ServletDomo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(is);
String username = properties.getProperty("username");
String pwd = properties.getProperty("password");
resp.getWriter().print(username);
resp.getWriter().print(pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
username=root
password=123456
6.HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,一个代表响应的HttpServletResponse;
- 如果要获取客户端传来的参数,找HttpServletRequest
- 如果要给客户端响应一些信息,找HttpServletResponse
6.1简单分类
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int 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;
常见应用
- 向浏览器输出消息(前面案例很多)
- 下载文件
- 要获取下载文件的路径
- 下载的文件名是什么?
- 想办法让浏览器支持下载我们要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileOutputStream写入到buffer缓冲区
- 使用OutputStream将缓冲区中的数据输出到客户端!
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.要获取下载文件的路径
String realPath = "E:\\Javastudy\\javaweb\\response01\\target\\classes\\范.png";
System.out.println(realPath);
// 2.下载文件名是什么
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
System.out.println(fileName);
// 3.想办法让浏览器支持我们下载的东西
resp.setHeader("Content-disposition","attachment;filename"+ URLEncoder.encode(fileName,"UTF-8"));
// 4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
// 5.创建缓存区
int len=0;
byte[] buffer = new byte[1024];
// 6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
// 7.将FileOutputStream写入到buffer缓冲区
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
// 8.使用OutputStream将缓存区中的数据输入到客户端
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_INT_RGB);
// 得到图片
Graphics2D g = (Graphics2D)image.getGraphics();/*笔*/
// 设置图片的背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20);
// 给图片写数据
g.setColor(Color.blue);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makenumber(),0,20);
// 告诉浏览器这个请求用图片的方式打开
resp.setContentType("image/jpg");
// 网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
// 把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
// 生成随机数
private String makenumber(){
Random random = new Random();
String num = random.nextInt(999999) + "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 6-num.length(); i++) {
sb.append("0");
}
String s = sb.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4.实现重定向(重要!)
B一个web资源收到客户端A请求后,B他会通知A客户端去访问另一个web资源C,这个过程叫重定向
常见场景:
- 用户登录
void sendRedirect(String var1) throws IOException;
测试:
public class RedirectsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Location","/img");
resp.setStatus(302);
resp.sendRedirect("/img");//重定向
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
面试题:请你聊聊重定向和转发的区别?
相同点
- 页面都会实现跳转
不同点
- 请求转发的时候,url不会产生变化
- 重定向的时候,url地址栏会发生变化
重定向案例
1.设置重定向要跳转的路径
public class RequestTest 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");
System.out.println(username+":"+password);
// 重定向时候一定要注意路径问题,否则404 404为路径设置问题;
resp.sendRedirect("success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.设置跳转的jsp首页
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<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>
设置点击登录按钮后要走的路径/login,此时/login要对应前端页面的action请求处的的路径:
<servlet>
<servlet-name>request</servlet-name>
<servlet-class>com.kk.Servlet.RequestTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>request</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
7.HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
1.获取前端传递的参数
一个获取单个,一个获取多个
2.请求转发
解决乱码:
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
/*后台接受中文乱码问题*/
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("==================");
// resp.sendRedirect();重定向 写前面的路径/s
// this.getServletContext().转发 不用写
/*通过请求转发*/
req.getRequestDispatcher("/success.jsp").forward(req,resp);
resp.setCharacterEncoding("utf-8");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
面试题:请你聊聊重定向和转发的区别?
相同点
- 页面都会实现跳转
不同点
- 请求转发的时候,url不会产生变化 307
- 重定向的时候,url地址栏会发生变化 302
Session
Cookie
JSP -->前端知识!HTML+JS
过滤器
mvc三层架构
七.Cookie Session
1会话
会话:用户打开你一个浏览器,点了很多的超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
有状态会话:保存来过的状态
你 学校
1.发票 学校给你发票
2.学校登记 学校标记你来过了
一个网站 怎么证明你来过
客户端 服务端
1.服务端给客户端一个信件 客户端下次访问服务端带上新建就可以了;cookie
2.服务器登记你来过了,下次你来的时候我来匹配你;session
2.保存会话的两种技术
cookie
客户端技术(响应、请求)
session
服务器技术,利用这个技术,可以保存用户的会话信息,我们可以把信息或者数据放在Session中
常见场景
- 网站登陆之后,下次都不再需要登录了,第二次登录直接已经是登录的状态
3.Cookie
- 从请求中拿到cookie信息
- 服务器响应给客户端cookie
Cookie[] cookies = req.getCookies(); // cookie,服务器从客户端获取 cookie.getName() // 获取cookie的名字 cookie.getValue() //获得cookie的值 Cookie cookie = new Cookie("time",System.currentTimeMillis()+""); //新建一个cookie cookie.setMaxAge(24*60*60); //设置cookie的有效期 resp.addCookie(cookie); // 响应给客户端
cookie:一般保存在本地的用户目录下 appdata
一个网站cookie是否存在上限?聊聊细节
- 一个Cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie 最多存放20个cookie
- Cookie大小有4kb
- 300个cookie浏览器上限
删除Cookie:
- 不设置有效期,关闭浏览器,自动失效;
- 设置有效期为0
网络编程 解决乱码:
//保存用户上一次访问的时间
public class CookieServlet extends HttpServlet {
// 服务器,告诉你,你来的时间,把这个事件封装成一个信件,你下次带来,我就知道你来了
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决中文乱码
req.setCharacterEncoding("utf-16");
resp.setCharacterEncoding("utf-16");
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("time")){
long l = Long.parseLong(cookie.getValue());
Date date = new Date(l);
out.write(date.toLocaleString());
}
}
}else{
out.write("这是您第一次访问访问网站");
}
// 服务器给客户端响应cookie
Cookie cookie = new Cookie("time",System.currentTimeMillis()+"");
// 设置有效期为1天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4.Session(重点!!!!)
1.Session是什么?
- 服务器会给每一个用户(浏览器)创建一个Session对象
- 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session一直存在;
- 用户登录之后,整个网站它都可以访问!
Session和Cookie的区别?
- Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
- Session是把用户的数据写到用户独占Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
- Session对象由服务器创建
使用场景:
- 保存一个登录用户的信息
- 购物车信息
- 在整个网站中经常会使用的数据,我们将它保存在SessIon中;
2.使用Session;
1.创建Session 根据Session是否存在采取不同反馈
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*解决乱码问题*/
req.setCharacterEncoding("utf-16");
resp.setCharacterEncoding("utf-16");
resp.setContentType("text/html,charset=utf-8");/*设置浏览器相应的格式*/
/*得到Session*/
HttpSession session = req.getSession();
/*给Session存东西*/
session.setAttribute("name",new Person("kk",23));
/*获取Session的ID*/
String id = session.getId();
/*判断Session是不是新创建的*/
if (session.isNew()){
resp.getWriter().write("Session创建成功,sessionid为:"+id);
}else {
resp.getWriter().write("Session已经在服务器存在了,为:"+id);
}
//Session创建的时候做了什么事情:在cookie中创建一个Session,再请求的时候再带回来
Cookie cookie = new Cookie("JSESSIONID",id);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.从另一个网页获取Session
public class SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*解决乱码问题*/
req.setCharacterEncoding("utf-16");
resp.setCharacterEncoding("utf-16");
resp.setContentType("text/html,charset=utf-8");/*设置浏览器相应的格式*/
/*得到Session*/
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("name");
System.out.println(person.toString());
resp.getWriter().write(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3 .会话自动过期
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
xml设置会话时间的方法
<!--设置Session默认的失效时间-->
<session-config>
<!-- 15分钟后 Session自动失效 以分钟为单位 -->
<session-timeout>1</session-timeout>
</session-config>
Session不够存储时候,用ServletContext,后面叫Application context
八.jsp
1.什么是JSP
Java Server Pages:Java服务器页面,也和Servlet一样,用户动态web技术
最大的特点:
- 写JSP就像在写HTML
- 区别:
- HTML只给用户嵌入Java代码
- 为用户提供动态数据
2.JSP原理
思路:JSP到底是怎么执行的?
- 代码层面没有任何问题
- 服务器内部工作
- (tomcat中有一个work目录)
- IDEA中使用Tomcat的会在IDEA中产生一个work目录
- 页面转换成了java程序!
- 浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet!
- JSP最终也会被转化为一个Java类
1.判断请求
2.内置一些对象
3.输出页面前增加的代码 4.以上的对象可以在JSP页面中直接使用
在JSP页面中
只要是Java代码就会原封不动的输出
如果是html代码,就会转换为
这样的格式,输出到前端
3.JSP基础语法
任何语言都有自己的语法,Java中又,JSP作为java技术的一种应用,它拥有一些自己扩充的语法(了解,知道即可!),java所有语法都支持
Jsp表达式
Jsp脚本片段
脚本片段的再实现
脚本片段的再实现
JSP声明:会被编译成JSP生成的Java的类中!其他的生成到_jspServices中!
在Java中嵌入Java代码!
总结
- <% %> 块片段
- <% = %>
- <% ! %>
JSP的注释,不会在客户端显示,HTML会!
4.jsp指令
1.可以在xml中利用errorpage设置500 404页面跳转 进而自定义500 404页面
2.网页头部选项每个页面都有,利用include将公共部分导入
3.文件结构建议
5. 九大内置对象
- PageContext (存东西)
- Request (存东西)
- Response
- Session (存东西)
- Application [ServletContext] (存东西)
- config [ServletConfig]
- out
- page
- exception
作用域:application、session > pageContext、request
request:客户端想服务器发送请求,产生的数据,看完就没用了,比如:新闻
session:客户端想服务器发送请求,产生的数据,一会还有用,比如:购物车
application:客户端想服务器发送请求,产生的数据,一个用完了,其他对象还能用,比如:聊天数据;
6.JSP标签、JSTL标签、EL表达式
EL表达式:${}
- 获取数据
- 执行运算
- 获取web开发的常用对象
九.JavaBean
实体类
JavaBean有特定的写法:
- 必须要有一个无参构造
- 属性必须私有化
- 必须有对应的get/set方法
一般用来和数据库的字段做映射 ORM
ORM:对象关系映射
- 表-->类
- 字段-->属性
- 行记录-->对象
十.MVC三层架构
1.早些年
什么是MVC:Model view Controller 模型、视图、控制器
用户直接访问控制层,控制层就可以直接操作数据库;
2.MVC三层架构
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD(Dao)
View
- 展示数据
- 提供链接发起Servlet(a,form,img...)
Controller(Servlet)
- 接受用户的请求:(req:请求参数 、Session信息...)
- 交给业务层处理对应的代码
- 控制视图的跳转
- 登录---接收用户的登录请求---处理用户的请求(获取用户的参数,username,password)--->交给业务层处理登录业务(判断用户名密码是否正确;事务)--->Daoc层查询用户名和密码是否正确--》数据库
十一.Filter
Filter:过滤器,用来过滤网站的数据;
- 处理中文乱码
- 登录验证....
Filter开发步骤:
这里直接新建一个maven项目,添加web支持,配置tomcat时候要在项目中导入tomcat
1.导包:
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
</dependencies>
2.编写过滤器
实现Filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter {
/*初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现!*/
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("已经初始化");
}
/*
* Chain:链
* 1.过滤器中的所有代码,在过滤器特定请求的时候都会执行
* 2.必须要让过滤器继续同行
* */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前");
chain.doFilter(request,response);//让请求继续走,如果不写,程序到这里停止
System.out.println("执行后");
}
/*销毁:web服务器关闭的时候,过滤器会销毁*/
public void destroy() {
System.out.println();
System.out.println("销毁");
}
}
3.在web.xml中配置filter过滤器
<filter>
<filter-name>Filter</filter-name>
<filter-class>com.kk.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter</filter-name>
<!--只要是/servlet下的任何请求。都会经过这个过滤器-->
<url-pattern>/s/*</url-pattern>
</filter-mapping>
十二.监听器
实现一个监听器的接口;(有N种)
1.编写一个监听器,实现监听器的接口
package com.kk.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数:统计Session
public class OnlineCountListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
ServletContext s = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) s.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(1);
} else {
int count = onlineCount.intValue();
onlineCount = new Integer(count + 1);
}
s.setAttribute("OnlineCount",onlineCount);
}
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext s = se.getSession().getServletContext();
Integer onlineCount = (Integer) s.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(0);
} else {
int count = onlineCount.intValue();
onlineCount = new Integer(count -1);
}
s.setAttribute("OnlineCount",onlineCount);
}
/*Session销毁
1.自动销毁,在web.xml中配置
* */
}
2.在web.xml中注册监听器
<listener>
<listener-class>com.kk.listener.OnlineCountListener</listener-class>
</listener>
3.看情况是否使用