maven
创建一个maven项目的过程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mzwwfNnx-1635834582755)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031094059282.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ud0mdrTi-1635834582758)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031090851978.png)]
(一开始是没有maven-repo文件夹的,是自己创建的,作为本地仓库)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OE1hlOTP-1635834582760)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031091704321.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5Uv7mUAy-1635834582762)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031091109421.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-T1De5ZbU-1635834582764)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031091434252.png)]
<mirror>
<id>alimavenid>
<mirrorOf>centralmirrorOf>
<name>aliyun mavenname>
<url>http://maven.aliyun.com/nexus/content/groups/publicurl>
mirror>
<mirror>
<id>mirrorIdid>
<mirrorOf>centralmirrorOf>
<name>Human Readable Name name>
<url>http://repo1.maven.org/maven2/url>
mirror>
<mirror>
<id>alimavenid>
<name>aliyun mavenname>
<url>http://central.maven.org/maven2url>
<mirrorOf>centralmirrorOf>
mirror>
<mirror>
<id>alimavenid>
<name>aliyun mavenname>
<url>http://maven.aliyun.com/nexus/content/repositories/central/url>
<mirrorOf>centralmirrorOf>
mirror>
<mirror>
<id>junitid>
<name>junit Address/name>
<url>http://jcenter.bintray.com/url>
<mirrorOf>centralmirrorOf>
mirror>
电脑配置环境打开操作(win+R——control system——关于——高级系统设置——系统属性——环境变量)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GfJXhNXJ-1635834582765)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031093046912.png)]
变量名:MAVEN_HOME
变量值:D:\environment\apache-maven-3.8.3-bin\apache-maven-3.8.3
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8Pht7l3d-1635834582766)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031093321045.png)]
添加环境变量:%MAVEN_HOME%\bin
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GBPKaUyu-1635834582766)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031093825154.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j9qaBSmB-1635834582768)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031095122038.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EZaihuZm-1635834582769)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031105402298.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lIblhMOs-1635834582770)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031105222786.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HqqbVeLd-1635834582770)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031102004837.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mLLNTkWR-1635834582771)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031102146286.png)]
<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>
11、在pom.xml中导入需要的依赖
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Yxo9DIrA-1635834582772)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031105610165.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a48QCkbS-1635834582773)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031105641212.png)]
<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>maven7artifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>maven7 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>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.4version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.3version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
dependency>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<excludes>
<exclude>**/*.propertiesexclude>
<exclude>**/*.xmlexclude>
excludes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
project>
以上已完成基本创建操作
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EIveSfQX-1635834582773)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031110039817.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4tBKruDI-1635834582774)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031110111867.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-i4A4eZea-1635834582774)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031110236590.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oXWyTiak-1635834582775)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031110319733.png)]
查看工作效果和时长等等
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GDDgX3Mp-1635834582776)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031114158998.png)]
查看,统计代码
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IEktB6kv-1635834582776)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031114612806.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LhoiIOYI-1635834582777)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031114749472.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SjbSRZjO-1635834582778)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031120507311.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KWY6sGvr-1635834582779)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031120533580.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AaopcGlR-1635834582780)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031120730472.png)]
帮助导入依赖
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IRFUG5H4-1635834582780)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031121013873.png)]
maven架包显示
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4lBWWN0E-1635834582781)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211031121400112.png)]
把实现了Servlet接口的java程序,即Servlet
Servlet接口有两个:HttpServlet和GenericServlet
1、构建一个普通的Maven项目(pom.xml是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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>maven7artifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>maven7 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>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.4version>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.3version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
dependency>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<excludes>
<exclude>**/*.propertiesexclude>
<exclude>**/*.xmlexclude>
excludes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
project>
2、关于Maven父子工程的理解
父项目中会有
<modules>
<module>servlet-01module>
modules>
子项目中会有
<parent>
<artifactId>maven-01artifactId>
<groupId>com.wugroupId>
<version>1.0-SNAPSHOTversion>
parent>
父项目中的java子项目可以使用
son extends father
3、Maven环境优化
1、修改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>
2、将maven的结构搭建完成;
3、没有web.iml文件
在Terminal输入:mvn idea:module
4、编写一个Servlet程序
1、编写一个普通类
2、实现Servlet接口
public class HelloServlet extends HttpServlet{
//由于get和post只是请求实现的不同方式,可以互相调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
PrintWriter writer = resp.getWriter();
writer.println("Hello,World!")
}
}
5、编写Servlet的映射
为什么需要映射!我们写的java程序,要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要web服务中注册我们写的Servlet,还需要给他一个能够访问的路径。在web.xml中修改
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.wu.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
6、配置Tomcat
注意:配置项目发布的路径就可以了
7、启动测试
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZxWr7qUQ-1635834582782)(C:\Users\28164\Pictures\Screenshots\屏幕截图(10)].png)
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
<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-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>*.xiaowuurl-pattern>
servlet-mapping>
指定了固有的映射路径的优先级最高,如果找不到就走默认的处理请求
<servlet>
<servlet-name>errorservlet-name>
<servlet-class>com.wu.servlet.errorServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>errorservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
public class SetServletContext extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// content.getInitParameter();初始化参数
// this.getServletConfig();Servlet配置
// this.getServletContext();Servlet上下文
ServletContext context = this.getServletContext();
String username = "小米";
context.setAttribute("username",username);
System.out.println("放置");
}
}
public class GetServletContext extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.getWriter().print(username);
System.out.println("得到!");
}
}
//获取初始化配置的信息
public class InitServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
}
<context-param>
<param-name>urlparam-name>
<param-value>jdbc:mysql://localhost:3306/mybatisparam-value>
context-param>
<servlet>
<servlet-name>Initservlet-name>
<servlet-class>com.wu.servlet.InitServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>Initservlet-name>
<url-pattern>/Initurl-pattern>
servlet-mapping>
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
ServletContext context = this.getServletContext();
resp.getWriter().print("转化成功!");
}
}
<servlet>
<servlet-name>Disservlet-name>
<servlet-class>com.wu.servlet.DispartcherServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>Disservlet-name>
<url-pattern>/disurl-pattern>
servlet-mapping>
web-app>
Properties
都被打包到相同路径:classes,类路径
public class PropertiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream input = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(input);
String name = properties.getProperty("username");
String pwd = properties.getProperty("password");
resp.getWriter().print(name+pwd);
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
}
}
<servlet>
<servlet-name>proservlet-name>
<servlet-class>com.wu.servlet.PropertiesServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>proservlet-name>
<url-pattern>/prourl-pattern>
servlet-mapping>
username = 小吴
password = 1234567890
web服务器接收客户端的http请求,针对这个请求,分别创建一个代表的HttpServletRequest对象,代表响应的一个HttpServletResponse;
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nbepGSWH-1635834582783)(C:\Users\28164\Pictures\resp.png)]
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throw IOException;
PrintWriter getWriter() threws IOException;
负责向浏览器发送响应头的方法
String getCharacterEncoding();
String getContentType();
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 setBufferSize(int var1);
int getBufferSize();
void flushBuffer() throws IOException;
void resetBuffer();
boolean isCommitted();
void reset();
void setLocale(Locale var1);
Locale getLocale();
响应的状态码:
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、下载文件
public class DownServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = "D:\\maven-01\\servlet-02\\target\\classes\\1.PNG";
String fileName = path.substring(path.lastIndexOf("\\")+1);
resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
FileInputStream fis = new FileInputStream(path);
int len = 0;
byte[] data = new byte[1024];
ServletOutputStream os = resp.getOutputStream();
while ((len=fis.read(data))>0){
os.write(data,0,len);
}
fis.close();
os.close();
}
}
public class imageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器3秒自动刷新一次
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D) image.getGraphics();//笔
//设置图片的背景颜色
g.setColor(Color.white);
g.fillRect(0,0,100,30);
//给图片写数据
g.setColor(Color.blue);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//请求浏览器以图片的形式打开
resp.setContentType("image/jpeg");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//将图片在浏览器画出来
ImageIO.write(image,"jpg",resp.getOutputStream());
}
<!--产生随机数-->
private String makeNum(){
Random rand = new Random();
String num = rand.nextInt(1000000)+"";
StringBuffer buf = new StringBuffer();
for(int i = 0;i < 7-num.length();i++){
buf.append("0");
}
num = buf.toString()+num;
return num;
}
}
A访问B B告诉A重新访问C A再访问C
面试题:重定向和请求转发有的区别
相同点
不同点
public class RequestServlet 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);
//重定向时要注意路径,否则报错404
resp.sendRedirect("/s2/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
Hello World!
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前的项目--%>
<%--
Created by IntelliJ IDEA.
User: 28164
Date: 2021/10/27
Time: 18:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
登录测试成功!
登录测试成功!
<servlet>
<servlet-name>reqservlet-name>
<servlet-class>com.wu.servlet.RequestServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>reqservlet-name>
<url-pattern>/requrl-pattern>
servlet-mapping>
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest的方法,获取客户端的全部信息。
会话:用户打开一个浏览器,点击了许多连接,访问多个web资源,关闭浏览器,这个过程就是会话
有状态会话:
客户端 服务端
1、服务器给客户端一个 信件 客户端下次访问服务端时带上信件即可;cookie
2、服务器登记你来过了,下次你来得时候服务端来匹配你;session
cookie
session
常见:网站登录之后,第二次就不用再登录,第二次访问直接就上去了
服务器端像客户端发送Cookie是通过HTTP响应报文实现的,在Set-Cookie中设置需要像客户端发送的cookie,cookie格式如下:
Set-Cookie: “name=value;domain=.domain.com;path=/;expires=Sat, 11 Jun 2016 11:29:42 GMT;HttpOnly;secure”
其中name=value是必选项,其它都是可选项。Cookie的主要构成如下:
name:一个唯一确定的cookie名称。通常来讲cookie的名称是不区分大小写的。
value:存储在cookie中的字符串值。最好为cookie的name和value进行url编码
domain:cookie对于哪个域是有效的。所有向该域发送的请求中都会包含这个cookie信息。这个值可以包含子域(如:yq.aliyun.com),也可以不包含它(如:.aliyun.com,则对于aliyun.com的所有子域都有效).
path: 表示这个cookie影响到的路径,浏览器跟会根据这项配置,像指定域中匹配的路径发送cookie。
expires:失效时间,表示cookie何时应该被删除的时间戳(也就是,何时应该停止向服务器发送这个cookie)。如果不设置这个时间戳,浏览器会在页面关闭时即将删除所有cookie;不过也可以自己设置删除时间。这个值是GMT时间格式,如果客户端和服务器端时间不一致,使用expires就会存在偏差。
expiry=-1:代表浏览器关闭后,也就是会话结束后,cookie就失效了,也就没有了。
expiry>0:代表浏览器关闭后,cookie不会失效,仍然存在。并且会将cookie保存到硬盘中,直到设置时间过期才会被浏览器自动删除,
expiry=0:删除cookie。不管是之前的expiry=-1还是expiry>0,当设置expiry=0时,cookie都会被浏览器给删除。
max-age: 与expires作用相同,用来告诉浏览器此cookie多久过期(单位是秒),而不是一个固定的时间点。正常情况下,max-age的优先级高于expires。
HttpOnly: 告知浏览器不允许通过脚本document.cookie去更改这个值,同样这个值在document.cookie中也不可见。但在http请求张仍然会携带这个cookie。注意这个值虽然在脚本中不可获取,但仍然在浏览器安装目录中以文件形式存在。这项设置通常在服务器端设置。
secure: 安全标志,指定后,只有在使用SSL链接时候才能发送到服务器,如果是http链接则不会传递该信息。就算设置了secure 属性也并不代表他人不能看到你机器本地保存的 cookie 信息,所以不要把重要信息放cookie就对了服务器端设置
1、从服务器拿到cookie信息
2、服务器响应到客户端cookie
Cookie[] cookies = req.getCookies();// Cookie,服务器从客户端获取可能存在多个Cookie
cookies.getName();//获取cookie中的key
cookies.getValue();//获取cookie中的value
new Cookie("lastLoginTime",System.currentTimeMillis()+"");//新建一个cookie
cookie.setMaxAge(24*60*60);//设置cookie有效期
resp.addCookie(cookie);//响应给客户端一个cookie
cookie:一般会保存在本地的用户目录下的appdate
C:\Users\28164\AppData\LocalLow
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H3SJGV5I-1635834582783)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211028095503419.png)]
一个网站cookie是否存在上限!
删除Cookie:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 服务器告诉你来的时间,把这个时间封装成为一个信件,下次访问时携带此信息,服务器知道你来了
// 解决乱码
req.setCharacterEncoding("gbk");
resp.setCharacterEncoding("gbk");
PrintWriter out = resp.getWriter();
// Cookie,服务器从客户端获取
Cookie[] cookies = req.getCookies();//返回数组,可能存在多个Cookie
// 判断Cookies是否存在
if(cookies!=null){
// 存在
out.write("上次访问的时间:");
for(int i = 0;i<cookies.length;i++){
Cookie cookie = cookies[i];
// 获取cookie的名字
if(cookie.getName().equals("lastTime")){
// 获取cookie的值
long lastTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastTime);
out.write(date.toLocaleString());
}
}
}else {
out.print("第一次访问!");
}
// 服务器给客户端响应一个cookie
Cookie cookie = new Cookie("lastTime",System.currentTimeMillis()+"");
// cookie有效期为20s
cookie.setMaxAge(1*5*60);
resp.addCookie(cookie);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 创建一个Cookie,名字和删除的Cookie的name一致
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
// 将Cookie的有效期设置为10s
cookie.setMaxAge(1*1*10);
// 将cookie响应给客户端
resp.addCookie(cookie);
}
<session-config>
<cookie-config>
<max-age>1max-age>
cookie-config>
session-config>
什么是Session
Session和Cookie的1区别:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//预防出现乱码
req.setCharacterEncoding("gbk");
resp.setCharacterEncoding("utf-8");
//得到一个Session
HttpSession session = req.getSession();
//在Session中存放对象
session.setAttribute("person",new Person("小五",19,1001));
//获取Session中的内容
String str = (String) session.getAttribute("Person");
//打印Session
System.out.println(str);
//获取时间函数
Date date = new Date();
//获取session最后一次交互时间
Date date1 = new Date(session.getLastAccessedTime());
//判断是不是新创建的Session
if(session.isNew()){
resp.getWriter().write("Session创建成功!id:"+session.getId());
}else{
resp.getWriter().write("session创建时间为:"+date1);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setCharacterEncoding("utf-8");
req.setCharacterEncoding("utf-8");
//获得Session
HttpSession session = req.getSession();
//获取Session中的person
Person person = (Person) session.getAttribute("person");
System.out.println(person.toString());
//显示获取到的信息
resp.getWriter().write(person.toString());
resp.getWriter().write(session.getId());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取Session
HttpSession session = req.getSession();
//移除person
session.removeAttribute("person");
//手动注销Session
session.invalidate();
}
}
public class Person {
String name;
int age;
int id;
public Person(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
}
Java Server Page:java服务端页面,也和Servlet一样,用于动态Web技术
最大的特点:
写JSP就像在写HTML
区别
代码层面看不难
Tomcat服务器内部工作原理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zoe913uS-1635834582784)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211030223318518.png)]
路径:C:\Users\28164\AppData\Local\JetBrains\IntelliJIdea2021.1\tomcat
页面转变成了java程序
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OigupptH-1635834582785)(C:\Users\28164\AppData\Roaming\Typora\typora-user-images\image-20211030225320848.png)]
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet
JSP最终也会被转换成一个java类!
JSP本质就是一个Servlet
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
if (!javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
final java.lang.String _jspx_method = request.getMethod();
if ("OPTIONS".equals(_jspx_method)) {
response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
return;
}
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) {
response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSP 只允许 GET、POST 或 HEAD。Jasper 还允许 OPTIONS");
return;
}
}
1、判断请求
2、设置内置对象
final javax.servlet.jsp.PageContext pageContext;//页面上下文
javax.servlet.http.HttpSession session = null;//session
final javax.servlet.ServletContext application;//ServletContext
final javax.servlet.ServletConfig config;//配置文件
javax.servlet.jsp.JspWriter out = null;//页面输出
final java.lang.Object page = this;//当前页面
final javax.servlet.http.HttpServletRequest request;//请求
final javax.servlet.http.HttpServletResponse response;//响应
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();
out = pageContext.getOut();
_jspx_out = out;
4、以上这些对象我们可在jsp页面中直接使用。
在jsp页面中
只有是java代码就会原封不动的输出
如果是HTML,就会被转化为
out.write("\r\n");
以此种方式,输出到前端
任何语言都有自己的语法
jsp作为java技术的一种应用,它拥有自己的扩展,但java的所有语法都支持
<%--JSP表达式
作用:用来将程序的输出,输出到客户端
<%变量或者表达式%>--%>
<%= new java.util.Date()%>
<%
String str = "Hello World!";
out.println("输出:"
+str+"");
%>
<%
for (int i = 0; i <3;i++){
%>
<h2>你好,我的小楠,爱你</h2>
<%}%>
//全局变量
<%!
String name = "小吴";
int id = 007;
%>
<%
out.println("name:"+name);
out.println("id:"+id);
%>
<!--html注释-->//会在客户端源代码显示
<%--jsp注释--%>//不会在客户端源代码显示
<!--新建的404.jsp-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page errorPage="404.jsp" %>
<%--显示声明这是一个错误页面--%>
<%@page isErrorPage="true" %>
<html>
<head>
<title>404错误</title>
</head>
<body>
<img src="../img/404.jpg" alt="404错误图片">
</body>
</html>
<!--在web.xml中配置-->
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<!--新建的500.jsp-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--定制500u错误页面--%>
<%@page errorPage="500.jsp" %>
<%@page isErrorPage="true" %>
<html>
<head>
<title>500错误</title>
</head>
<body>
<img src="../img/500.jpg" alt="500错误图片">
</body>
</html>
<!--web.xml中配置-->
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
<!--在web下新建一个common目录存放-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>头部页面</title>
</head>
<body>
<h>这是头部</h>
</body>
</html>
<!--存放在common目录-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>底部文件</title>
</head>
<body>
<h>这是底部</h>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试include</title>
</head>
<body>
<%--合二为一--%>
<%@include file="/common/header.jsp"%>
<h1>这是主体1!</h1>
<%@include file="/common/footer.jsp"%>
<hr>
<%--拼接而成,较好--%>
<jsp:include page="/common/header.jsp"/>
<h1>这是主体2!</h1>
<jsp:include page="/common/footer.jsp"/>
</body>
</html>
out.write("\r\n");
out.write("\r\n");
out.write(" 头部页面 \r\n");
out.write("\r\n");
out.write("\r\n");
out.write("这是头部 \r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("这是主体1!
\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" 底部文件 \r\n");
out.write("\r\n");
out.write("\r\n");
out.write("这是底部 \r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
后者源码
static {
_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(2);
_jspx_dependants.put("/common/header.jsp", Long.valueOf(1635616124279L));
_jspx_dependants.put("/common/footer.jsp", Long.valueOf(1635616124287L));
}
out.write("\r\n");
out.write("\r\n");
out.write("
\r\n");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/common/header.jsp", out, false);
out.write("\r\n");
out.write("这是主体2!
\r\n");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/common/footer.jsp", out, false);
out.write("\r\n");
out.write("\r\n");
out.write("
\r\n"); out.write("