javaweb

一、Maven

  • 在Java开发中,需要使用大量的jar,需要手动导入
  • maven就可以自动导入jar包

1、Maven项目架构管理工具

我没目前用它就是为了方便导入jar包
约定大于配置

  • 有约束,不要去违反
    Maven会规定好如何编写Java代码,必须要按照这个规范来

2、下载按照Maven

javaweb_第1张图片

3、配置系统环境变量

  • M2_HOME maven目录下的bin目录
  • MAVEN_HOME maven目录
  • 在系统的path中配置 %MAVEN_HOME%\bin
    javaweb_第2张图片

4、配置阿里云镜像

  • 镜像:mirrors
    • 国内使用阿里云镜像

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>

5、本地仓库

在本地的仓库、远程仓库
建立本地仓库
javaweb_第3张图片

apache-maven-3.8.6\conf\settings.xml
javaweb_第4张图片

6、在IDEA中使用Maven

  • 创建maven项目

javaweb_第5张图片
通过模板创建
javaweb_第6张图片
不使用模板
javaweb_第7张图片

javaweb_第8张图片
标记资源目录
方式一:
javaweb_第9张图片
方式二:
javaweb_第10张图片

7、在IDEA中配置tomcat

javaweb_第11张图片
javaweb_第12张图片
javaweb_第13张图片

8、pom文件

pom.xml是maven的核心配置问津
javaweb_第14张图片



<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>

9、导入jar包

maven仓库:https://mvnrepository.com/
以导入spring为例:
javaweb_第15张图片
javaweb_第16张图片
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>

10、jar包结构图

javaweb_第17张图片

二、Servlet

1、Servlet简介

  • Servlet就是sun公司开发动态web的一问技术
  • sun在这些API中提供一个接口叫做:Servlet,如果你想开发一个Servlet程序,只需要完成两个小步骤
    • 编写一个类,实现Servlet接口
    • 吧开发好的java类部署到web服务器中
  • 把实现了Servlet家口的java程序叫做,servlet

2、HelloServlet

  • 新建一个maven普通项目,删除src文件夹

  • 添加子工程modules:
    javaweb_第18张图片
    javaweb_第19张图片
    javaweb_第20张图片

    • 关于maven父子工程的理解
      父项目的pom中会有
      javaweb_第21张图片
      子项目的pom会有:
      javaweb_第22张图片
      父项目中的java子项目可以直接使用

son extends father

3、maven环境优化

  • 用apache-tomcat-10.0.22\webapps\ROOT\WEB-INF\web.xml将子项目中src\main\webapp\web-inf\web.xml文件替换掉
  • 将maven结构搭建完整
    javaweb_第23张图片

4、编写一个servlet程序

  • 编写一个普通类
  • 实现servlet接口,继承httpservlet、GenericServlet
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);
    }
}

5、编写Servlet的映射

为什么需要映射:我们写的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>

6、配置Tomcat

见:一、7 在IDEA中配置tomcat

7、启动测试

三、Servlet原理

servlet是由web服务器调用,web服务器
javaweb_第24张图片

四、Mapping问题

1、路径映射的方式

  • 一个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>
    

2、优先级问题(编写报错页面):

  • 编写报错的errorservlet报错程序
    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>
    

javaweb_第25张图片
javaweb_第26张图片
由此得出:指定了固定的映射路径优先级最高,如果找不到就会走默认处理请求

五、ServletContext

web容器在启动的时候,他会为每一个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用:

1、 共享数据

  • 我在这个Servlet中保存的数据,可以在另外一个servlet中拿到
    //保存数据的类
    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>
    
  • 测试访问:
    先访问(http://localhost:8080/servlet_02_war/hello)页面,往ServletContext里面放入数据;
    再访问(http://localhost:8080/servlet_02_war/getc)页面,读取ServletContext里面放入的数据。

2、获取初始化参数

  • 在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>
    
  • 测试
    javaweb_第27张图片

3、请求转发

  • 实现转发的类
    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>
    
  • 测试(当访问http://localhost:8080/servlet_02_war/sd4时,会转到http://localhost:8080/servlet_02_war/getp页面)
    javaweb_第28张图片

4、读取资源文件

Properties

  • 在java目录下新建properties
  • 在resource目录下新建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>
    
  • 测试
    javaweb_第29张图片

6、HttpServletResponse

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;

  • 如果要获取客户端请求来的参数:找HttpServletRequest
  • 如果要给客户端响应一些信息:找HttpServletResponse

1、简单分类

负责向浏览器发送数据的方法

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;

2、常见应用

1、向浏览器输出消息
2、下载文件

  • 要获取下载文件的路径
  • 下载的文件名
  • 让浏览器能够支持下载我们需要的东西
  • 获取下载文件的输入流
  • 创建缓冲区
  • 获取outoutstream对象
  • 将Fileoutputstream流写入到buffer缓冲区
  • 使用outputstream将缓冲区的数据输出到客户端

文件下载类

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
    

3、验证码功能

  • 前端实现
  • 后端实现,需要用到java的图片类
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>

4、实现重定向

一个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);
    }
}

绑定路径:略

面试题:请你聊聊重定向和转发的区别
相同点:

  • 页面都会实现跳转

不同点:

  • 请求转发的时候:url不会产生变化 307
  • 重定向时候:url地址栏会发送变化 302

5、模拟登录跳转

  • 登录页面

    <%@ 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>
    

7、HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过http协议访问服务器:http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息

1、获取前端传递的参数

javaweb_第30张图片

获取单个前端传递的参数、获取多个前端传递的参数、请求转发
前端页面:

<%@ 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(略)

六、Cookie、Session

1、会话

会话:
用户打开浏览器、点击了很多超链接,访问多个web资源,关闭浏览,这个过程可以称为会话
有状态会话:
1、服务端给客户端一个信件、客户端下次访问服务端带上信件就可以了,cookie
2、服务器登记cookie,下次客户端访问时服务器可以匹配;session

2、保存会话的两种技术

cookie

  • 客户端技术(响应,请求)

session

  • 服务器技术,利用这个技术,可以保存用户的会话信息,我们可以把信息或者数据放在session中

常见场景:网站登录之后,下次不用在登录

3、Cookie

javaweb_第31张图片

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只能保存一个信息
  • 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
  • cookie大小由限制4kb
  • 300个cookie浏览器上限

删除cookie:

  • 不设置有效期,关闭浏览器,自动失效
  • 设置有效期时间为0;
    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);
    }
}

4、Session(重点)

javaweb_第32张图片

什么是Session:

  • 服务器会给每个用户(浏览器)创建一个session对象
  • 一个session独占一个浏览器,只要浏览器没有关,这个session就存在
  • 用户登录之后,整个网站他都可以访问——>保存用户的信息,保存购物车的信息

Session和cookie的区别:

  • Cookie把用户的数据写给用户的浏览器保存
  • Session把用户的数据写到用户独占Session中,服务器端保存(保存重要的信息,减少服务器资源浪费)
  • Session对象服务器创建

使用场景:

  • 保存一个登录用户的信息
  • 购物车信息
  • 在整个网站中经常会使用的数据,我们将他保存在Session中

创建session:

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对象(略):

获取session值:

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);
    }
}

手动注销session:

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);
    }
}

通过web.xml设置session自动失效时间(会话自动过期):


    <session-config>

        <session-timeout>1session-timeout>
    session-config>

你可能感兴趣的:(学习笔记,java,intellij-idea,maven)