JavaWeb
JavaWeb
摘录自狂神相关课程略有补充
1.web基本概念
1.1.基本概念
web 开发:
- web ,网页的意思,www.baidu.com
- 静态web
- html,css,
- 提供给所有人看的数据始终不会发生变化!
- 动态web
- 提供给所有人看的数据会发生变化,每个人在不同的时间、不同的地点、看到的信息各不相同。
- 淘宝,几乎所有的网站
- 技术栈:Servlet/Jsp、Asp、Php
在java 中,动态web资源开发的技术通常为JavaWeb;
1.2.Web应用程序
web应用程序:可以提供浏览器访问的程序;
- a.html、b.html …多个web资源,这些web资源可以被外界访问,对外界提供服务;
- 你们能访问到的任何一个页面或者资源,都存在于这个世界的某一个角落的计算机上
- URL
- 这个同一的web资源会被放在同一文件夹下,web应用程序—-》Tomcat 服务器
- 一个web应用由多部分组成(静态web,动态web)
- html,css,js
- Jsp,Servlet
- Java程序
- jar包
- 配置文件(Properties)
web应用程序编写完毕后,若想提供给外界访问:需要一个服务器来统一管理;
1.3.静态Web
*.htm, *.html 这些都是网页的后缀,如果服务器上一直存在这些东西,
静态web存在的缺点
- Web 页面 无法动态更新,所有用户看到的是同一页面
- 轮播图,点击特性:伪动态
- JavaScript
- VBScript
- 它无法和数据库交互(数据无法持久化,用户无法交互)
1.4.动态web
页面会动态展示:“Web 的页面展示效果因人而异”;
根据不同的输入与操作实现不同的展示效果。
缺点:
- 假如服务器的动态web资源出现了错误,我们需要重新编写我们的后台程序
- 停机维护
优点:
- Web 页面 可以动态更新,所有用户看到的都不是同一页面
- 它可以和数据库交互(数据持久化:注册、商品信息)
新手村:—-》魔鬼训练(分析原理,看源码) —-》PK场
2.web服务器
2.1.技术讲解
ASP:
- 微软:国内最流行的就是ASP;
- 在html中嵌入VB脚本,ASP+COM
- 在ASP开发中,基本一个页面都有几千行的业务代码,页面极其换乱。
- 维护成本考
- C#
- IIS
PHP:
- PHP开发速度快,功能很强大,跨平台,代码很简单(70%)
- 无法承载大访问量的情况(有局限性)
JSP/Servlet:
-
B/S:浏览器和服务器
-
C/S:客户端和服务器、
-
B/S:程序完全部署在服务器上,用户通过服务器来访问应用程序,这是基于Internet的产物。
-
sun公司主推的B/S架构
-
基于java语言的(所有的大公司,或者一些开源的组件,都是用java写的)
-
可以承载三高问题带来的影响;
-
B/S结构中,浏览器端与服务器端采用请求/响应模式
-
2.2.web服务器
服务器是一种被动的操作,用户处理用户的一些请求和给用户一些响应信息;
IIS
微软的
用来跑ASP程序的,windows中自带的
Tomcat
Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。
Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。
下载:
- 安装 or 解压
- 了解配置文件和目录
- 这个东西的作用
3.Tomcat
3.1.安装Tomcat
tomcat官网:
3.2.tomcat启动和配置
文件夹作用
启动、关闭tomcat
访问测试
http://localhost:8080/
可以配置启动的端口号
- http: 80
- https:443
- mysql:3306
- redis:6379
- tomcat默认:8080
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
可以配置主机的名称
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
完整配置文件
<?xml version="1.0" encoding="UTF-8"?>
<Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
<GlobalNamingResources>
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
<Service name="Catalina">
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Engine name="Catalina" defaultHost="localhost">
<Realm className="org.apache.catalina.realm.LockOutRealm">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
</Engine>
</Service>
</Server>
3.3.高难度面试题
请你谈谈网站是如何访问的!
-
输入一个域名;点击回车
-
客户端在发送请求之前,会
先去检查 本机的 hosts 文件
有没有这个域名的映射
- 有: 直接返回对应的ip地址,在这个地址中,有我们需要访问的web程序,可以直接访问
127.0.0.1 www.bloghut.cn - 没有:去DNS 服务器 找到的话就返回, 找不到就返回找不到
- 有: 直接返回对应的ip地址,在这个地址中,有我们需要访问的web程序,可以直接访问
3.4.发布一个web网站
将自己写的网站放到服务器(Tomcat) 中指定的web应用的文件夹(webapps)下,就可以访问了
网站应该有的结构
--webapps :Tomcat服务器的web目录
- ROOT
- bloghut : 网站的目录名
- WEB_INF
- classes : java程序
- lib : web 应用依赖的jar包
- web.xml : 网站的配置文件
- index.html 默认的首页
- static
-css
- style.css
-js
-img
4.Http
4.1 什么是Http
超文本传输协议(Hyper Text Transfer Protocol,HTTP)是一个简单的;请求-响应协议,它通常运行在TCP之上。
无状态协议
- 文本:html,字符串,~
- 超文本:图片,音乐,视频,定位,地图…
- 80
https:安全的
- 443
4.3.2.两个时代
http 1.0
- http/1.0:客户端可以与web服务器连接后,只能获得一个web资源,断开连接
http 2.0
- http/1.1:客户端可以与web服务器连接后,可以获得多个web资源。
4.3.Http请求
客户端—–发请求(Request)——-服务器
百度:
Request URL: https://www.baidu.com/ --请求地址
Request Method: GET --请求方式
Status Code: 200 OK --状态码
Remote Address: 14.215.177.38:443 --远程地址
Accept: text/html --
Accept-Encoding: gzip, deflate, --编码
Accept-Language: zh-CN,zh;q=0.9 --
Connection: keep-alive --
Cookie:
Host: www.baidu.com
4.3.1.请求行
- 请求行中的请求方式:GET
- 请求方式:GET、POST、HEAD、DELETE、PUT
- get :一次请求能够携带的参数比较少,大小限制,会在浏览器的url 地址栏显示内容,不安全,但高效。
- post:一次请求能够携带的参数没有限制,大小没有限制,不会在浏览器的url 地址栏显示内容,安全,但不高效。
4.3.2.请求头
Accept --告诉浏览器它所支持的数据类型
Accept-Encoding --告诉浏览器支持哪种编码格式 GBK、UTF-8 、GB2312
Accept-Language --告诉浏览器,它的语言环境
Cache-Control --缓存控制
Connection --告诉浏览器,请求完成是断开还是保持连接
HOST: --主机
4.4.Http响应
服务器—–响应(response)—–客户端
Cache-Control: private --缓存控制
Connection: keep-alive --连接
Content-Encoding: gzip --编码
Content-Type: text/html;charset=utf-8 --类型
Date: Fri, 03 Sep 2021 15:18:56 GMT --当前时间
Expires: Fri, 03 Sep 2021 15:18:23 GMT --当前时间
Set-Cookie: BDSVRTM=0; path=/ -- cookie 会话技术
Set-Cookie: BD_HOME=1; path=/
Set-Cookie: H_PS_PSSID=
4.4.1.响应体
Accept --告诉浏览器它所支持的数据类型
Accept-Encoding --告诉浏览器支持哪种编码格式 GBK、UTF-8 、GB2312
Accept-Language --告诉浏览器,它的语言环境
Cache-Control --缓存控制
Connection --告诉浏览器,请求完成是断开还是保持连接
HOST: --主机
Refresh: --告诉客户端,多久刷新一次
Location --让网页重新定位
4.4.2.响应状态码
- 200 请求响应成功
- 4xx 找不到资源 404
- 资源不存在
- 3** 请求重定向
- 重定向:你重新到我给你的新位置去
- 5xx 服务器代码错误 500
- 502 网关错误
4.5.常见面试题
当你的浏览器中地址栏输入地址并回车的一瞬间到页面能够展示回来,经历了什么?
5.Maven
我为什么要学习这个?
- 在JavaWeb开发中需要使用大量的jar包,我们手动导入;
- 如何能够让一个东西帮我导入和配置这些jar包
- 由此maven诞生了
5.1.Maven项目架构管理工具
我们目前用来就是方便导入jar包的!
maven的核心思想:约定大于配置
有约束,不要去违反
maven 会规定好你该如何去编写我们的Java代码,必须按照这个规范来;
5.2.下载安装Mavne
https://maven.apache.org/
下载完成后解压即可
目录结构
- bin 放一些可执行文件
- boot 该目录只包含一个jar文件,plexus-classworlds-2.5.2.jar。maven就是用它来加载自己的类库的。
- conf 该目录下最重要的是settings.xml 文件,它主要用于全局的定制maven的行为
- lib 该目录包含了maven运行时的java类库
5.3.配置环境变量
在我们的系统环境变量中
配置如下信息:
- M2_HOME maven目录下的bin目录
- MAVEN_HOME maven的目录
- 在系统的path 中配置 MAVEN_HOME
测试是否安装成功
5.4.阿里云镜像
- 镜像:mirros
作用:加速我们的下载 - 国内建议使用阿里云
<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:\Program Files (x86)\maven_repository</localRepository>
5.6.在idea中使用maven
- 启动idea
- 创建一个maven项目
idea中的maven设置
经常在idea中出现一个问题,就是项目自动创建完成后, 这个maven home 会使用idea默认的,我们如果发现了这个问题,手动改为本地。
5.7.创建一个普通的maven项目
这个只有web的项目才有
5.8.标记文件夹功能
5.9.在idea中配置tomcat
解决警告问题
为什么会有这个问题,我们访问一个网站,需要指定一个文件夹的名字
这个过程叫虚拟路径映射
5.10.pom文件
pom.xml 是maven的 核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--maven 的版本和头文件-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--公司域名-->
<groupId>cn.bloghut</groupId>
<!--项目名-->
<artifactId>demo1</artifactId>
<!--版本-->
<version>1.0-SNAPSHOT</version>
<!--项目的打包方式
jar:java应用
war:javaweb应用
-->
<packaging>war</packaging>
<name>demo1 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<!--配置-->
<properties>
<!--项目的默认构建编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--编码版本-->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!--项目依赖-->
<dependencies>
<!--具体依赖的jar包配置文件-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--项目构建用的东西-->
<build>
<finalName>demo1</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
6.Servlet
Servlet
Ajax
Json
Xml
6.1.Servlet 简介
Servlet 就是sun公司开发动态web的一门技术
sun 在这些API 中提供了一个接口:Servlet,如果你想开发一个Servlet 程序,只需要完成两个步骤
- 编写一个类,实现Servlet 接口
- 把开发号好的Java类部署到服务器中
把实现了Servlet接口的Java 程序叫做:Servlet
6.2.HelloServlet
Servlet 接口有两个默认的实现类:HttpServlet、GenericServlet
关于mavne 父子工程的理解
父项目中会有
<modules>
<module>servlet-01</module>
</modules>
子项目中会有
<parent>
<artifactId>servlet</artifactId>
<groupId>cn.bloghut</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
父项目中的jar包 子项目可以直接使用
子项目中的jar包 父项目不能使用
Zi extends Fu
编写一个普通类,实现Servlet接口,这里我们直接继承httpServlet
public class HelloServlet extends HttpServlet {
}
public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同的方法,可以相互调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ServletOutputStream sos = resp.getOutputStream();
PrintWriter writer = resp.getWriter();//响应流
writer.println("hello,Servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
6.3.编写Servlet的映射
为什么需要映射:我们写的Java程序,但是要通过浏览访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需要给他一个浏览器能够访问的路径。
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
配置tomcat
测试
在servlet3.0以后,我们可以不用再web.xml里面配置servlet,只需要加上@WebServlet注解就可以修改该servlet的属性了。
@WebServlet 注解的属性
@WebServlet 用于将一个类声明为 Servlet,该注解会在部署时被容器处理,容器根据其具体的属性配置将相应的类部署为 Servlet。该注解具有下表给出的一些常用属性。
属性名 | 类型 | 标签 | 描述 | 是否必需 |
---|---|---|---|---|
name | String | 指定 Servlet 的 name 属性。 如果没有显式指定,则取值为该 Servlet 的完全限定名,即包名+类名。 | 否 | |
value | String[ ] | 该属性等价于 urlPatterns 属性,两者不能同时指定。 如果同时指定,通常是忽略 value 的取值。 | 是 | |
urlPatterns | String[ ] | 指定一组 Servlet 的 URL 匹配模式。 | 是 | |
loadOnStartup | int | 指定 Servlet 的加载顺序。 | 否 | |
initParams | WebInitParam[ ] | 指定一组 Servlet 初始化参数。 | 否 | |
asyncSupported | boolean | 声明 Servlet 是否支持异步操作模式。 | 否 | |
description | String | 指定该 Servlet 的描述信息。 | 否 | |
displayName | String | 指定该 Servlet 的显示名。 | 否 |
6.4.Servlet 原理
Servlet 是由web服务器调用,web服务器在收到浏览器请求之后,会调用相关API对请求处理。
servlet生命周期
-
创建一个请求对象,一个响应对象,调用service()方法
-
当不需要servlet或者服务器关闭的时候,调用destroy()方法,销毁servlet实例
6.5.Mapping 问题:
一个请求(Servlet)可以指定一个映射路径
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
一个请求(Servlet)可以指定多个映射路径
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello3</url-pattern>
</servlet-mapping>
一个请求(Servlet)可以指定通用映射路径
<!--默认请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
指定一些后缀或者前缀等
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;
6.6.ServletContext
web容器在启动的时候,它会为每个web程序都创建一个ServletContext对象,它代表了当前的web应用。
6.6.1.共享数据
我在这个Servlet中保存的数据
放置数据的Servlet
需要一个放置数据的类,一个读取数据的类。
/**
* @author by
* @classname HelloServlet
* @description 放置数据
* @date 2021/9/11 14:23
*/
public class setData extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello");
ServletContext servletContext = this.getServletContext();
String username = "闲言";//数据
servletContext.setAttribute("username",username);//将一个数据保存在ServletContext中 名为:username 值为 闲言
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
读取数据的Servlet
/**
* @author by
* @classname GetServlet
* @description 获取数据
* @date 2021/9/16 21:32
*/
public class GetData extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.write(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
6.6.2获取初始化参数
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/school</param-value>
</context-param>
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取上下文对象
ServletContext context = this.getServletContext();
//获取初始参数
String url = context.getInitParameter("url");
System.out.println("url: "+url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
6.6.3 请求转发
路径不会发生变化
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
//请求转发 /get 转发的路径
RequestDispatcher dispatcher = context.getRequestDispatcher("/get");
//调用forward 实现请求转发
dispatcher.forward(req,resp);
// z
}
6.6.4 读取配置文件
Properties
在resources 目录下新建properties
在java 目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath;
思路:需要一个文件流
properties文件
username=xy123
password=123
代码
通过Context读取配置文件
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream stream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/bloghut/servlet/aa.properties");
//通过Context读取配置文件
// InputStream stream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties pt = new Properties();
pt.load(stream);
String username = pt.getProperty("username");
String password = pt.getProperty("password");
resp.getWriter().println(username+":"+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
效果
maven资源导出失败问题
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
6.7.HttpServletResponse
web服务器接收到客户端的http请求,会针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletRespoonse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
6.7.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 void setDateHeader(String name, long date);
public void addDateHeader(String name, long date);
public void setHeader(String name, String value);
public void addHeader(String name, String value);
public void setIntHeader(String name, int value);
public void addIntHeader(String name, int value);
响应的状态码常量
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_ACCEPTED = 202;
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_NOT_FOUND = 404;
public static final int SC_METHOD_NOT_ALLOWED = 405;
public static final int SC_NOT_ACCEPTABLE = 406;
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;
6.7.1.常见应用
1.向浏览器输出消息
2.下载文件
2.1.要获取文件的路径
2.2下载的文件名是啥
2.3设置想办法让浏览器能够支持下载我们需要的东西
2.4获取下载文件的输入流
2.创建缓冲区
2.5获取OutputStream对象
2.6将FileOutputStream流写入到buff缓冲区
2.7使用OutputStream将缓冲区中的数据输出到客户端!
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//要获取文件的路径
// String realPath = this.getServletContext().getRealPath("/1.png");
String realPath = "G:\\JavaWeb\\狂\\servlet\\response-2\\target\\classes\\1.png";
System.out.println("下载路径:" + realPath);
//下载的文件名是啥
String fileName = realPath.substring(realPath.lastIndexOf("//") + 1);
//设置想办法让浏览器能够支持下载我们需要的东西
//中文文件名URLEncoder.encode 编码,否则可能乱码
resp.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));
//获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
//创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//将FileOutputStream流写入到buff缓冲区
//使用OutputStream将缓冲区中的数据输出到客户端!
while ((len = in.read(buffer)) > 0) {
out.write(buffer,0,len);
}
out.close();
in.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
验证码功能
验证码怎么来的?
1.前端实现
2.后端实现,需要用到Java图片类,生成一个图片
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器3秒自动刷新一次
resp.setHeader("refresh", "3");
//在内存中创建一个图片
BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D graphics = (Graphics2D) bufferedImage.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(makeNumber(),0,20);
//告诉浏览器器,这个请求用图片的方式打开
resp.setContentType("image/png");
//网站存储缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNumber() {
Random random = new Random();
String str = random.nextInt(9999) + "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4 - str.length(); i++) {
sb.append("0");
}
return sb.toString() + str;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
实现重定向
B一个web资源收到客户端A请求后,B他会通知客户端去访问另一个web资源,这个过叫重定向。
用户登录
public void sendRedirect(String location) throws IOException;
测试
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
resp.setHeader("Location","/r2/img");
resp.setStatus(302);
*/
resp.sendRedirect("/r2/img");//重定
}
面试题:请你聊聊重定向和转发的区别?
- 相同点
页面都会实现跳转 - 不同点
请求转发的时候,url不会产生变化
重定向的时候,url地址栏会发生变化
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//出来请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username:"+username+" password:"+password);
//重定向一定要注意:“路径问题”,否则404
resp.sendRedirect("/r2/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
页面提交过来的HTTP请求包含了参数,放在URL里面了,tomcat自动解析封装在request对象里,再调用service方法,request可以根据键得到传过来的值
6.8.HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest中的方法,获取客户端的所有信息。
获取前端传递的参数
请求转发
1.转发时”/“代表的是本应用程序的根目录 重定向时”/”代表的是webapps目录
2.getRequestDispatcher分成两种,可以用request调用,也可以用getServletContext()调用 不同的是request.getRequestDispatcher(url)的url可以是相对路径也可以是绝对路径。而this.getServletContext().getRequestDispatcher(url)的url只能是绝对路径。
转发是一个web应用内部的资源跳转
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+" : "+password+" :"+ Arrays.toString(hobbys));
//通过请求转发
//这里的 / 代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
面试题:请你聊聊重定向和转发的区别?
- 相同点
页面都会实现跳转 - 不同点
请求转发的时候,url不会产生变化
重定向的时候,url地址栏会发生变化
7.Cookie/Session详解
7.1.会话
会话:用户打开一个浏览器,点击了很多连接,访问多个web资源,关闭浏览器,这个过程可以称之为会话。
有状态会话:
一个同学来过教室,下次再来教室,我们会知道这个同学,之前来过
举例:
你能怎么证明你是湾大的学习?
你 湾大
1.发票 湾大给你发票
2.学校登记 湾大标记你来过了
一个网站怎么证明你来过?
客户端 服务端
1.服务端给客户端一个cookie(信件),客户端下次访问服务端带上 信件 就可以了;cookie
2.服务器登记你来过了,下次你来的时候我来匹配你;session
第一次访问,服务器给客户端发送一个cookie
发了之后,每次请求都会带上cookie
7.2.保存会话的两种技术
cookie
客户端技术(响应,请求)
session
服务器技术,利用整个技术,可以保存用户的会话信息?我们可以把信息或者数据放在session中!
常见场景:
网站登录之后,你下次不用再登录了,第二次访问直接上去了!
7.3.Cookie
1.从请求中拿cookie信息
2.服务器响应给客户端cookie信息
Cookie的常用方法
Cookie[] cookies = req.getCookies(); //获取所有cookie信息
cookie.getName() //获取cookie的名称
cookie.getValue(); //获取cookie的值
//创建cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
cookie.setMaxAge(24 * 60 * 60); //设置cookie的有效期
123456
cookie:一般会报错在本地的用户目录下appdata;
一个网站的cookie是否存储上限!聊聊细节问题
- 一个Cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
- cookie大小有限制4kb
- 上限大概为300个(浏览器上限)
删除cookie
- 不设置有效期,关闭浏览器,自动失效;
- 设置有效期时间为0
编码解码:
URLEncoder.encode("闲言","utf-8")
URLDecoder.decode(cookie.getValue(),"UTF-8")
7.4.Session(重点)
什么是session:
- 服务器会给每一个用户(浏览器)创建一个session对象;
- 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
- 用户登录之后,整个网站它都可以访问!–》保存用户的信息,保存购物车的信息…
Session和Cookie的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
- Session 把用户的数据写到独占Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
- Session对象由服务创建
使用场景:
- 保存一个登录用户的信息;
- 购物车信息;
- 在整个网站中经常会使用的数据,我们将它保存在session中
使用session
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//给session存东西
session.setAttribute("name","闲言");
Person person = new Person(18, "闲言博客");
session.setAttribute("person",person);
//获取session的Id
String id = session.getId();
//判断session是不是新创建
if (session.isNew()){
resp.getWriter().write("session 创建成功,ID"+id);
}else {
resp.getWriter().write("session 已经存在了"+id);
}
//session创建的时候做了什么事情
// Cookie cookie = new Cookie("JSESSIONID", id);
// resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
从session中获取数据
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//从session中获取数据
String name = (String)session.getAttribute("name");
Person person = (Person)session.getAttribute("person");
System.out.println(name);
System.out.println(person);
}
调用invalidate()方法注销session
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
session.removeAttribute("name");
//注销
session.invalidate();
}
会话自动过期
在web.xml中进行一下配置
<session-config>
<session-timeout>1</session-timeout>
</session-config>
123
8.jsp
8.1.什么是JSP
Java Server Pages:Java服务器端页面,也和Servlet一样,用于动态web技术!
最大特点:
1.写JSP就像在写HTML
2.区别:
HTMl只给用于提供静态数据
JSP页面中可以嵌入JAVA代码,为用户提供动态数据
8.2.JSP原理
思路:JSP到底怎么执行的!
1.代码层面没有任何问题
2.服务器内部工作
Tomcat
我电脑的地址:
C:\Users\wei\AppData\Local\JetBrains\IntelliJIdea2020.3
\tomcat\0794b5b5-a6b7-4d24-86bd-409f1fd809ef\work\Catalina
\localhost\ROOT\org\apache\jsp
发现页面转变成了Java程序!
浏览器向服务器发送请求,不管访问什么资源,其实都在访问Servlet!
JSP 最终也会被转换称为一个Java类!
通过查看被转换后的Java类的源码,发现该类继承了HttpJspBase
通过查看HttpJspBase的源码发现,该类继承了HttpServlet
也就是说:JSP本质上就是一个Servlet
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
1.判断请求
2.内置一些对象
final javax.servlet.jsp.PageContext pageContext; //页面上下文
javax.servlet.http.HttpSession session = null; //session
final javax.servlet.ServletContext application; //applicationContext
final javax.servlet.ServletConfig config; //config
javax.servlet.jsp.JspWriter out = null; //out
final java.lang.Object page = this; //page:当前
HttpServletRequest //请求
HttpServletResponse //响应
3.输出页面前增加的代码
response.setContentType("text/html"); //设置响应的页面类型
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig(); //获取配置
session = pageContext.getSession(); //获取session
out = pageContext.getOut();
_jspx_out = out;
4.以上的这些个对象我们可以在JSP页面中直接使用
1.在JSP页面中;
2.只要是Java代码就会原封不动的输出;
3.如果是HTML代码,就会转化为
out.write("<html>\r\n");
这样的格式输出到前端
测试:
1.找到tomcat服务器工作的目录
当前目录只要两个文件
2.新建一个jsp页面
3.重启tomcat服务器
会发现当前目录会报错,因为重启tomcat服务器后,该工作空间会被重新刷新、重新加载。
启动完成后,当前工作空间还是只有两个文件
我们访问test.jsp 之后,会生成对应的Java类
大概流程
8.3.JSP基础语法
任何语言都有自己的语法,Java中有,JSP作为Java技术的一种应用,他拥有自己扩充的语言。Java所有语法都支持!
JSP表达式
<%--JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
<%= new Date()%>
JSP脚本片段
<%--JSP脚本片段--%>
<%
int sum = 0;
for (int i = 1;i<=100; i++) {
sum+=i;
}
out.println("<h1>Sum="+sum+"</h1>");
%>
<%
int x = 10;
out.println(x);
%>
<p>这是一个jsp文档</p>
<%
int y = 2;
out.println(y);
%>
<hr>
<%--在代码中嵌入html元素--%>
<%
for (int i = 0; i < 5; i++) {
%>
<h1>Hello,Workd</h1>
<%
}
%>
JSP声明
<%!
static {
System.out.println("loading Servlet!");
}
private int globalVar = 0;
public void xy(){
System.out.println("进入了方法xy");
}
%>
JSP声明:会被编译到JSP生成的类中!其他的(JSP表达式,JSP脚本片段),就会被生成到_jspService方法中!
在JSp中,嵌入Java代码即可!
<%%>
<%=%>
<%!%>
<%--注释--%>
Jsp的注释不会在客户端显示,html的就会
JSP指令
<%@ page args ... %>
1
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/10/16
Time: 16:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--<%@ include 会将两个页面合二为一--%>
<%@ include file="common/head.jsp"%>
<h1>网页主题体</h1>
<%@ include file="common/footer.jsp"%>
<hr>
<%--
jsp:include 拼接页面,本质还是三个
--%>
<%--jsp 标签--%>
<jsp:include page="/common/head.jsp"/>
<h1>网页主题体</h1>
<jsp:include page="/common/footer.jsp"/>
</body>
</html>
8.4.九大内置对象
1.PageContext –存东西
javax.servlet.jsp.PageContext
JSP的页面容器,页面上下文
2.Response
javax.servlet.http.HttpServletResponse
服务器向客户端的响应信息
3.Request –存东西
javax.servlet.http.HttpServletrequest
封装了全部用户的请求信息
4.Session — 存东西
javax.servlet.http.HttpSession
用来保存每一个用户的信息,利用sessionid进行会话跟踪
作用范围:一次会话有效
5.Application 【ServletContext】 –存东西
javax.servlet.ServletContext
表示所有用户的共享信息
6.config【ServletConfig】
javax.servlet.ServletConfig
服务器配置信息,可以取得初始化参数
7.out
javax.servlet.jsp.jspWriter
页面输出
作用范围为一个jsp页面
8.page 不用
java.lang.object
jsp实例
9.exception
java.lang.Throwable
pageContext.setAttribute();
保存的数据只在一个页面中有效
request.setAttribute(“);
保存的数据只在一次请求中有效 ,请求转发会携带这个数据
session.setAttribute();
保存的数据只在一次会话中有效 ,从打开浏览器到关闭服务器
application.setAttribute();
保存的数据只在服务器中有效 ,从打开服务器到关闭服务器
request:
客户端想服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用的!
session:
客户端想服务器发送请求,产生的数据,用户用完,用户看完一会还有用,比如:购物车
application:
客户端想服务器发送请求,产生的数据,一个用户用完,其他用户还能使用。、,比如聊天数据。
8.5.JSP标签、JSTL标签、EL表达式
EL表达式:
1.获取数据
2.执行运算
3.获取web开发的常用对象
EL表达式的语法
EL 表达式语法如下:
${EL表达式}
EL 表达式语法以${
开头,以}
结束,中间为合法的表达式。
示例
${param.name}
表示获取参数 name 的值,它等同于 <%=request.getParameter('name') %>
。
EL算术运算符 | 说明 | 范例 | 结果 |
---|---|---|---|
+ | 加 | $ | 7 |
– | 减 | $ | 3 |
* | 乘 | $ | 10 |
/ 或 div | 除 | $ | 2 |
% 或 mod | 求余 | $ | 1 |
EL 的
+
运算符与 Java 的+
运算符不一样,它无法实现两个字符串的连接运算。如果该运算符连接的两个值不能转换为数值型的字符串,则会拋出异常;反之,EL 会自动将这两个字符转换为数值型数据,再进行运算
EL比较运算符
比较运算符用来实现两个表达式的比较,进行比较的表达式可以是数值型或字符串。EL 表达式比较运算符如下:
EL比较运算符 | 说明 | 范例 | 结果 |
---|---|---|---|
== 或 eq | 等于 | ${6==6} 或 ${6 eq 6} ${“A”=”a”} 或 $ | true false |
!= 或 ne | 不等于 | ${6!=6} 或 ${6 ne 6} ${“A”!=“a”} 或 $ | false true |
< 或 lt | 小于 | ${3<8} 或 ${3 lt 8} ${“A”<“a”} 或 $ | true true |
> 或 gt | 大于 | ${3>8} 或 ${3 gt 8} ${“A”>”a”} 或 $ | false false |
<= 或 le | 小于等于 | ${3<=8} 或 ${3 le 8} ${“A”<=”a”} 或 $ | true true |
>= 或 ge | 大于等于 | ${3>=8} 或 ${3 ge 8} ${“A”>=”a”} 或 $ | false false |
EL逻辑运算符
逻辑运算符两边的表达式必须是布尔型(Boolean)变量,其返回结果也是布尔型(Boolean)。EL 表达式逻辑运算符如下:
EL逻辑运算符 | 说明 | 范例 | 结果 |
---|---|---|---|
&& 或 and | 与 | ${2>1&&3<4 } 或 $ | true |
|| 或 or | 或 | ${2<1||3>4} 或 $ | false |
! 或 not | 非 | ${!(2>4)} 或 $ | true |
EL其它运算符
1). 和 [ ]
.
和[ ]
是 EL 中最常用的运算符,用来访问 JavaBean 中的属性和隐式对象的数据。一般情况下,.
用来访问 JavaBean 属性或 Map 类型的值,[ ]
用来访问数组或者列表的元素。
2)empty
empty 用来判断 EL 表达式中的对象或者变量是否为空。若为空或者 null,返回 true,否则返回 false。
3)条件运算符
EL 表达式中,条件运算符的语法和 Java 的完全一致,如下:
${条件表达式?表达式1:表达式2}
其中,条件表达式用于指定一个判定条件,该表达式的结果为 boolean 类型。如果该表达式的运算结果为 true,则返回表达式 1 的值;反之,返回表达式 2 的值。
示例
运算符演示如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
import="net.biancheng.*,java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>编程帮(www.biancheng.net)</title>
</head>
<body>
<h4>.运算符</h4>
<% Site site = new Site();
site.setName("编程帮");
site.setUrl("www.biancheng.net");
session.setAttribute("site", site); %>
欢迎来到${site.name},我们的网址是:${site.url}
<h4>[]运算符</h4>
<% List tutorials = new ArrayList();
tutorials.add("Java");
tutorials.add("Python");
session.setAttribute("tutorials", tutorials);
HashMap siteMap = new HashMap();
siteMap.put("one", "编程帮");
siteMap.put("two", "C语言中文网");
session.setAttribute("site", siteMap); %>
tutorials 中的内容:${tutorials[0]},${tutorials[1]}
<br> siteMap 中的内容:${site.one},${site.two}
<h4>
empty和条件运算符</h4>
<!-- 当 cart 变量为空时,输出购物车为空,否则输出cart -->
<% String cart = null; %>
${empty cart?"购物车为空":cart}
</body>
</html>
运行结果如下:
EL内置对象
为了显示方便,EL 表达式语言提供了许多内置对象,可以通过不同的内置对象来输出不同的内容。EL 表达式内置对象如下:
内置对象 | 说明 |
---|---|
pageScope | 获取 page 范围的变量 |
requestScope | 获取 request 范围的变量 |
sessionScope | 获取 session 范围的变量 |
applicationScope | 获取 application 范围的变量 |
param | 相当于 request.getParameter(String name),获取单个参数的值 |
paramValues | 相当于 request.getParameterValues(String name),获取参数集合中的变量值 |
header | 相当于 request.getHeader(String name),获取 HTTP 请求头信息 |
headerValues | 相当于 request.getHeaders(String name),获取 HTTP 请求头数组信息 |
initParam | 相当于 application.getInitParameter(String name),获取 web.xml 文件中的参数值 |
cookie | 相当于 request.getCookies(),获取 cookie 中的值 |
pageContext | 表示当前 JSP 页面的 pageContext 对象 |
从以上方法可以看出,EL 表达式可以输出 4 种属性范围的内容。如果在不同的属性范围中设置了同一个属性名称,则按照 page、request、session、application 的顺序依次查找。
我们也可以指定要取出哪一个范围的变量,例如:
${pagesScope.name}
,表示取出 page 范围的 name 变量。
<html>
<head>
<title>编程帮(www.biancheng.net)</title>
</head>
<body>
<%
pageContext.setAttribute("info", "page属性范围");
request.setAttribute("info", "request属性范围");
session.setAttribute("info", "session属性范围");
application.setAttribute("info", "application属性范围");
%>
<h2>不同属性范围的值</h2>
<hr />
不指定范围:${info}
<br> page 属性内容:${pageScope.info}
<br> request 属性内容:${requestScope.info}
<br>session 属性内容:${sessionScope.info}
<br>application 属性内容:${applicationScope.info}
</body>
</html>
运行结果如下:
下面演示 param、paramValues 的使用方法,
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>编程帮(www.biancheng.net)</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
%>
<form action="${pageContext.request.contextPath}/index.jsp" method="post">
网站名称: <input type="text" name="name" value="编程帮" /> <br>
<input type="text" name="name" value="C语言中文网" /> <br>
<input type="text" name="name" value="百度" /> <br>
网址: <input type="text" name="url" value="www.biancheng.net" /> <br>
<input type="submit" value="提交" />
</form>
</body>
</html>
表单的 action 属性也是一个 EL 表达式。
${pageContext.request.contextPath} 等价于 <%=request.getContextPath()%>,
意思就是取出部署的应用程序名,或者是当前的项目名称。
本例中项目名称是 jspDemo,
因此 ${pageContext.request.contextPath} 或 <%=request.getContextPath()%> 就等于 /jspDemo。
实际项目中应该这样写:${pageContext.request.contextPath}/login.jsp。
index.jsp 页面代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>编程帮(www.biancheng.net)</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
%>
请求参数值:${param.url}
<br> ${paramValues.name[0]}
</body>
</html>
运行结果如下:
login.jsp运行结果
index.jsp运行结果
<!--JSTL表达式的依赖-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!--standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
JSP标签
<jsp:forward page="jsptag2.jsp">
<jsp:param name="name" value="xianyan"/>
<jsp:param name="age" value="age"/>
</jsp:forward>
JSTL表达式
JSTL标签库的使用就是为了弥补HTML标签的不足,它自定义了许多标签,可以供我们使用
核心标签
<%--引入jstl核心标签库 core--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
JSTL标签库使用步骤
1.引入对应的taglib
2.使用其中的方法
3.在Tomcat也需要引入jstl的依赖,否则报错
if 说明
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/10/16
Time: 18:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入jstl核心标签库 core--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>If测试</h4>
<hr>
<form action="coreif.jsp" method="get">
<%--
el表达式获取表单中的数据
${param.参数名}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
<%--判断提交的用户名是管理员,则登录成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="管理员欢迎您!"/>
</c:if>
<c:out value="${isAdmin}"/>
</body>
</html>
foeach说明
<%@ page import="java.util.ArrayList" %><%--
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入jstl核心标签库 core--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
ArrayList<String> people = new ArrayList<>();
people.add("张三");
people.add("李四");
people.add("王五");
people.add("赵六");
people.add("冯七");
request.setAttribute("list",people);
%>
<%--
var : 每一次遍历出来的变量
items :要遍历的对象
--%>
<c:forEach var="people" items="${list}">
<c:out value="${people}"/><br>
</c:forEach>
<hr>
<%--
var : 每次遍历出来的变量
items : 要遍历的对象
begin : 哪里开始
end : 到哪里
step : 步长
--%>
<c:forEach begin="1" end="3" step="2" var="peopel" items="${list}">
<c:out value="${peopel}"/> <br>
</c:forEach>
</body>
</html>
choose-when说明
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/10/16
Time: 18:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入jstl核心标签库 core--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--定义一个变量score,值为85--%>
<c:set var="score" value="85"/>
<c:choose>
<c:when test="${score>=90}">
你的成绩为优秀
</c:when>
<c:when test="${score>=80}">
你的成绩为良好
</c:when>
<c:when test="${score>=70}">
你的成绩为一般
</c:when>
<c:when test="${score<=60}">
你的成绩为不及格
</c:when>
</c:choose>
</body>
</html>
9.JavaBean
bean:豆子
实体类
JavaBean存在特定写法
- 必须要有一个无参构造
- 属性必须私有化
- 必须要有对应的get/set方法
一般用来做数据库得字段映射
ORM:对象关系映射
- 数据库中 表—>类
- 数据库中 字段->属性
- 数据库中 行—>对象
i | name | age | address |
---|---|---|---|
1 | 小一 | 10 | 西安 |
2 | 小贰 | 12 | 上海 |
3 | 小伞 | 7 | 深圳 |
class People{
private int id;
private String name;
private int age;
private String address;
}
实体类:一般都是和数据库中的表结构一一对应
10.mvc
- 设计模式
- 是一套被反复使用,多数人之知晓的,代码设计经验的总结
- 模式必须是典型问题
什么是mvc:Model View Controller 模型 -视图-控制器
1.早些年
用户直接访问控制层,控制层就可以直接操作数据库;
servlet--CRUD---》数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、处理业务代码、处理逻辑代码
程序员调用
|
JDBC
|
架构:没有什么是加一层解决不了的!
JDBC -- MYSQL Oracle SqlServer
1234567891011
2.MVC三层架构
Model
业务处理:业务逻辑(Service)
数据持久层:CRUD(Dao)
View
展示数据
提供链接发起Servlet请求(a,form,img…)
Controller(Servlet)
接收用户的请求:(request:请求参数,session信息…)
交给业务层处理对应的代码
登录---》接收用户的登录请求----》处理用户的请求(获取用户登录的参数,name,pwd)
---》交给业务层处理登录业务(判断用户名密码是否错误)
---》Dao层查询用户名和密码是否正确
---》数据库
11.Filter(重点)
过滤器,用来过滤网站的数据;
处理中文乱码
登录验证…
过滤器实际上就是对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理
通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理
大概流程图如下
应用场景
自动登录
统一设置编码格式
访问权限控制
敏感字符过滤等
Filter开发步骤
1.导包
2.编写过滤器
3.导包不要错
import javax.servlet.Filter;
实现filter接口,重写对应方法
package cn.bloghut.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
/**
* chain:链
* 1.过滤器中的所有代码,在执行特定请求的时候都会执行
* 2.必须要让过滤器继续执行
* chain.doFilter(request,response);
* @param request
* @param response
* @param chain
* @throws IOException
* @throws ServletException
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前....");
//让我们的请求继续走,如果不写,程序到这里就会被拦截
chain.doFilter(request,response);
System.out.println("CharacterEncodingFilter执行后....");
}
/**
* 初始化
* web服务器启动的就初始化了
* @param filterConfig
* @throws ServletException
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化");
}
/**
* 销毁
* web服务器关闭的时候,过滤器会被销毁
*/
@Override
public void destroy() {
System.out.println("destroy");
}
}
在web.xml中配置过滤器
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>cn.bloghut.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!--只要是 /servlet 的任何请求,会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
12.Listener监听器
1.实现一个监听器的接口;(有n种)
实现监听器的接口
package cn.bloghut.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* 统计网站在线人数 :统计session
*/
public class OnlineCountListener implements HttpSessionListener {
/**
* 创建session 监听 : 看你的一举一动
* 一旦创建session就会触发一次这个事件!
*
* @param se
*/
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext context = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onLineCount = (Integer) context.getAttribute("onLineCount");
if (onLineCount == null) {
onLineCount = new Integer(1);
} else {
//不为空,在线数量+1
onLineCount++;
}
//更新在线人数
context.setAttribute("onLineCount",onLineCount);
}
/**
* 销毁session 监听
* 一旦session 就会触发一次这个事件!
*
* @param se
*/
@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext context = se.getSession().getServletContext();
Integer onLineCount = (Integer) context.getAttribute("onLineCount");
if (onLineCount == null){
onLineCount = 0;
}else {
onLineCount = onLineCount - 1;
}
context.setAttribute("onLineCount",onLineCount);
}
/**
* session销毁
*
* 1.手动销毁 getSession().invalidate();
* 2.自动销毁
*/
}
2.在web.xml中配置
<!--注册监听器-->
<listener>
<listener-class>cn.bloghut.listener.OnlineCountListener</listener-class>
</listener>
看情况是否使用
13.JQuery&ajax
jQuery 库可以通过一行简单的标记被添加到网页中。
- 访问操作DOM对象
- 控制页面样式
- 对页面事件进行处理
主要内容:
-
Jquery对象
- Jquery的使用
- DOM对象与Jquery包装集对象
-
Jquery选择器
- 基础选择器
- 层次选择器
- 表单选择器
-
Jquery DOM操作
- 操作元素的属性
- 操作元素的样式
- 操作元素的内容
- 创建元素
- 添加元素
- 删除元素
- 遍历元素
-
Jquery事件
- ready加载事件
- 绑定事件
-
Jquery Ajax(异步无刷新操作)
-
$.ajax( )
-
$.get( )
-
$.post( )
-
$.getJSON( )
-
jQuery 是一个 JavaScript 函数库。
jQuery 库包含以下特性:
- HTML 元素选取
- HTML 元素操作
- CSS 操作
- HTML 事件函数
- JavaScript 特效和动画
- HTML DOM 遍历和修改
- AJAX
- Utilities
jQuery 库位于一个 JavaScript 文件中,其中包含了所有的 jQuery 函数。
可以通过下面的标记把 jQuery 添加到网页中:
<head>
<script src="jquery.js"></script>
</head>
注意: