我没目前用它就是为了方便导入jar包
约定大于配置
apache-maven-3.8.6\conf\settings.xml
<mirrors>
<mirror>
<id>alimavenid>
<mirrorOf>centralmirrorOf>
<name>aliyun mavenname>
<url>http://maven.aliyun.com/nexus/content/groups/publicurl>
mirror>
<mirror>
<id>maven-default-http-blockerid>
<mirrorOf>external:http:*mirrorOf>
<name>Pseudo repository to mirror external repositories initially using HTTP.name>
<url>http://0.0.0.0/url>
<blocked>trueblocked>
mirror>
mirrors>
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>javaweb-01-mavenartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>javaweb-01-maven Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
dependencies>
<build>
<finalName>javaweb-01-mavenfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
maven仓库:https://mvnrepository.com/
以导入spring为例:
maven由于它的约定大于配置,我们之后可能遇到我们写的配置文件,无法导出生效问题:
解决:在pom.xml中添加
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
son extends father
package com.jjl.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
// 由于get或者post只是请求实现的不同方式,可以相互调用,业务逻辑一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();//响应流
writer.print("hello.serlvet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
为什么需要映射:我们写的java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要再web服务器中注册我们写的Servlet,还需要给它一个浏览器能够访问的路径:
在web.xml中添加:
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.jjl.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
见:一、7 在IDEA中配置tomcat
一个servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
一个servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hello1url-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hello2url-pattern>
servlet-mapping>
一个servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hello/*url-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
指定一些后缀或者前缀等等
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
package com.jjl.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ErrorServlet extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");//以html页面展示
resp.setCharacterEncoding("UTF-8");//指定字符集
PrintWriter writer = resp.getWriter();
writer.print("404"
);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
<servlet>
<servlet-name>errorservlet-name>
<servlet-class>com.jjl.servlet.ErrorServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>errorservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
由此得出:指定了固定的映射路径优先级最高,如果找不到就会走默认处理请求
web容器在启动的时候,他会为每一个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用:
//保存数据的类
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = "jjl";//数据
context.setAttribute("username",username);//将数据保存到了ServletContext中,名字为:username,值:username
}
}
//读取数据的类
public class GetServlet extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().print("名字:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.jjl.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
<servlet>
<servlet-name>getcservlet-name>
<servlet-class>com.jjl.servlet.GetServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>getcservlet-name>
<url-pattern>/getcurl-pattern>
servlet-mapping>
在web.xml中配置初始化参数
<context-param>
<param-name>urlparam-name>
<param-value>jdbc:mysql://localhost:3306/mybdtisparam-value>
context-param>
获取参数的类,并输出参数
public class ServletDemo03 extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String parameter = context.getInitParameter("url");//获取参数
resp.getWriter().print(parameter);//输出参数
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
配置参数路径
<servlet>
<servlet-name>getpservlet-name>
<servlet-class>com.jjl.servlet.ServletDemo03servlet-class>
servlet>
<servlet-mapping>
<servlet-name>getpservlet-name>
<url-pattern>/getpurl-pattern>
package com.jjl.servlet;
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 context = this.getServletContext();
System.out.println("进入servletdemo04");
// RequestDispatcher requestDispatcher = context.getRequestDispatcher("/getp");//配置转发的路径
// requestDispatcher.forward(req,resp);//调用forward实现转发
context.getRequestDispatcher("/getp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>sd4</servlet-name>
<servlet-class>com.jjl.servlet.ServletDemo04</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd4</servlet-name>
<url-pattern>/sd4</url-pattern>
</servlet-mapping>
Properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath
思路:需要一个文件流
在resource资源文件夹里创建db.properties资源文件
username=root
password=123456
读取资源文件的类
package com.jjl.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
resp.getWriter().print(username);
resp.getWriter().print(password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
创建路径
<servlet>
<servlet-name>sd5servlet-name>
<servlet-class>com.jjl.servlet.ServletDemo05servlet-class>
servlet>
<servlet-mapping>
<servlet-name>sd5servlet-name>
<url-pattern>/sd5url-pattern>
servlet-mapping>
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送一些响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
void addIntHeader(String var1, int var2);
状态码:
int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
1、向浏览器输出消息
2、下载文件
package com.jjl.servlet;
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;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 要获取下载文件的路径
String realPath = "G:\\Program Files\\apache-tomcat-9.0.46\\webapps\\javaweb-02-servlet\\response\\target\\response\\WEB-INF\\classes\\1.png";
System.out.println("下载文件的路径"+realPath);
// 下载的文件名
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);//截取"/1.png"的"\"后面的所有字符
// 让浏览器能够支持下载我们需要的东西
//resp.setHeader("Content-disposition","attachment;filename=" +filename);
resp.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));//给文件名输出时转码,能识别中文
// 获取下载文件的输入流
FileInputStream inputStream = new FileInputStream(realPath);
// 创建缓冲区
int len=0;
byte[] buffer=new byte[1024];
// 获取outoutstream对象
ServletOutputStream outputStream = resp.getOutputStream();
// 将Fileoutputstream流写入到buffer缓冲区,使用outputstream将缓冲区的数据输出到客户端
while ((len=inputStream.read(buffer))>0){
outputStream.write(buffer,0,len);
}
inputStream.close();
outputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
绑定路径:
filedown
com.jjl.servlet.FileServlet
filedown
/filedown
package com.jjl.servlet;
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");
//在内存中创建图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D graphics = (Graphics2D) image.getGraphics();//笔
//设置图片的背景颜色
graphics.setColor(Color.white);
graphics.fillRect(0,0,80,20);
//给图片写数据
graphics.setColor(Color.BLUE);
graphics.setFont(new Font(null, Font.BOLD,20));
graphics.drawString(makeNum(),0,20);
//告诉浏览器,这个请求用图片的形式打开
resp.setContentType("image/jpg");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNum(){
Random random = new Random();
String num = random.nextInt(9999999)+"";
StringBuffer sb = new StringBuffer();
for (int i=0;i<7-num.length();i++){
sb.append("0");
}
num = sb.toString()+num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
路径绑定
<servlet>
<servlet-name>ImageServletservlet-name>
<servlet-class>com.jjl.servlet.ImageServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>ImageServletservlet-name>
<url-pattern>/imgurl-pattern>
servlet-mapping>
一个web资源收到客户端请求后,他会通知客户端去访问另外一个web资源,这就叫重定向
常见场景:
sendRedirect
测试:
package com.jjl.servlet;
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 RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
resp.setHeader("Location","/response_war/img");
resp.setStatus(302);
*/
resp.sendRedirect("/response_war/img");//重定向
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
绑定路径:略
面试题:请你聊聊重定向和转发的区别
相同点:
不同点:
登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!h2>
<%--这里提交的路径,需要寻找到项目的路径
${pageContext.request.contextPath}:当前项目
--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="提交">
form>
body>
html>
处理请求类
package com.jjl.servlet;
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("/response_war/success.jsp");//处理之后跳转的页面
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
成功登录之后跳转的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<H1>SUCCESSH1>
body>
html>
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器:http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息
获取单个前端传递的参数、获取多个前端传递的参数、请求转发
前端页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录title>
head>
<body>
<div style="text-align: center">
<%-- 以post方式提交表单,提交到login请求--%>
<h1>登录h1>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:<br>
<input type="checkbox" name="hobbys" value="女孩">女孩
<input type="checkbox" name="hobbys" value="代码">代码
<input type="checkbox" name="hobbys" value="唱歌">唱歌
<input type="checkbox" name="hobbys" value="电影">电影<br>
<input type="submit" value="提交">
form>
div>
body>
html>
获取请求的类:
web.xml的路径:略
package com.jjl.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
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("=====================================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("=====================================");
//通过请求转发
// "/Success.jsp"这里的"/"代表当前web应用
req.getRequestDispatcher("/Success.jsp").forward(req,resp);
resp.setCharacterEncoding("utf-8");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
转发页面:Success.jsp(略)
会话:
用户打开浏览器、点击了很多超链接,访问多个web资源,关闭浏览,这个过程可以称为会话
有状态会话:
1、服务端给客户端一个信件、客户端下次访问服务端带上信件就可以了,cookie
2、服务器登记cookie,下次客户端访问时服务器可以匹配;session
cookie
session
常见场景:网站登录之后,下次不用在登录
1、从请求中拿到cookie信息
2、服务器响应给客户端
Cookie[] cookies = req.getCookies();获取cookie
cookie.getName();获取cookie中的key
cookie.getValue();获取cookie中的值
Cookie cookie = new Cookie(“lastLoginTime”, System.currentTimeMillis()+“”);新建一个cookie
cookie.setMaxAge(246060);设置cookie的有效期
resp.addCookie(cookie);响应一个cookie给客户端
package com.jjl.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器告诉你,你来的时间,把这个时间封装为一个信件,你下次来,我就知道你来了
//解决中文乱码
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
//Cookie服务器端从客户端获取
Cookie[] cookies = req.getCookies(); //这里返回数组,说明cookie可能存在多个
//判断cookie是否存在
if(cookies!=null){
//如果存在怎么办?
out.write("你上一次访问的时间是");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获得cookie的名字
if (cookie.getName().equals("lastLoginTime")) {
//获取cookie中的值
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
out.write(date.toLocaleString());
}
}
}else {
out.write("这是你第一次访问本站");
}
//服务器给客户端响应一个cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
//cookie有效期为一天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
cookie:一般会保存在本地用户目录下appdata:
一个网站cookie是否存在上线
删除cookie:
package com.jjl.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建一个cookie,名字必须要和要删除的名字一致
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
//将cookie有效期设置为0,马上过期
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
用cookie传递中文时的编码解码
package com.jjl.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
//中文数据怎么传
public class CookieDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("UTF-8");
//Cookie服务器端从客户端获取
Cookie[] cookies = req.getCookies(); //这里返回数组,说明cookie可能存在多个
PrintWriter out = resp.getWriter();
//判断cookie是否存在
if(cookies!=null){
//如果存在怎么办?
out.write("你上一次访问的时间是");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获得cookie的名字
if (cookie.getName().equals("name")) {
//获取cookie中的值
//URLDecoder.decode(cookie.getValue(),"UTF-8")解码
out.write(URLDecoder.decode(cookie.getValue(),"UTF-8"));
}
}
}else {
out.write("这是你第一次访问本站");
}
//URLEncoder.encode("中文cookie","utf-8")转码(编码)
Cookie cookie = new Cookie("name", URLEncoder.encode("中文cookie","utf-8"));
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Session和cookie的区别:
使用场景:
package com.jjl.servlet;
import com.jjl.pojo.Person;
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 SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("UTF-8");
//得到session
HttpSession session = req.getSession();
//给session中存东西,可以是字符串,可以是对象
session.setAttribute("name",new Person("蒋樊",24));
//获取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 {
doGet(req, resp);
}
}
Person对象(略):
package com.jjl.servlet;
import com.jjl.pojo.Person;
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.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("UTF-8");
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("name");
System.out.println(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.jjl.servlet;
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
session.removeAttribute("name");
//注销session,手动注销
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<session-config>
<session-timeout>1session-timeout>
session-config>