目录
(3) 修改阿里云镜像 在..conf\settings.xml
2.检查本机的 C:\Windows\System32\drivers\etc\hosts配置文件下有没有这个域名映射;
1、Tomcat
1.安装tomcat
2.tomcat启动和配置
(1) 启动
a.可能遇到的问题:
环境变量没有配置
3.发布一个web网站
将自己写的网站,放到服务器(Tomcat)中指定的web应用的文件夹(webapp)下,就可以访问了
网站应该有的结构
--webapps : Tomcat服务器的web目录
--ROOT
--aotao : 网站的目录名
- WEB-INF
-classes : java程序
-lib : web应用所依赖的jar包
-web.xml : 网站的配置文件
- index.html : 默认的首页
- static
- css
- js
- img
2、Maven
(1) 下载:https://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.zip
(2) 配置环境变量:
在系统环境中配置
M2_HOME maven目录下的bin目录
MAVEN_HOME maven的目录
在系统的path中配置 %MAVEN_HOME%\bin
(3) 修改阿里云镜像 在..conf\settings.xml
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
(4) 本地仓库
a.创建本地仓库 localRepository
<localRepository>D:\env\maven\apache-maven-3.8.1\maven-repo</localRepository>
b.idea自带Maven
d.在idea中配置tomcat
3、Serverlet
1.Servlet简介
默认有两个实现类:HttpServlet,GenericServlet
(1) Servlet就是sun公司开发动态web的一门技术
(2) Sun在这些API中提供一个接口叫做:Servlet,如果想开发一个Servlet程序,只需完成两个小步骤:
a.编写一个类,实现Servlet接口
b.把开发号的java类部署到web服务器中
c.把实现了Serverlet接口的Java程序叫做,Servlet
2.Hello Servlet
(1) 构建一个普通maven项目,删掉里面的src目录,以后我们学习就在这个项目里面家里Model;这个空工程就是Maven主工程
(2) Maven环境优化
a.修改web.xml为最新的
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>
b.将maven的结构搭建完整
(3) 编写一个Servlet程序
依赖:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
a.编写一个普通类
b.实现Servlet接口
c.直接继承HttpServlet
public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同的方式,可以互相调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter(); //响应流
writer.print("hello servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
d.编写Servlet的映射
我们写的是JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要再web服务器中注册我们写的Servlet,还需要给他一个浏览器能够访问的路径;
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--注册Servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.aotao.servlet.HelloServlet</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
e.启动测试
3.Servlet原理
4.Mapping问题
5.ServletContext (上下文)
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用。
(1) 共享数据
在这个Servlet中保存的数据,可以在另外一个servlet中拿到;
a.创建HelloServlet类
package com.aotao.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String name = "aotao"; //数据
context.setAttribute("username",name); //将一个数据保存在ServletContext中,名字为:username。值name
System.out.println("hello");
}
}
b.创建读取HelloServlet类的GetServlet类
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String username = (String) servletContext.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
c.配置xml
<!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>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.aotao.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>com.aotao.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
</web-app>
d.运行测试
名字为null
当进入hello页面之后
名字已被更改
(2) 获取初始化参数
a.创建初始化类ServletDemo03
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
String url = servletContext.getInitParameter("url");
resp.getWriter().print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
b.配置web.xml
<!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://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>url</param-name>
<param-value>测试初始化参数</param-value>
</context-param>
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.aotao.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
</web-app>
c.测试
(3) 请求转发
a.创建请求转发类ServletDemo04
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
System.out.println("进入了ServletDemot04");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/gp"); //需要转发的地址
requestDispatcher.forward(req,resp); //调用forward实现请求转发
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
b.配置web.xml
<!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://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>url</param-name>
<param-value>测试初始化参数</param-value>
</context-param>
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.aotao.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sd4</servlet-name>
<servlet-class>com.aotao.servlet.ServletDemo04</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd4</servlet-name>
<url-pattern>/sd4</url-pattern>
</servlet-mapping>
</web-app>
c.测试
(4) 读取资源文件
<build>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<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>
Properties
在java目录下新建properties
在resources目录下新建db.properties 在配置文件里放入:
username=root
password=12345
发现都被打包到了同一个路径下:
a.新建ServletDemo05
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
System.out.println("进入了ServletDemot04");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
InputStream resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
resp.getWriter().print(username+":"+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
b.web.xml设置路径
<servlet>
<servlet-name>sd5</servlet-name>
<servlet-class>com.aotao.servlet.ServletDemo05</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd5</servlet-name>
<url-pattern>/sd5</url-pattern>
</servlet-mapping>
c.测试结果
6.HttpServletResponse
web服务器接收客户端的http请求,针对这个请求,分别创建一个代理请求的HttpServletRequest对象,代表响应的一个HttpServletResponse。
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
(1) 简单分类
a.负责向浏览器发送数据的方法
ServletOutputstream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
b.负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setBufferSize(int var1);
int getBufferSize();
void flushBuffer() throws IOException;
void resetBuffer();
boolean isCommitted();
void reset();
void setLocale(Locale var1);
Locale getLocale();
c.响应状态码
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) 常见应用
a.向浏览器输出消息
b.下载文件
1.要获取下载文件的路径
2.下载的文件是啥?
3.设置想办法让浏览器能够支持下载我们需要的东西
4.获取下载文件的输入流
5.创建缓冲区
6.获取OutputStream对象
7.将FileOutputStream流写入到buffer缓冲区
8.使用OutputStream将缓冲区中的数据输出到客户端
c.创建FileServlet类
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.要获取下载文件的路径
//String realPath = this.getServletContext().getRealPath("/功能分析图片.png");
String realPath = 这里改为图片的绝对地址;
System.out.println("下载文件的路径"+realPath);
//2.下载的文件是啥?
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3.设置想办法让浏览器能够支持下载我们需要的东西
resp.setHeader("Content-disposition","attachment;filename="+fileName);
//4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
//5.创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7.将FileOutputStream流写入到buffer缓冲区
while ((len=in.read(buffer)) != -1){
out.write(buffer,0,len);
}
in.close();
out.close();
//8.使用OutputStream将缓冲区中的数据输出到客户端
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
d.添加web.xml路径
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>filedown</servlet-name>
<servlet-class>com.aotao.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>filedown</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
</web-app>
e.测试结果
(2) 验证码功能
验证怎么来的?
前端实现
后端实现,需要java的图片类生产一个图片编写ImageServlet类,然后再web.xml注册类
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器5秒自动刷新一次;
resp.setHeader("refresh","3"); //js 里面的refresh刷新
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_3BYTE_BGR);
//得到图片
Graphics2D graphics = (Graphics2D) image.getGraphics(); //笔2D
//设置图片的背景颜色
graphics.setColor(Color.WHITE);
graphics.fillRect(0,0,80,20);
//给图片写数据
graphics.setColor(Color.BLUE);
graphics.setFont(new Font(null,Font.BOLD,20));
graphics.drawString(makNum(),0,20);
//告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpg");
//网站纯在缓冲不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生产随机数
private String makNum(){
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < 7- num.length();i++){
stringBuffer.append("0");
}
String s = stringBuffer.toString()+num;
return s;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
(3) 实现重定向
B一个web资源收到客户端A请求后,B他会通知A客户端去访问另外一个web资源C,这个过程交重定向。
void sendRedirect(String var1) throws IOException;
(4) 实现登陆测试重定向
a.再webapp添加index.jsp和success.jsp
需要提前导入jsp的包
index.jsp
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径需要寻找到项目路径--%>
<%--${pageContext.request.contextPath} :代表当前项目--%>
<%--pageEncoding="UTF-8"--%>
<form action="${pageContext.request.contextPath}/login">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
success.jsp
<html>
<body>
<h2>success!</h2>
</body>
</html>
添加测试类RequestTest
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username + ":" + password);
resp.sendRedirect("/aotao/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
再web.xml注入类和路径
<servlet>
<servlet-name>request</servlet-name>
<servlet-class>com.aotao.servlet.RequestTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>request</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
7.HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息
(1) 获取前端传递的参数
创建index.jsp
<%--
Created by IntelliJ IDEA.
User: LGS
Date: 2021/5/21
Time: 10:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陆</title>
</head>
<body>
<div style="text-align: center">
<%--以post提交请求--%>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:
<input type="checkbox" name="hobby" value="女孩">女孩
<input type="checkbox" name="hobby" value="代码">代码
<input type="checkbox" name="hobby" value="唱歌">唱歌
<input type="checkbox" name="hobby" value="电影">电影
<br>
<input type="submit">
</form>
</div>
</body>
</html>
创建LoginServlet类
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobby");
System.out.println("==================================================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
System.out.println("==================================================");
//通过请求转发
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
}
7、Cookie、Session
1.会话
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程称为会话
有状态会话:
一个网站怎么证明你来过?
客户端 服务端
1.服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了,这个信件就是cookie。
2.服务端等级你来过了,下次你来的时候我来匹配你,这就是session。
2.保存会话的两种技术
cookie
客户端技术(响应,请求)
session
服务器技术,利用这个技术,可以保存用户的会话信息?
3.Cookie
(1) 从请求中拿到cookie信息
(2) 服务器响应给客户端cookie
Cookie cookies = req.getCookies(); //获得cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); 获得cookie中的value
new Cookie("lastLoginTime",System.currentTimeMillis()+""); //新建一个cookie
cookie.setMaxage(24*60*60); //设置cookie的有效期
resp.addCookie(cookie); //响应给客户端一个cookie
cookie:一般会保存在本地的用户目录下appdata;
删除Cookie:
不设置有效期,关闭浏览器,自动失效;
设置有效时间为0
4.Session (重点)
(1) 什么是Session:
- 服务器会给每一个用户(浏览器)创建一个Session对象
- 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
- 用户登陆之后,整个网站它都可以访问 --->保存用户的信息;保存购物车的信息……
(2) Session和cookie的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存
- Session是把用户的数据写到用户独占Session中,服务器端缓存(保存重要的信息,减少服务器资源浪费)
- Session对象有服务器创建;
(3) 使用场景:
- 保存一个登陆用户的信息。
- 购物车信息。
- 整个网站中经常会使用的数据,我们将它保存在Session中。
(4) 使用Session
import java.io.IOException;
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setContentType("text/html");
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("name","aotao");
//获取Session的ID
String sessionID = session.getId();
//判断Session是不是新创建
if (session.isNew()){
resp.getWriter().write("Session创建成功,ID为:"+sessionID);
}else {
resp.getWriter().write("session已经存在,ID为:"+sessionID);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
(5) 得到Session
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setContentType("text/html");
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
//得到Session
HttpSession session = req.getSession();
Object name = session.getAttribute("name");
System.out.println(name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
(6) 会话手动过期
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销session
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
(7) 会话自动过期
<!--设置Session默认失效时间-->
<session-config>
<!--以分钟为单位-->
<session-timeout>1</session-timeout>
</session-config>
一个网站cookie是否存在上限!
tips:请你谈谈网站是如何访问的
1.输入一个域名,回车
2.检查本机的 C:\Windows\System32\drivers\etc\hosts配置文件下有没有这个域名映射;
(1) 有:直接返回对应的ip地址,这个地址中,有我们需要访问的web程序,可以直接访问
(2) 没有:去DNS服务器找,找到就返回,找不到就返回找不到