Java Web
Java Web
1、 基本概念
1.1 、前言
web开发
- web,网页的意思。www.daidu.com
- 静态web
- html 、css
- 提供给所有人看的数据 始终不会发生变化
- 动态web
- 淘宝 几乎所有的网站
- 提供给所有人看的数据 始终不会发生变化。 每个人在不同的时间、不同的地点 看到的信息各不相同
- 技术栈:Servlet/JSP ,ASP , PHP
在java中动态web资源开发的技术统称为JavaWeb;
1.2 、Web应用程序
web应用程序:可以提供浏览器访问的程序;
- a.html
- 能访问到的任何一个资源都存在于这个世界上的某一个角落的计算机上。
- 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
- 无法和数据库交互(数据无法持久化,用户无法交互)
- Web页面无法动态更新,所有用户看到的都是用一个页面
1.4、动态web
页面会动态展示:“Web"展示的效果因人而异;
缺点:
- 假如服务器的动态web’资源出现了错误,我们需要重新编写后台程序 ,重新发布
- 停机维护
优点:
- Web页面无法动态更新,所有用户看到的都是不同的页面
- 可以和数据库交互(数据持久化,注册,商品信息,用户信息)
2、Web服务器
2.1、技术讲解
ASP
- 微软:国内最早流行的及时ASP
- 在html中嵌入了vb的脚本,ASP+COM
- 在ASP开发中,基本一个页面
- 维护成本高
- c#
- IIS
PHP
- php开发速度快,功能很强大,跨平台,代码很简单()
- 无法承载大访问量的情况下(局限性)
JSP/Servlet:
B/S:浏览器和服务器
C/S:客户端和服务器
- sun公司主推的B/S架构
- 基于Java的语言(所有的大公司,或者一些开源的组件,都是用java写的)
- 可以承载三高问题带来的影响;(高并发,高可用,高性能)
2.2、web服务器
服务器是一种被动操作,用来处理用户的一些请求和给用户一些响应
IIS
微软的:ASP… windows中自带的
tomcat
面向百度编程
Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 规范。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。
Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。对于一个初学者来说,可以这样认为,当在一台机器上配置好Apache 服务器,可利用它响应HTML(标准通用标记语言下的一个应用)页面的访问请求。实际上Tomcat是Apache 服务器的扩展,但运行时它是独立运行的,所以当你运行tomcat 时,它实际上作为一个与Apache 独立的进程单独运行的。
诀窍是,当配置正确时,Apache 为HTML页面服务,而Tomcat 实际上运行JSP 页面和Servlet。另外,Tomcat和IIS等Web服务器一样,具有处理HTML页面的功能,另外它还是一个Servlet和JSP容器,独立的Servlet容器是Tomcat的默认模式。不过,Tomcat处理静态HTML的能力不如Apache服务器。目前Tomcat最新版本为9.0.41**。**
下载tomcat:
- 安装or解压
- 了解配置文件及目录结构
- 这个东西的作用
3、Tomcat
3.1 、安装tomcat
https://tomcat.apache.org/
3.2、Tomcat启动和配置
文件夹作用
启动。关闭tomcat
测试tomcat:http://localhost:8080/
可能遇到的问题
- java环境变量没有配置 (tomcat依赖于java)
- 闪退问题,需要配置兼容性
- 乱码问题:配置文件中设置
3.3、配置
服务器核心配置文件
可以配置启动的端口号
tomcat 的默认端口号:8080
mysql:3306
http:80
https:443
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
可以配置主机的名称
- 默认的主机名为 localhost->127.0.0.1
- 默认的网站应用存放的位置为:webapps
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
高难度面试题:
请你谈谈网站是如何进行访问的!
-
输入一个域名去访问;回车
-
检查本机的C:\Windows\System32\drivers\etc\hosts 配置文件下有没有这个域名映射;
-
有:直接返回对应的ip地址,这个地址中,有我们需要访问的web程序,可以直接访问
127.0.0.1 localhost
-
没有:去DNS服务器上找(domain name service)找到返回,找不到就返回找不到
-
-
可以配置一下环境变量(可选性)
3.4、发布一个web网站
不会就先模仿
- 将自己写的网站放到服务器(Tomcat)中指定的web应用的文件夹(Webapps)下。就可以访问了
网站应该有的结构
--webapps: tomcat服务器的web目录
-ROOT
-Richard:网站的目录名
-WEB-INF
-Classes :java程序
-lib:web应用所依赖的jar包
-web.xml : 网站的配置文件
-index.html 默认首页
-static
-css
style.css
-js
-img
4、Http
4.1、什么是http
HTTP:超文本传输协议(Hypertext Transfer Protocol,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 状态码
Remote(远程) Address(地址): 180.101.49.11:443
请求:
Accept: text/html,
Accept-Encoding: gzip, deflate, br 类型编码
Accept-Language: zh-CN,zh;q=0.9 语言
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 GB2312 ISO8859-1
Accept-Language: 告诉浏览器他的语言环境
Cache-Control: 缓存控制
Connection: 告诉浏览器,请求完成是断开还是保持联系
host:表示主机.....
4.4、HTTP响应
- 服务器–响应–客户端
百度:
Cache-Control: private 缓存控制
Connection: keep-alive 连接:保持连接
Content-Encoding: gzip 编码 GBK UTF-8
Content-Type: text/html;charset=utf-8
Server: BWS/1.1 服务信息
1.响应体
Accept: 告诉浏览器,它所支持的数据类型
Accept-Encoding: 支持哪种编码格式,GBK UTF-8 GB2312 ISO8859-1
Accept-Language: 告诉浏览器他的语言环境
Cache-Control: 缓存控制
Connection: 告诉浏览器,请求完成是断开还是保持联系
host:表示主机.....
refresh:告诉客户端,多久刷新一次
Location:让网页重新定位
2.响应状态码
- 200:请求成功
- 3xx:请求重定向
- 重定向:你重新到我给你的新位置去;
- 4xx:找不到资源 404
- 资源不存在
- 5xx:服务器代码错误 500 502 :网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车的一瞬间到页面能够展示回来,经历了什么?
5、Maven
我们为什么要学习这个技术?
-
在javaweb开发中,需要使用大量的jar包,我们手动去导入
-
如何能够让一个东西自动帮我们导入和配置这个jar包
由此,Maven诞生了。
5.1、Maven项目架构管理工具
我们目前用他来方便导入jar包
Maven核心思想:约定大于配置
- 有约束、不要去违反。
Maven会规定好你如何去写java代码,必须按照这个规范来。
5.2、下载安装Maven
官网:https://maven.apache.org/index.html
各个版本下载:http://archive.apache.org/dist/maven/maven-3/3.6.2/binaries/
下载完成后,解压即可;
5.3、配置环境变量
配置如下:
- M2_HOME maven目录下的bin目录
- MAVEN_HOME maven目录
- 在系统的path中配置 %MAVEN_HOME%\bin
测试Maven是否安装成功,保证必须配置完毕!
5.4、阿里云镜像
-
镜像:mirrors
- 作用:加速我们的下载
-
国内建议使用阿里云的镜像
<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>D:\lyj\资料\Java\Maven\apache-maven-3.6.3\maven-repo</localRepository>
5.6、在idea中使用Maven
-
启动idea
-
等待项目初始化完毕
-
观察maven仓库
-
idea中的Maven设置
idea中配置Maven 注意:经常在idea中会出现一个问题,就是项目自动创建完成后,他这个MavenHome会使用Idea默认,我们如果发现了这个问题,手动改为本地配置。
5.7、创建一个普通的Maven项目
5.8、在idea中标记文件夹功能
5.9、在idae中配置tomcat
取消警告问题
为什么会有这个问题:我们访问一个网站,需要指定一个文件夹的名字;
5.10、pom文件
pom.xml 是maven的核心配置文件
maven由于他的约定 大于配置
<!-- 在build中配置resources , 来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
5.11、maven树
6、Servlet
6.1、Servlet简介
- Servlet就是sun公司,开发动态web的一门技术。
- sun公司在这些api中提供了一个接口叫做:Servlet,如果你想开发一个Servlet程序,主需要完成两个小步骤:
- 编写一个类实现Servlet接口
- 把开发好的java类部署到web服务器中。
把实现了servlet接口的java程序叫做,Servlet
6.2、HelloServlet
Servlet在sun公司有两个默认的实现类:HttpServlet,GenericServlet
-
构建一个普通Maven项目,删掉里面的src目录,以后我们学习就在这个项目里面建立Module;这个空的工程就叫Maven的主工程
-
关于Maven父子工程的理解
<modules> <module>servlet-01</module> </modules>
父项目中有modules
子项目中有parent
son extends father
-
Maven环境优化
- 修改web.xml为最新
- 将maven的结构搭建完整
-
编写一个servlet
-
编写一个普通类
-
实现Servlet接口
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 响应流 //ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = resp.getWriter(); writer.print("Hello,Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
-
-
编写Servlet的映射
为什么要写映射:我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中注册我们写的servlet,还需要给他一个浏览器能够访问的路径。
<!-- 配置Servlet --> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.richard.servlet.HelloServlet</servlet-class> </servlet> <!-- Servlet的请求路径 --> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
-
配置Tomcat
注意:配置项目发布的路径
-
启动测试
错误原因:Tomcat版本太高。
6.3、运行原理
Servlet是有web服务器调用,web服务器在收到浏览器请求之后,会:
6.4、Mapping问题
-
一个Servlet可以指定一个映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello1</url-pattern> </servlet-mapping>
-
一个Servlet可以指定多个映射路径
<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>
-
一个Servlet可以指定通用映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping>
-
指定一些后缀或者前缀(*前面不能加映射路径)
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.liyujie</url-pattern> </servlet-mapping>
-
优先级问题
指定了固有的映射路径,优先级最高,如果找不到就会走默认的处理请求;
public class Error 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();
writer.print("<h1>404</h1>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.richard.servlet.Error</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
6.5、ServletContext
web容器在启动的时候,他会为每个web程序都创建一个Servletcontext对象,他代表了当前的web应用。
1、共享数据
我在这个servlet中保存的数据,可以再另外一个servlet中拿到;
public class getServlet extends HttpServlet { // 读取
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
String username = (String) context.getAttribute("username");
resp.getWriter().print("名字:" + username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
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
System.out.println("hello");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>com.richard.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>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
3、请求转发
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
// RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); // 转发请求路径
// requestDispatcher.forward(req, resp); // 调用forward实现请求转化
context.getRequestDispatcher("/gp").forward(req, resp);
}
4、读取资源文件
Properties
- 在java目录下新建properties
- 在resources目录下新建properties
发现,都被打包到了同一个路径下:classes,我们俗称这个路径为classpath;
思路:需要一个文件流;
@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 password = properties.getProperty("password");
resp.getWriter().print(username + ": " + password);
}
访问测试即可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、下载文件
- 向浏览器输出消息
- 下载文件
- 要获取下载文件的路径
- 下载的文件名
- 设置想办法让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取outoutstream
- 将fileoutputframe流写入到buffer缓冲区
- 使用outputframe将缓冲区中的数据输出到客户端
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 要获取下载文件的路径
String realPath = "D:\\lyj\\JAVA2\\MavenWeb\\Maven105\\response\\target\\response\\WEB-INF\\classes\\1.png";
System.out.println("下载文件的路径:" + realPath);
// 2. 下载的文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\" + 1));
// 3. 设置想办法让浏览器能够支持下载我们需要的东西
resp.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
// 4. 获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
// 5. 创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// 6. 获取outoutstream
ServletOutputStream outputStream = resp.getOutputStream();
// 7. 将fileoutputframe流写入到buffer缓冲区,使用outputframe将缓冲区中的数据输出到客户端
while ((len = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,len);
}
fileInputStream.close();
outputStream.close();
}
3、验证码功能
验证怎么来的?
- 前端实现
- 后端实现,需要用到java的图片类,生成一个图片
public class imageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 如何让浏览器3秒自动刷新一次;
resp.setHeader("refresh","3");
// 在内存中创建一个图片
BufferedImage image = new BufferedImage(84,75,BufferedImage.TYPE_INT_RGB);
// 得到图片
Graphics2D graphics = (Graphics2D) image.getGraphics(); // 笔
// 设置图片的背景颜色
graphics.setColor(Color.white);
graphics.fillRect(0,0,80,20);
// 给图片写数据
graphics.setColor(Color.blue);
graphics.setFont(new Font(null,Font.BOLD, 20));
graphics.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());
}
// 生成随机数
public String makeNum() {
Random random = new Random();
String s = random.nextInt(9999999) + "";
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < 7-s.length(); i++) {
stringBuffer.append("0");
}
s = stringBuffer.toString() + s;
return s;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4、实现重定向
一个web资源受到客户端请求,他会通知客户端去访问另外一个wen资源,这个过程叫做重定向。
常见场景:
-
用户登录
void sendRedirect(String var1) throws IOException;
测试:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
// resp.setHeader("Location","/r/img");
// resp.setStatus(HttpServletResponse.SC_FOUND);
resp.sendRedirect("/r/img");
}
面试题:
请你聊聊重定向和转发的区别?
相同点:
- 页面都会实现跳转
不同点:
- 请求转发的时候,URL不会产生变化
- 重定向的时候,URL地址栏会发生变化
6.7、HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过这个方法HttpServletRequest的方法,获得客户端的所有信息;
1、获取前端传递的参数
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("=====================================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("=====================================");
// 通过请求转发
// 这里的/ 代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req, resp);
}
7、Cookie 、Session
7.1、会话
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话。
有状态会话:一个同学来过教室下次再来教室,我们会知道这个同学曾经来过,称之为有状态会话。
一个网站,怎么证明你来过?
客户端 服务端
- 服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了;cookie
- 服务器登记你来过,下次你来的时候我来匹配你;session
7.2、保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务器技术,利用这个技术,可以保存用户的会话信息,我们可以吧信息或者数据放在session中!
常见:网站登录后,下次不用重新登录,
7.3、Cookie
- 从请求中拿到cookie信息
- 服务器响应给客户端
// 保存用户上一次访问的时间
public class CookieDemo01 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 (Cookie cookie : cookies) {
//
// }
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
// 获取cookie的名字
if (cookie.getName().equals("LastLoginTime")) {
// 获取cookie中的值
long LastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(LastLoginTime);
out.write(date.toLocaleString());
}
}
} else {
out.write("这是您第一次访问!");1613628705268
}
// 服务器给客户端响应一个cookie
Cookie cookie = new Cookie("LastLoginTime", System.currentTimeMillis() + "");
// cookie有效期为一天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
cookie:一般会保存在本地的用户目录下appdate
一个网站cookie是否存在上限!
- 一个cookie只能保存一个信息;
- 一个web站点可以给浏览器发送多个cookie,每个站点最多存放20个
- 300个cookie浏览器上限
- cookie大小有限制4kb
删除cookie
- 不设置有效期,关闭浏览器,自动失效;
- 设置有效期时间为0。立马就没了
编码解码
URLEncoder.encode("liyujie","utf-8") // 编码
URLDecoder.decode(cookie.getValue(),"utf-8") // 解码
7.4、Session(重点)
什么是session:
- 服务器会给每一个用户(浏览器)创建一个session对象;
- 一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在;
- 用户登录之后,整个网站他都可以访问!—> 保存用户信息;保存购物车信息
Sesion和Cokie区别:
- 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-16");
resp.setCharacterEncoding("utf-16");
resp.setContentType("text/html");
// 得到session
HttpSession session = req.getSession();
// 给session中存东西
session.setAttribute("name",new Person("李宇杰",20));
// 获取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);
}
}
// 手动注销
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");
// 得到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);
}
}
// 清除
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);
}
}
会话自动过期:
<!-- 设置session默认结束时间 以分钟为单位 -->
<session-config>
<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中有一个word目录
IDEA中使用tomcat的会在idea的tomcat中产生一个work目录
页面会转化成java程序!
浏览器向服务器发送请求,不管访问什么资源,都是在访问servlet
JSP最终转化为java类
JSP本质上就是一个Servlet
// 初始化
public void _jspInit() {
}
// 销毁
public void jspDestroy() {
}
// JspService
public abstract void _jspService(HttpServletRequest var1, HttpServletResponse var2) throws ServletException, IOException;
-
判断请求
-
内置一些对象
-
输出页面前增加代码
4.以上的这些对象,我们在jsp中可以直接使用
在JSP页面中只要是Java代码,就会原封不动的输出;
如果是HTML代码,就会被转换为:
out.write("</html>\r\n");
这样的格式输出到前端。
8.3、JSP基础语法
任何语言都有自己的语法,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>");
%>
脚本片段的在实现
<%-- 在代码中嵌入html元素--%>
<%
for (int i = 0; i < 5; i++) {
%>
<h1>Hello,Richard!!! <%=i%> </h1>
<%
}
%>
JSP声明
<%!
static {
System.out.println("Loading Servlet!");
}
private int global = 0;
public void richard() {
System.out.println("进入了方法!");
}
%>
JSP声明:会被编译到JSP生成的Java类中!其他的,就会被生成到_jspService()方法中!
在JSP中嵌入Java代码
<%%>
<%=%>
<%!%>
<%-- --%>
JSP的注释,不会再客户端显示,HTML就会!
8.4、JSP指令
<% page args...%>
<%@ include file="" %> // 提取公共页面
正常用下面的。
8.5、9大内置对象
- PageContext
- Request
- Response
- Session
- Application
- config (ServletConfig)
- out
- page 不用了解
- exception
pageContext.setAttribute("name1","richard1"); // 保存的数据只在一个页面中有效
request.setAttribute("name2","richard2"); // 保存的数据只在一次请求中有效,请求转发中携带这个数据
session.setAttribute("name3","richard3"); // 保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","richard4"); // 保存的数据在服务器中有效,从打开服务器到关闭服务器
pageContext.setAttribute("hello1","hello1",PageContext.APPLICATION_SCOPE);
request:客户端向服务器发送请求,产生的数据,用户号看完就没用了,比如新闻,用户看完就没用的!
session:客户端向服务器发送请求,产生的数据,用户用完一会儿还有用,比如:购物车;Hystrix
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能会用,比如聊天数据。
8.6、JSP标签、JSTL标签、EL表达式
EL表达式:${}
- 获取数据
- 执行运算
- 获取web开发的常用对象
- 调用Java方法
<!-- jstl的依赖-->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard的依赖-->
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
JSP标签
名字:<%=request.getParameter("name")%>
年龄:<%=request.getParameter("age")%>
<jsp:include page="jsptag2.jsp">
<jsp:param name="name" value="liyujie"/>
<jsp:param name="age" value="21"/>
</jsp:include>
JSTL表达式
JSTL标签库的使用就是为了弥补HTML标签的不足,他自定义许多标签,可以供我们使用,标签的功能和Java代码一样!、
格式化标签
SQL标签
XML标签
核心标签(掌握部分)
JSTL标签使用步骤:
- 引入对应的taglib
- 使用其中的方法
- 在tomcat中有需要引入jstl的包否则会报错:JSTL解析错误
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>if测试</h4>
<form action="coreif.jsp" method="get">
<%--
EL表达式获取表单中的数据
${param.参数名}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
<%--判断如果提交的用户是管理员,则登录成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin" >
<c:out value="管理员欢迎您!" />
</c:if>
<c:out value="${isAdmin}" />
</body>
</html>
<%@ 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> people = new ArrayList<>();
people.add("zhangsan ");
people.add("zhangsan ");
people.add("zhangsan ");
people.add("zhangsan ");
people.add("zhangsan ");
people.add("zhangsan ");
request.setAttribute("list",people);
%>
var 每一次遍历的对象
items 要遍历的悐
<c:forEach var="people" items="${list}">
<c:out value="${people}"/>
</c:forEach>
</body>
</html>
9、JavaBean
实体类
JavaBean的特有写发:
- 必须有一个无参构造
- 属性必须私有化
- 必须有对应的get,set方法
一把用来个数据库的字段做映射,ORM;
ORM:对象关系映射
- 表—>类
- 字段—>属性
- 行记录—>对象
people表
id | name | age | address |
---|---|---|---|
1 | 李宇杰 | 18 | 山西 |
2 | Richard | 18 | 山西 |
3 | 理查德 | 18 | 山西 |
class People {
private int id;
private String name;
private int age;
private String address;
}
class A {
new People(1,"liyujie",18,"山西");
new People(1,"liyujie",18,"山西");
new People(1,"liyujie",18,"山西");
}
10、MVC三层架构
什么是MVC:model,view,controller,模型,视图,控制器
10.1、早些年
用户直接访问控制层,控制层就可以直接操作数据库;
servlet---crud--->数据库
弊端:程序十分臃肿,不利于维护 servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的
程序员调用JDBC
JDBC
MySQL Oracle SqlServer
10.2、MVC三层架构
model
- 业务逻辑:业务逻辑(Service)
- 数据持久层:CRUD(Dao)
view
- 展示数据
- 提供 链接发起Servlet请求(a,form,img…)
controller(Servlet)
-
接收用户请求:request 请求参数,session信息
-
交给业务层处理对应的代码
-
控制视图的跳转
登录--->接收用户的登录请求--->处理用户的请求(获取用户登录的参数,username,password)---->交给业务层处理登录业务(判断用户名密码是否正确,事务) --->Dao层查询用户名密码是否正确--->数据库
11、Filter(重点)
Filter:过滤器,用来过滤网站数据;
-
处理中文乱码
-
登录验证…
Filter开发步骤:
-
导包
-
编写过滤器
-
导包不要错
实现Filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-16"); servletResponse.setCharacterEncoding("utf-16"); servletResponse.setContentType("text/html;charset=UTF-8"); // 1.过滤中的所有代码,在过滤特定请求的时候都会执行 // 2.必须要让过滤器继续通行 // 3.filterChain.doFilter(servletRequest,servletResponse); System.out.println("CharacterEncodingFilter执行前..."); filterChain.doFilter(servletRequest,servletResponse);// 让我们的请求继续走,如果不写 ,程序到这里就被拦截停止了! System.out.println("CharacterEncodingFilter执行后..."); } // 初始化 @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharacterEncodingFilter初始化"); } // 销毁 @Override public void destroy() { System.gc(); System.out.println("CharacterEncodingFilter被销毁"); } }
-
-
在web.xml中配置Filter过滤器
-
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.richard.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/servlet/s1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.richard.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
</web-app>
12、监听器
实现一个监听器的接口:(有N种)
-
编写一个监听器
实现接听器的接口
// 统计网站在线人数监听 统计session public class OnlineCountListener implements HttpSessionListener { // 创建session监听:看你的一举一动 // 一但创建一个session就会触发一次这个事件! @Override public void sessionCreated(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext ctx = session.getServletContext(); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); System.out.println(se.getSession().getId()); if (onlineCount == null) { onlineCount = new Integer(1); } else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } ctx.setAttribute("OnlineCount",onlineCount); } // 销毁session监听 @Override public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext ctx = session.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); } }
-
web.xml中注册监听器
<listener> <listener-class>com.richard.listener.OnlineCountListener</listener-class> </listener>
-
看情况是否使用
13、过滤器,监听器
监听器:GUI编程中经常使用
用户登录之后才能进入主页!用户注销后就不能进入主页!
-
用户登录之后,向session中放入用户的数据
-
进入主页的时候要判断用户是否已经登录; 要求在过滤器中实现!
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; Object user_session = request.getSession().getAttribute(USER_SESSION); if (user_session == null) { response.sendRedirect("/error.jsp"); } chain.doFilter(request,response); }
14、JDBC
需要jar包的支持:
- java.sql
- javax.sql
- mysql-conneter-java… 连接驱动
实验环境搭建:
导入数据库依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
public class TestJdbc {
public static void main(String[] args) throws Exception {
// 获取配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
// 1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
// 3.向数据库发送sql的对象Statement:CRUD
Statement statement = connection.createStatement();
// 4. 编写sql
String sql = "select * from users";
// 5. 执行查询sql返回一个结果集
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println("id=" + resultSet.getObject("id"));
System.out.println("name=" + resultSet.getObject("name"));
System.out.println("password=" + resultSet.getObject("password"));
System.out.println("email=" + resultSet.getObject("email"));
System.out.println("birthday=" + resultSet.getObject("birthday"));
}
//6. 关闭连接,释放资源 先开后关
resultSet.close();
statement.close();
connection.close();
}
}
JDBC固定步骤:
- 加载驱动
- 连接数据库
- 向数据库发送sql的对象Statement:CRUD
- 编写sql(根据业务,不同的sql)
- 执行sql
- 关闭连接
预编译sql
public class TestJdbc2 {
public static void main(String[] args) throws Exception{
// 获取配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
// 1. 加载驱动
Class.forName("com.mysql.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.setObject(1,9);// 各第一个?占位符的 赋值为1
preparedStatement.setObject(2,"李宇杰");// 各第一个?占位符的 赋值为1
preparedStatement.setObject(3,"12345666");// 各第一个?占位符的 赋值为1
preparedStatement.setObject(4,"344272568@qq.com");// 各第一个?占位符的 赋值为1
preparedStatement.setObject(5,"2000-05-21");// 各第一个?占位符的 赋值为1
// 5. 执行sql
int i = preparedStatement.executeUpdate();
if (i>0) {
System.out.println("success");
}
//6. 关闭连接,释放资源 先开后关
preparedStatement.close();
connection.close();
}
}
事务
要么都成功,要么都失败!
ACID原则:保证数据安全。
(原子性,一致性,隔离性,持久性)
开启事务
事务提交 commit()
事务回滚 rollback()
关闭事务
转账:
A:1000
B:1000
A减100 中间服务器断了 B加100 (A减少了 B没有增加)
Junit单元测试
依赖:
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
简单使用:
@Test注解只有在方法上使用,,只要加了这个注解的方法,就可以直接运行!
@Test
public void test() {
System.out.println("1324563");
}
搭建一个环境
public class TestJdbc3 {
public static void main(String[] args) throws Exception{
// 获取配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
// 1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
connection.setAutoCommit(false);
// 3. 编写sql
String sql1 = "update account set money = money-100 where name='李宇杰'";
connection.prepareStatement(sql1).executeUpdate();
String sql2 = "update account set money = money+100 where name='宇杰'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();
//6. 关闭连接,释放资源 先开后关
connection.close();
}
}
事务:
start transaction ;
update account set money = money-100 where name='李宇杰';
update account set money = money+100 where name='宇杰';
commit ;