admin管理员组文章数量:1607722
JavaWeb 2022.9.24
Java web
1、基本概念
1.1、前言
web开发
- web,网页的意思
- 静态web
- heml、css
- 提供给所有人看的数据始终不会发生变化!
- 动态web
- 淘宝、几乎所有的网站
- 童工给所有人看的数据始终会发生变化,每个人在不同的时间,不同的地点看到的信息各不相同!
在Java中,动态web资源开发的技术统称为JavaWeb;
1.2、web应用程序
web应用程序:可以提供浏览器访问的程序;
- a.html、b.html…多个web资源,这些web资源可以被外界访问,对外界提供服务;
- 你们能访问到的任何一个页面或者资源,都存在于 这个世界的某一个角落的计算机上。
- URL
- 这个统一的web资源会被放在同一个文件夹下,web应用程序–>Tomcaat:服务器
- 一个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页面无法动态更新,所有用户看到的都不是同一个页面
-
它可以与数据库交互(数据持久化:注册:商品信息)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mj8ysYYo-1665814142397)(C:\Users\WYX\AppData\Roaming\Typora\typora-user-images\image-20220924152523291.png)]
2、web服务器
2.1、技术讲解
ASP:
- 微软:国内最早流行的就是ASP;
- 在HTML中嵌入了VB的脚本,ASP+COM;
- 在ASP开发中,基本一个页面都有几千行的业务代码,页面极其混乱
- 维护成本高!
- C#
- IIS服务器
php
- PHP开发速度很快,功能很强大,跨平台,代码很简单(70%,WP)
- 无法承载大访问量的情况(局限性)
JSP/Servlet:
B/S:浏览和服务器
C/S : 客户端和服务器
-
sun公司主推的B/S架构
-
基于Java语言的(所有的大公司,或者一些开源的组件,都是用Java写的)
-
可以承载三高问题(高并发、高性能、高可用)问题带来的影响;
-
语法想ASP,ASP --> JSP,加强市场的强度
2.2、web服务器
服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息;
IIS
微软的;
Tomcat
Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 规范。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为比较流行的Web 应用服务器。
Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。对于一个初学web的人来说,它是最佳的选择
Tomcat 实际上运行JSP 页面和Servlet。Tomcat处理静态HTML的能力不如Apache服务器。
下载Tomcat:
- 安装 or 解压
- 了解配置文件及目录结构
- 这个东西的作用
3、Tomcat
3.1、安装Tomcat
3.2、Tomcat启动和配置
启动。关闭Tomcat
访问测试:http://localhost:8080
可能遇到的问题:
- 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程序,可以直接访问
- 没有:去DNS服务器找,找到的话就返回,找不到就返回找不到;、
- 可以配置环境变量(可选)
3.4、发布一个web网站
- 将自己写的网站,放到服务器(Tomcat)中指定的web应用的文件夹(webapps)下,就可以访问了
网站应该有的结构
3.5、tomcat启动可能会出现的问题
问题:
org.apache.catalina.LifecycleException: 协议处理器启动失败
Caused by: java.lang.IllegalArgumentException: AJP连接器配置secretRequired=“true”,但是属性secret确实空或者空字符 串,这样的组合是无效的。
解决方法:
-
将Connector标签注释掉,不适用AJP(还不知道是什么)的话,建议注释掉
<!-- 我自己注释掉的,建议注释掉 <Connector protocol="AJP/1.3" address="::1" port="8009" redirectPort="8443" /> -->
-
或者加上==secretRequired=“”==属性
<Connector protocol="AJP/1.3"
address="::1"
port="8009"
redirectPort="8443"
secretRequired="" />
4、什么是HTTP
HTTP(超文本传输协议)是一个简单的请求-响应协议,它通常运行再TCP之上
- 文本:html,字符串~…
- 超文本:图片、音乐、视频、定位…
- 80
Https:安全的
- 443
4.2、两个时代
- http1.0
- HTTP/1.0:客户端可以与web服务器连接后,只能获得一个web资源,断开连接
- http2.0
- HTTP/1.1:客户端可以与web服务器连接后,可以获得多个web资源
4.3、Http请求
- 客户端—发请求(Request)—服务器
百度:
Request URL: https://www.baidu.com/ 请求地址
Request Method: GET get方法/post方法
Status Code: 200 OK 状态码
Accept:text/html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en-US; 语言
Cache-Control: max-age=0
Connection: keep-alive
1、请求行
- 请求行中的请求方式:GET
- 请求方式:Get,Post。HEAD,DELETE…
- 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 编码
Content-Type: text/html 类型
1、响应体
Accept:告诉浏览器,它支持的数据类型
Accept-Encoding: 支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language: 告诉浏览器,它的语言环境
Cache-Control: 缓存控制
Connection: 告诉浏览器,请求完成是断开还是保持连接
HOST:主机
Refrush: 告诉客户端,多久刷新一次
Location:让网页重新定位
2、响应状态码
200:请求响应成功
3xx:请求重定向
- 重定向:你重新到我给你的新位置去;
4xx:找不到资源 404
- 资源不存在;
5xx:服务器代码错误 500 502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车的一瞬间到页面能够展示回来,经历了什么?
5、Maven
我为什么要学习这个技术?
-
在javaweb开发中,需要使用大量的jar包,我们需要手动去导入;
-
如何能够让一个东西自动帮我导入和配置这个jar包
由此,Maven诞生了!
5.1、Maven项目架构管理工具
我们目前用来就是方便导入jar包的!
Maven的核心思想:约定大于配置
- 有约束,不要去违反
Maven会规定好你该如何去编写我们的Java代码,必须按照这个规范来;
5.2、阿里云镜像
- 镜像:mirrors
- 作用:加速我们的下载
- 建议使用阿里云的镜像
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun/nexus/content/groups/public/</url>
</mirror>
5.3、本地仓库
在本地的仓库,远程仓库
建立一个本地仓库:localRepository
<localRepository>
D:\App\apache-maven-3.6.3\maven-repo
</localRepository>
5.4、Maven资源导出问题
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
6、Servlet
6.1、Servlet简介
- Servlet就是sun公司开发动态web的一门技术
- Sun在这些API中提供一个接口叫做:Servlet,如果你想开发一个Servlet程序,只需要完成两个小步骤:
- 编写一个类,实现Servlet接口
- 将开发好的java类部署到服务器中
把实现了Servlet接口的Java程序叫做Servlet
6.2、HelloServlet
Servlet接口在Sun公司有两个默认的实现类:HttpServlet,GenericServlet
-
构建一个普通的maven项目,删除src目录,将这个maven做为一个父项目
-
关于父子工程的理解:
父项目由的依赖子项目都会有
-
Maven环境优化
- 修改web.xml为最新的
- 将maven的结构搭建完整
-
编写一个servlet程序
-
编写一个普通类
-
实现Servlet接口,这里我们直接HttpServlet
public class HelloServlet extends HttpServlet { //由于get或者post只是请求实现的不同方式,可以相互调用,业务逻辑都一样 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("实行了doGet方法"); PrintWriter writer = resp.getWriter(); //响应流 writer.println("<h1>hello Servlet</h1>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
-
-
编写Servlet的映射
为什么需要映射:我们写的是JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中注册我们写的Servlet,还需给他一个浏览器能够访问的路径;
<!--web.xml中是配置我们web的核心应用--> <!--注册Servlet--> <servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.xing.servlet.HelloServlet</servlet-class> </servlet> <!--一个Servlet对应一个Mapping:映射--> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <!--请求路径--> <url-pattern>/helloServlet</url-pattern> </servlet-mapping>
-
配置tomcat
-
启动测试
6.3、Servlet原理
6.4、Mapping问题
-
一个Servlet可以指定一个映射路径
<servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.xing.servlet.HelloServlet</servlet-class> </servlet> <!--一个Servlet对应一个Mapping:映射--> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <!--请求路径--> <url-pattern>/helloServlet</url-pattern> </servlet-mapping>
-
一个Servlet可以指定多个映射路径
<servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.xing.servlet.HelloServlet</servlet-class> </servlet> <!--一个Servlet对应一个Mapping:映射--> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <!--请求路径--> <url-pattern>/helloServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <!--请求路径--> <url-pattern>/helloServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/helloServlet2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/helloServlet3</url-pattern> </servlet-mapping>
-
一个Servlet可以指定通用映射路径
<servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.xing.servlet.HelloServlet</servlet-class> </servlet> <!--一个Servlet对应一个Mapping:映射--> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <!--请求路径--> <url-pattern>/*</url-pattern> </servlet-mapping>
-
默认请求路径
<!--默认请求路径--> <servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.xing.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name <url-pattern>/*</url-pattern> </servlet-mapping>
-
指定一些后缀或者前缀等等…
<!--默认请求路径-->
<!--可以自定义后缀实现请求映射
注意点,*前面不能加项目映射的路径
servletHello/jfjfj.do-->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.xing.servlet.HelloServlet</servlet-class>
</servlet>
<!--一个Servlet对应一个Mapping:映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!--请求路径-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
6.优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;
6.5、ServletContext
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
1、共享数据
我在这个Servlet中保存的数据,可以在另外一个servlet中拿到;
public class HelloGetServlet 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;charset=utf-8");
resp.getWriter().println("名字 = " + username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
public class HelloSetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String username = "乔巴";
servletContext.setAttribute("username",username); //将数据保存到servletContext中
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
<servlet>
<servlet-name>setServlet</servlet-name>
<servlet-class>com.xing.servlet.HelloSetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>setServlet</servlet-name>
<url-pattern>/set</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getServlet</servlet-name>
<servlet-class>com.xing.servlet.HelloGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getServlet</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
2、获取初始化参数
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String url = servletContext.getInitParameter("url");
resp.getWriter().println(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<!--设置web初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
3、请求转发
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
System.out.println("ServletDemo04");
//请求转发,设置路径,传入请求和响应
servletContext.getRequestDispatcher("/url").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4、读取资源文件
Properties
- 在java目录下新建properties
- 在resources目录下新建properties
发现:都被打包到了同一个路径下:classes;我们俗称为classpath:
思路:需要一个文件流;
username = root
password = 123123
public class PropertiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
InputStream resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
resp.getWriter().println(properties.getProperty("username") + ":" + properties.getProperty("password"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6.6、HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
1、简单分类
负责向浏览器发送数据的方法
public ServletOutputStream getOutputStream() throws IOException;
public PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
public void setCharacterEncoding(String charset);
public void setContentLength(int len);
public void setContentLengthLong(long len);
public void setContentType(String type);
响应的状态码:
public static final int SC_CONTINUE = 100;
public static final int SC_SWITCHING_PROTOCOLS = 101;
public static final int SC_OK = 200;
public static final int SC_CREATED = 201;
public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
public static final int SC_NO_CONTENT = 204;
public static final int SC_RESET_CONTENT = 205;
public static final int SC_PARTIAL_CONTENT = 206;
public static final int SC_MULTIPLE_CHOICES = 300;
public static final int SC_MOVED_PERMANENTLY = 301;
public static final int SC_MOVED_TEMPORARILY = 302;
public static final int SC_FOUND = 302;
public static final int SC_SEE_OTHER = 303;
public static final int SC_NOT_MODIFIED = 304;
public static final int SC_USE_PROXY = 305;
public static final int SC_TEMPORARY_REDIRECT = 307;
public static final int SC_BAD_REQUEST = 400;
public static final int SC_UNAUTHORIZED = 401;
public static final int SC_PAYMENT_REQUIRED = 402;
public static final int SC_FORBIDDEN = 403;
public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
public static final int SC_REQUEST_TIMEOUT = 408;
public static final int SC_CONFLICT = 409;
public static final int SC_GONE = 410;
public static final int SC_LENGTH_REQUIRED = 411;
public static final int SC_PRECONDITION_FAILED = 412;
public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
public static final int SC_REQUEST_URI_TOO_LONG = 414;
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
public static final int SC_EXPECTATION_FAILED = 417;
public static final int SC_INTERNAL_SERVER_ERROR = 500;
public static final int SC_NOT_IMPLEMENTED = 501;
public static final int SC_BAD_GATEWAY = 502
public static final int SC_SERVICE_UNAVAILABLE = 503;
public static final int SC_GATEWAY_TIMEOUT = 504;
public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2、常见应用
-
向浏览器输出消息
-
下载文件
- 要获取下载文件的路径
- 下载的文件名是啥?
- 设置想办法让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileOutStream流写入到buffer缓冲区
- 使用OutputStream将缓冲区中的数据输出到客户端!
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 要获取下载文件的路径
String realPath = "D:\\Homework\\idea\\Amazing\\javaweb-study\\servlet-03-downloadFile\\src\\main\\resources\\header1.jpg";
// 2. 下载的文件名是啥?
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3. 设置想办法让浏览器能够支持下载我们需要的东西能够支持("Content-Disposition")下载我们需要的东西,中文文件名URLEncoder.encode,否则有可能乱码
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
// 4. 获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
// 5. 创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// 6. 获取OutputStream对象
ServletOutputStream outputStream = resp.getOutputStream();
// 7. 将FileOutStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
fileInputStream.close();
outputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3、验证码
public class ImgServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置让浏览器3秒自动刷新一次
resp.setHeader("refresh","3");
//在内存中创建一张图片
BufferedImage image = new BufferedImage(150,30,BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D graphics = (Graphics2D) image.getGraphics(); //画笔
//设置背景颜色
graphics.setColor(Color.WHITE);
graphics.fillRect(0,0,150,30);
//给图片写数据
graphics.setColor(Color.BLUE);
graphics.setFont(new Font(null,Font.BOLD,30));
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,"jpeg",resp.getOutputStream());
}
//生成一个8位数的随机数字
public String makeNum(){
Random random = new Random();
//生成一个99999999以内的随机数字
String num = random.nextInt(99999999) + "";
StringBuffer sb = new StringBuffer(num);
while (sb.length() < 8){
sb.append("0");
}
return sb.toString();
}
}
4、实现重定向
常见场景:
- 用户登录
public void sendRedirect(String location) throws IOException;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
重定向原理:
resp.setHeader("Location","/download/img");
resp.setStatus(302);
*/
resp.sendRedirect("/download/img");
}
面试题:请你聊聊重定向和转发的区别?
相同点:
- 页面都会实现跳转
不同点:
- 请求转发的时候,url不会产生变化
- 重定向时候,url地址栏会发生变化
5、write() 和 print() 的区别
HttpServletResponse.getWriter() 中的write()和print()方法
print
response.getWriter().print(),不仅可以打印输出文本格式的(包括html标签),还可以将一个对象以默认的编码方式转换为二进制字节输出
write
response.getWriter().write() ,只能打印输出文本格式的(包括html标签),不可以打印对象。
6.7、HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息
获取参数,请求转发
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));
//请求转发
req.getRequestDispatcher("/success.jsp").forward(req,resp);
7、Cookie、Session
7.1、会话
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话;
有状态会话:一个同学来过教师,下次再来教室,我们会知道这个同学曾经来过,称之为有状态会话;
客户端 服务端
- 服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了;cookie
- 服务器登记你来过了,下次你来的时候服务器来匹配你; session
7.2、保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务器技术,利用这个技术。可以保存用户的会话信息。我们可以把信息或者数据放在Session中!、
常见:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!
7.3、Cookie
- 从请求中拿到cookie信息
- 服务器响应给客户端cookie
//从客户端获得cookie
Cookie[] cookies = req.getCookies(); //客户端可能有多个cookie
//添加cookie,cookie中的值不能有空格,否则服务端响应给客户端会报错
Cookie cookie = new Cookie("lastTime",Long.toString(System.currentTimeMillis()));
//服务端给客户端添加一个cookie
resp.addCookie(cookie);
cookie:一般会保存在本地的用户目录下 Appdata
一个网站cookie是否存在上限!聊聊细节问题
- 一个Cookie只能保存一个信息;
- 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
- Cookie大小有限制4kb;
- 300个cookie浏览器上限
删除Cookie:
- 不设置有效期,关闭会话就删除了
- 设置有效期为0,立马过期
编码解码:
//编码
Cookie cookie = new Cookie("username", URLEncoder.encode("乔巴"));
//解码
out.println("用户名:" + URLDecoder.decode(cookie.getValue()));
7.4、Session(重点)
什么是Session:
- 服务器会给每一个用户(浏览器)创建一个Session对象;
- 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在
- 用户登录之后,整个网站它都可以访问!–>保存用户的信息;保存购物车信息…
Session和cookie的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
- Session把用户的数据写到用户独占Session中,服务端保存(保存重要的信息,减少服务器资源的浪费)
- Session对象由服务器创建
使用场景:
- 保存一个登录用户的信息
- 购物车信息
- 在整个网站中经常会使用的数据,我们将它保存在Session中;
对Session的疑问:(我自己的疑问)
- 为什么关闭浏览器后就访问不到以前在Session中保存的数据了呢?
- Session中的数据保存在服务器内存中,而JSESSIONID保存在客户端的cookie中,关闭浏览器后cookie中的JSESSIONID就丢失了,再次打开浏览器访问服务器一个页面后会重新创建一个JSESSIONID,所以访问不到之前的数据了,之前的Session会在默认的失效时间过后失效(Tomcat中Session默认失效时间为30分钟)
- Session是何时创建的
- 当浏览器第一次访问服务器一个页面之后由服务器创建的,并使用特殊算法算出一个Session的ID(JSESSIONID),以Cookie的方式保存在客户端中,而这个JSESSIONID在随后的请求中会被用来获得已经创建的Session;在Session被创建之后,就可以调用Session的相关方法往Session中增加内容了,而这些内容只会保存在服务器中,响应给客户端的只有JSESSIONID;
- 为什么同一个浏览器的不同页面可以访问同一个session
- session被创建会以cookie的方式保存在客户端的每一个页面,而不单单是只保存在你请求的那个页面
使用Session:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("username","乔巴");
//获取Session的ID
String sessionId = session.getId();
//判断Session是不是新创建的
if (session.isNew()){
System.out.println("这个Session是新创建的");
}else{
out.write("SessionId:" + sessionId);
}
//Session创建的时候做了什么事情
//Cookie cookie = new Cookie("JSESSIONID", sessionId);
//resp.addCookie(cookie);
}
//设置编码
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取session数据
HttpSession session = req.getSession();
String username = (String) session.getAttribute("username");
resp.getWriter().write("名字:" + username);
//手动注销Session
req.getSession().invalidate();
会话自动过期:web.xml配置
<!--session配置-->
<session-config>
<!--设置session默认过期时间,单位为分钟-->
<session-timeout>1</session-timeout>
</session-config>
8、JSP
8.1、什么是JSP
Java Server Pages : Java服务端页面,也和Servlet一样,用于动态Web技术!
最大的特点:
- 写JSP就像在写HTML
- 区别
- HTML只给用户提供静态的数据
- JSP页面中可以嵌入JAVA代码,为用户提供数据
8.2、JSP原理
思路:JSP到底怎么执行的
-
代码层面没有任何问题
-
服务器内部工作
tomcat中有一个workmulu;
IDEA中使用Tomcat的会在IDEA中生成一个work目录
发现页面转换成为Java程序
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet
JSP最终也会被转换成为一个Java类 !
JSP本质上就是一个Servlet
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
JSPService
public void _jspService(){
}
-
判断请求
-
内置一些对象
final javax.servlet.jsp.PageContext pageContext; //session javax.servlet.http.HttpSession session = null; //applicationContext final javax.servlet.ServletContext application; //页面上下文 final javax.servlet.ServletConfig config; //config javax.servlet.jsp.JspWriter out = null; //out final java.lang.Object page = this; //page:当前 HttpServletRequest request //请求 HttpServletResponse response //响应
-
输出页面前增加的代码
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;
-
以上的这些个对象我们可以在JSP页面中直接使用!
在JSP页面中;
只要是JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为
out.write("<html>\n");
这样的格式,输出到前端!
8.3、JSP基础语法
任何语言都有自己的语法,JAVA中有。JSP作为一个Java技术的一种应用,它拥有一些自己扩充的语法,Java所有语法都支持!
Jsp表达式
<%--Jsp表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
<%= new java.util.Date()%>
jsp脚本片段
写的java代码都是在_jspService()方法里面的
<%--jsp脚本片段 --%>
<%
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
out.print("<h1>" + sum + "</h1>");
%>
脚本片段的的再实现
JSP声明
就是作用域是全局的
<%! %>
JSP声明:会被编译到JSP生成Java的类中!其他的,就会被生成到——jspService()方法中!
在JSP中嵌入java代码即可!
JSP的注释,不会再客户端显示,HTML就会!
8.4、JSP指令
<%--@include会将了两个页面合二为一 --%>
<%@ include file="common/footer.jsp"%>
<h1>我是文本内容</h1>
<%@ include file="common/header.jsp"%>
<hr>
<%--jsp标签
jsp:include:拼接页面,本质还是三个
--%>
<jsp:include page="/common/header.jsp"/>
<h1>我是文本内容</h1>
<jsp:include page="/common/footer.jsp"/>
<%--定制错误页面,如果报500错误跳到这个页面--%>
<%@ page errorPage="/error/500.jsp" %>
8.5、9大内置对象
- PageContext 存东西
- Resquest 存东西
- Response
- Session 存东西
- Application 【ServletContext】 存东西
- config 【ServletConfig】
- out
- page
- exception
原理:就是pageContext.setAttribute()设置了作用域
//abstract public void setAttribute(String name, Object value, int scope);
//可以设置作用域
//public static final int PAGE_SCOPE = 1;
//public static final int REQUEST_SCOPE = 2;
//public static final int SESSION_SCOPE = 3;
//public static final int APPLICATION_SCOPE = 4;
pageContext.setAttribute("scope","scope",PageContext.PAGE_SCOPE);
//abstract public void setAttribute(String name, Object value, int scope);
//可以设置作用域
// public static final int PAGE_SCOPE = 1;
//public static final int REQUEST_SCOPE = 2;
//public static final int SESSION_SCOPE = 3;
//public static final int APPLICATION_SCOPE = 4;
//pageContext.setAttribute("scope","scope",PageContext.PAGE_SCOPE);
pageContext.setAttribute("name1","乔巴1号"); //保存的数据只在一个页面中有效
request.setAttribute("name2","乔巴2号"); //保存的数据只在一个请求中有效,请求转发会携带这个数据
session.setAttribute("name3","乔巴3号"); //保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","乔巴4号"); //保存的数据只在服务器中有效,从打开服务器到关闭服务器
request: 客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完就没用了!
session: 客户端向服务器发送请求,产生的数据,用户用完 一会还有用,比如:购物车;
application: 客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据;
8.6、JSP标签、JSTL标签、EL表达式i
<!--JSTL表达式依赖-->
<!-- https://mvnrepository/artifact/javax.servlet.jsp.jstl/jstl-api -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!--标签库-->
<!-- https://mvnrepository/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
EL表达式:${}
- 获取数据
- 执行运算
- 获取web开发的常用对象
JSP标签
<% request.setCharacterEncoding("utf-8");%>
<jsp:forward page="/jspTag2.jsp">
<jsp:param name="username" value="乔巴"></jsp:param>
<jsp:param name="age" value="13"/>
</jsp:forward>
名字:<%= request.getParameter("username")%><br>
年龄:<%= request.getParameter("age")%>
JSTL表达式
JSTL标签库使用步骤:
- 引入对应的taglib
- 使用其中的方法
- 在Tomcat也需要引入jstl的包,否则也会报错
9、JavaBean
实体类
JavaBean有特定的写法:
- 必须要有一个无参构造
- 属性必须私有化
- 必须有对应的get/set方法;
一般用来和数据库的字段做映射 ORM;
ORM :对象关系映射
- 表 --> 类
- 字段 —> 属性
- 行记录 --> 对象
10、MVC三层架构
什么是MVC:Model view Controller 模型、视图、控制器
10.1、早些年
用户直接访问控制层,控制层就可以直接操作数据可;
Servle ---CRUD ---> 数据库
弊端 :程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
10.2、MVC三层架构
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD (Dao)
View
- 展示数据
- 提供链接发起Servlet请求 (a,form,img…)
Controller (Servlet)
- 接收用户的请求:(req:请求参数、Session信息…)
- 交给业务层处理对应的代码
- 控制视图的跳转
登录--->接受用户的登录请求---->处理用户的请求(获取用户登录的参数,username,password)--->交给业务层处理登录业务(判断用户名密码是否正确:事务)--->Dao层查询用户名和密码是否正确--->数据库
11、Filter(重点)
Filter:过滤器,用来过滤网站的数据;
- 处理中文乱码
- 登录验证…
Filter开发步骤:
-
导包
-
编写过滤器
-
导包不要导错了
-
实现Filter接口,重写对应的方法即可
public class CharsetEncodingFilter implements Filter{ //初始化:web服务器启动,就已经初始化了,随时等待过滤器对象出现! public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharsetEncodingFilter初始化完毕"); } //chain : 链 /* 1.过滤中的所有代码,在过滤特定请求的时候都会执行 2.必须要让过滤器继续同行 chain.doFilter(request,response); */ 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("过滤前"); chain.doFilter(request,response); //让我们的请求继续走,如果不写,程序到这里就被拦截停止了! System.out.println("过滤后"); } //销毁:web服务器关闭的时候,过滤会销毁 public void destroy() { System.out.println("CharsetEncodingFilter销毁"); } }
-
在web.xml中配置 Filter
<filter> <filter-name>charsetEncoding</filter-name> <filter-class>com.xing.filter.CharsetEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>charsetEncoding</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
-
12、监听器
实现一个监听器的接口;(有N种)
-
编写一个监听器
实现监听的接口
//统计网站在线人数 session public class SessionListen implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer count = (Integer) servletContext.getAttribute("onlineCount"); if (count == null){ servletContext.setAttribute("onlineCount",1); }else { servletContext.setAttribute("onlineCount",count + 1); } } public void sessionDestroyed(HttpSessionEvent se) { } }
-
web.xml中注册监听器
<!--注册监听器--> <listener> <listener-class>com.xing.listen.SessionListen</listener-class> </listener>
-
看情况是否使用
13、过滤器、监听器常见应用
监听器:GUI编程中常用
用户登录之后才能进入主页 ! 用户注销后就无法进入
- 用户登录之后,向Session中放入用户的数据
- 进入主页的时候要判断用户是否已经登录
stem.out.println(“过滤前”);
chain.doFilter(request,response); //让我们的请求继续走,如果不写,程序到这里就被拦截停止了!
System.out.println(“过滤后”);
}
//销毁:web服务器关闭的时候,过滤会销毁
public void destroy() {
System.out.println("CharsetEncodingFilter销毁");
}
}
```
-
在web.xml中配置 Filter
<filter> <filter-name>charsetEncoding</filter-name> <filter-class>com.xing.filter.CharsetEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>charsetEncoding</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
12、监听器
实现一个监听器的接口;(有N种)
-
编写一个监听器
实现监听的接口
//统计网站在线人数 session public class SessionListen implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer count = (Integer) servletContext.getAttribute("onlineCount"); if (count == null){ servletContext.setAttribute("onlineCount",1); }else { servletContext.setAttribute("onlineCount",count + 1); } } public void sessionDestroyed(HttpSessionEvent se) { } }
-
web.xml中注册监听器
<!--注册监听器--> <listener> <listener-class>com.xing.listen.SessionListen</listener-class> </listener>
-
看情况是否使用
13、过滤器、监听器常见应用
监听器:GUI编程中常用
用户登录之后才能进入主页 ! 用户注销后就无法进入
- 用户登录之后,向Session中放入用户的数据
- 进入主页的时候要判断用户是否已经登录
本文标签: JavaWeb
版权声明:本文标题:JavaWeb 2022.9.24 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728532073a1162244.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论