1月19号-Request和Response

3 篇文章 0 订阅
2 篇文章 0 订阅

二. 内容回顾

2.1 Servlet概述

  1. Servlet是一个java程序(动态资源), 运行在web服务器上面

  2. 接收浏览器请求,获取浏览器提交的请求数据(Servlet里面的request)

    浏览器---------------------->服务器端

  3. 响应数据给浏览器(Serlvet里面的response)

    浏览器<--------------------服务器端

2.2 Servlet体系结构

  • 顶层接口: Servlet
  • 抽象类: GenericServlet
  • 抽象类: HttpServlet
  • 关系: HttpServlet—>GenericServlet---->Servlet
  • 结论:
    1. 在开发时,自定义servlet有三种方式.
    2. 浏览器发送的是http请求,推荐使用HttpServlet

2.3 HttpServlet

源码分析: HttpServlet的service方法内部的思路

  1. 获取浏览器的请求方式

  2. 根据请求方式的不同,去执行对应的doGet(req,resp)和doPost(req,resp)

    //1.获取请求方式: request请求对象,当然获取请求数据
    String method = request.getMethod();
    //2.if判断: 请求方式=="get",这样写不合理
    if(method.equals("Get")){
        this.doGet(request,response)
    }else if(method.equals("Post")){
         this.doPost(request,response)
    }
    --------
    
  • 结论

    继承HttpServlet以后,重写doGet和doPost方法

三. 请求对象

3.1请求对象概述以及作用

  • 请求过程: 从浏览器到服务器的过程,称之请求过程

    浏览器-------请求过程: 提交请求数据------------------->服务器端

  • 请求数据: 使用请求对象request来处理

  • 请求对象的类型:

    HttpServletRequest(引用类型) request

3.2请求对象常用的方法

  • 第一类: 获取请求数据

    方法名称作用
    getParameter(“name属性的值”)获取单个输入框的值
    getParameterValues(“name属性的值”)获取复选框的值
    getParameterMap()获取的表单里面的所有数据

    Map<String,String[]> map = request.getParameterMap()

    map的key: name的属性值,比如: username, psw, love

    map的value: 用户输入的数据(用户名和密码)以及用户选择的数据(单选按钮,复选框)

前台代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>request parameter page</title>
</head>
<body>
        <!--
            form表单的方式提交数据
            http协议提交数据时: key=value的形式.
            所以form中的输入项必须得有name属性
            输入项没有name属性, 就不能提交数据到后台,所以后台获取的是null
        -->
        <form action="paramMapServlet" method="get">
            用户名: <input type="text" name="username"/>
            <br/>
            密&nbsp;&nbsp;&nbsp;码: <input type="password" name="psw"/>
            <br/>
            爱&nbsp;&nbsp;&nbsp;好:
            <input type="checkbox" name="love" value="comment">爱评论
            <input type="checkbox" name="love" value="study">爱学习
            <input type="checkbox" name="love" value="16k"/>拿高薪
            <input type="submit" value="提交数据"/>
        </form>
</body>
</html>

后台代码

package com.tedu.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * 1. 定义类ParamServlet 继承HttpServlet的方式
 *    作用: 获取浏览器提交的数据,以及响应数据给浏览器
 * 2. doGet方法: request,response
 *    request请求对象: 在服务器端,获取浏览器提交的请求数据的
 *    response响应数据: 响应数据到浏览器的
 *3. doPost方法: request,response
 *     request请求对象: 在服务器端,获取浏览器提交的请求数据的
 *     response响应数据: 响应数据到浏览器的
 */
@WebServlet("/paramServlet")//注意 : 路径必须加/, 不加/ tomcat启动就报错了
public class ParamServlet extends HttpServlet {
    /**
     * 作用: 接收浏览器发送的get
     * @param request: 获取请求数据,浏览器----->服务器
     * @param response: 响应数据,   浏览器<-----服务器
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.根name的属性获取用户输入的用户名: username=jack
        // 因为name="username" 是写死的,但是用户名可以随意输入的值
        String userValue = request.getParameter("username");
        System.out.println("请求的用户名:"+userValue);
        //2.根据psw=1111
        String pswValue = request.getParameter("psw");
        System.out.println("请求的密码:"+pswValue);
        //3.love  多个值
        String[] loves = request.getParameterValues("love");
        System.out.println("请求的爱好:"+ Arrays.toString(loves));
        //1.获取表单提交的所有数据
        Map<String, String[]> map = request.getParameterMap();
        //2.遍历map
        //2.1 获取所有key
        Set<String> keys = map.keySet();
        //2.2遍历 set:  快捷键iter
        for (String key : keys) {
             //2.3 获取map的值
            String[] strings = map.get(key);
            System.out.println(key+":"+ Arrays.toString(strings));
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }


}

  • 第二类: 处理请求中文的乱码问题

    • 分析会出现请求中文的乱码问题?

    浏览器提交的中文数据的编码格式------>tomcat服务器的编码格式不一样

    比如: 小伙伴(意见)------不同-------->老师(方式)

    • 常见的编码格式, 推荐使用UTF-8

      1.支持中文的编码格式: GBK

      ​ 特点: 支持中文.不支持日文,韩文等等

      1. 万能的编码格式: utf-8 (UTF-8)

        特点: 支持所有字符,比如中文,韩文,日文,等等

      2. 西欧编码: ISO8859-1

        特点: 只支持欧美国家的字符,肯定不支持中文,韩文,日文等等

    • 解决乱码

      请求方式不一样,提交的请求数据的形式就不一样,所以根据不同的请求方式来处理乱码.

      1. get请求的中文:

        tomcat8版本以上: 自动处理了get请求的中文乱码问题.

        tomcat8版本以下: 代码处理get请求的中文乱码问题

        ​ String vule = new String(

        ​ “用户数据”.getBytes(“iso8859-1”),

        ​ “utf-8”

        ​ );

      2. post请求的中文:

        request.setCharacterEncoding(“utf-8”);

        注意: 上面的代码 必须放在方法的第一行.

3.3 案例: 常用的方法

  1. 获取请求参数的值的方法

    • 获取一个输入框的用户数据

    String value = request.getParameter(“name属性值”);

    • 获取复选框用户选择的数据

      String[] values = request.getParameterValues(“name属性值”);

    • 获取form表单提交的所有数据

      Map<String,String[]> map = getParameterMap();

    • 处理post请求的中文乱码问题(tomcat8以上不用处理get请求中文)

      request.setCharacterEncoding(“支持中文的编码格式,utf-8”);

四 响应对象

4.1 响应对象概述以及作用

  • 响应过程: 从服务器到浏览器响应数据的过程,就是响应过程

    web服务器------响应: 响应数据------>浏览器

  • 作用:

    主要处理响应数据以及重定向(稍后讲)

  • 类型

    HttpServletResponse(类型) response(对象)

4.2 常用方法

  • 字符流和字节流回顾

    • 字符流把c盘的图片文件拷贝到D盘?

      ​ 答案: 不行, 字符流只能进行字符串的读写操作.

    • 字节流把c盘的图片文件拷贝到D盘?

      ​ 答案: 可以的.

    • 将c盘的 文本文件,比如 a.txt 拷贝 到D盘

      推荐使用字符流, 字节流也可以

    • 结论:

      字符流只能进行字符串的读写操作, 字节流可以操作任意类型的文件

  • 第一类方法:

    响应数据方法(服务器—响应数据:与浏览器绑定的输出流–>浏览器)

    • 字符输出流的方式

      PrintWriter out = response.getWriter();

      out.writer(“字符串数据”); //out.println(“字符串数据”);

    • 字节输出流的方式

      ServletOutputStream out = response.getOutputStream();

      out.write(字节数据); //out.println(字节数据);

/**
 *  注解中:
 *  value特权属性: 当注解中,有且仅有一个value属性时,
 *                 value可以省略不写.
 */
@WebServlet(urlPatterns = "/demo2")
public class Demo2Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //字节输出流响应数据
        //1. 获取字节输出流对象
        //OutputStream        out1 = response.getOutputStream();//多态写法
        ServletOutputStream out2 = response.getOutputStream();
        //2. 写方法, 响应数据
        String str = "hello 11111";//字符串
        byte[] bytes = str.getBytes();//字节数据
        out2.write(bytes);//字节数据
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
  • 第二类方法: 处理响应中文数据的乱码问题

    • 处理字符流响应数据的乱码问题

      比如: response.setContentType(“text/html;charset=utf-8”);

      ​ 服务器向浏览器响应文本数据, 文本的编码格式是utf-8

      比如: response.setContentType(“application/json;charset=utf-8”);

      ​ 服务器向浏览器响应的json数据, json数据编码格式是utf-8

      • text/html(固定写法,不唯一):

        字符输出流向浏览器响应的文本或者html网页数据

        application/json(固定写法,不唯一):

        字符输出流向浏览器响应的json数据

      • charset = utf-8 (utf-8编码格式,不固定的, 推荐使用)

      注意: 放在方法的第一行

      • 代码如下:

        /**
         * 名为 [com.tedu.web.Demo2Servlet]和 [com.tedu.web.Demo2ServletEncode] 的servlet
         * 不能映射为一个url模式(url-pattern) [/demo2]
         *  原因:  一个访问路径 对应两个不同的servlet
         */
        @WebServlet(urlPatterns = "/code1")
        public class Demo1ServletEncode extends HttpServlet {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                //1.处理响应中文的乱码问题
                // 字符输出流
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write("<a href='http://www.tedu.cn'>hello 字符流</a>");
        
            }
        }
        
        

第三类方法: 重定向方法

  • 重定向: 从一个资源跳转到另一个资源(比如:点击超链接跳转)

  • 方法:

    response.sendRedirect(“路径”);

    路径书写:绝对路径的书写方式

  • 需求一: 站外跳转

    从我们自己的网站重定向到达内官网

  • 需求二: 站内跳转

    从我们自己的网站重定向到自己网站的资源

package com.tedu.redirect;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* 需求一: 站外跳转
* 从我们自己的网站重定向到达内官网
* 1. 访问自己网站资源:http://localhost:8080/case2_response/outer
* 2. 代码内部: 重定向, 跳转到 "http://www.tedu.cn"
*/
@WebServlet("/outer")
public class ServletRedirectOuter extends HttpServlet {
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //1.处理响应中文的乱码问题
       response.setContentType("text/html;charset=utf-8");
       //2.重定向: 绝对路径
       String outerUrl = "http://www.tedu.cn";
       response.sendRedirect(outerUrl);
   }

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request, response);
   }
}

4.3 案例

案例: 企业级项目用户管理平台,实现登录功能.

  • 步骤一: 创建一个web项目: UserSystem(usermanagerment)

  • 步骤二: 在web目录下面, 创建一个登录页面login.html

  • 步骤三: 创建一个LoginServlet,处理登录请求

  • 总结:

    login.html------->

    LoginServlet判断: 用户名和密码正确,重定向到main.html

    ​ 用户名或者密码错误,提示用户错了,重新登录

  • 前端代码

main.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
            <!--http://localhost:8080/usersystem/index.html-->
           <h1>欢迎您: 访问我的网站</h1>
</body>
</html>
============================
login.html登录页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login page</title>
</head>
<body>
 <div style="margin:auto;text-align: center;border: 1px solid blue;width: 500px;">
    <form action="LoginServlet"   method="post">
        用户名:<input type="text" name="username"/>
        <br/>&nbsp;&nbsp;&nbsp;<input type="password" name="psw"/>
        <br/>
        <input type="submit" value="登录" />
    </form>


 </div>
</body>
</html>
  • 后端代码

    package com.tedu.web;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * 实现登录功能: 获取用户输入的用户名和密码, 判断是否正确
     */
    @WebServlet(urlPatterns = "/LoginServlet")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //1.处理请求中文的乱码问题
            request.setCharacterEncoding("utf-8");
            //2.处理响应中文的乱码问题
            response.setContentType("text/html;charset=utf-8");
            //3.获取用户输入的数据: 用户名和密码
            String user = request.getParameter("username");//用户名
            String password = request.getParameter("psw");//密码
            //4.进行判断,
            //4.1 如果用户名= admin , 密码= 111, 表示登录成功
            if(user.equalsIgnoreCase("admin") && password.equals("111")){
                //成功以后,跳转到主页面, 使用重定向
                String indexUrl = "http://localhost:8080/usersystem/main.html";//url
                response.sendRedirect(indexUrl);//重定向跳转
            }else{
                //4.3 不正确, 表示登录失败,让用户重新登录,显示登录连接
                String  info = "用户名或者密码错误,请重新登录!";
                String  loginUrl = "http://localhost:8080/usersystem/login.html";
                info+="<br/>";//第一层: 拼接换行
                info+="<a href='"+loginUrl+"'>点击,重新登录</a>";//第二层: 拼接超链接
                response.getWriter().println(info);
            }
    
    
        }
    
    }
    
    

五. Filter(理解)

5.1Filter概述

  • 实际生活过滤和拦截场景

    1. 场景: 渔网去捕鱼.

      ​ 渔网的作用: 过滤水, 拦截鱼儿

    2. 场景: 高速公路的收费站

      ​ 收费站的作用: 先拦截,交钱,放行

      ​ 一般情况下: 北京—香港高速路, 很多个收费站

      北京高速<------------>收费站1<--------------收费站2<------------>香港高速

      1. 经过收费站时: 北京—>香港

        交钱了合理请求,放行

      2.经过收费站: 香港---->北京

      交钱了合理请求,放行

    3. 场景: 交警晚上查酒驾

      ​ 交警的作用: 拦截小汽车,喝酒了,去局子做做,没有喝酒,放行

  • 过滤器介绍

    它是web开发的三大组件之一,

    它的主要作用: 对浏览器访问的资源进行拦截和放行

    • 拦截: 浏览器访问资源时-------->Filter: 拦截----->服务器的资源

      拦截: 静态资源和动态资源.

    • 放行:

      在过滤器里面进行判断,如果合理请求,就放行,如果非法请求,就不放行

    • 实际开发中:

      浏览器<--------->Filter1<------------>Filter2<----------->服务器

      1. 浏览器访问服务器的资源时,经过多个过滤器
      2. 浏览器向服务器发送请求; 请求过程,过滤器拦截
      3. 服务器向浏览器响应数据; 响应过程,过滤器拦截
    • 企业级开发,过滤器的场景

      1. 全局的post请求的中文乱码处理(案例)

      2. 进行敏感词汇过滤(案例) :

        浏览器—Filter:评论内容过滤---->服务器保存

      3. 进行权限校验

        浏览器—Filter:判断用户有没有权限---->服务器资源

      4. 等等

    在这里插入图片描述

5.2 Filter入门

  • 步骤一: 在创建的web项目,自定义一个类, 实现Filter接口

  • 步骤二: 在自定义类里面配置拦截路径

  • 步骤三: 在浏览器访问资源,进行测试

    package com.tedu;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import java.io.IOException;
    
    /**
     * 1.   implements Filter 自定义一个过滤器
     * 2.   拦截和放行
     *     配置拦截路径: @WebFilter()
     */
    @WebFilter(urlPatterns = "/home.html")
    public class DemoFilter1 implements Filter {
       /**
         * 拦截和放行方法
         * @param servletRequest: 请求对象
         * @param servletResponse: 响应对象
         * @param filterChain: 过滤器链, 可以实现放行
         * @throws IOException
         * @throws ServletException
         */
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("拦截home.html");
            //2.测试放行
            filterChain.doFilter(req,resp);
        }
    
        @Override
        public void destroy() {
            //执行一次,在服务器正常关闭执行
        }
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            //执行一次,在首次访问时执行
        }
    }
    
    

5.3 Filter的拦截路径配置

    1. 直接配置拦截资源名称:

      比如: /home.html, 只拦截home.html

    1. 扩展名拦截资源配置: *.html

      比如: *.html, 拦截所有后缀名为html的资源

      注意: 前面一定不要加 /

    2. 通配符拦截资源配置: /*

      比如: /* , 拦截所有资源 , * 匹配所有资源

5.4 过滤器链

  • 过滤器链介绍

    指的在开发中,配置了多个过滤器,多个过滤器构成链.

    实际场景: 哈喽单车链条,是不是一个一个的链子构成

  • 过滤器的执行顺序

    浏览器—>filter1--------->filter2—>服务器端资源

  • 注意:

    每个过滤器配置的拦截路径一定一样,才会形成过滤器链

5.5 案例

  • 需求: 处理全局的post请求的中文乱码问题

  • 思路:

    1. 定义一个过滤器,在里面: 处理post请求的中文乱码问题
    2. 拦截所有的servlet, 配置的拦截路径 /*
  • 代码如下

    package com.tedu.global;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    
    @WebFilter("/*")
    public class FilterGlobal implements Filter {
        public void destroy() {
        }
    
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
            //1.处理post请求中文乱码问题
            HttpServletRequest request = (HttpServletRequest)req;//类型转换
            //2.获取浏览器提交方式
            String method = request.getMethod();//获取请求方式: get, post
            if(method.equalsIgnoreCase("post")){
                request.setCharacterEncoding("utf-8");
            }
            //3.处理中文乱码
            chain.doFilter(request, resp);
        }
    
        public void init(FilterConfig config) throws ServletException {
    
        }
    
    }
    
    
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 43
    评论
评论 43
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值