一篇博客上手request和response

博客 动态
0 191
羽尘
羽尘 2023-04-19 16:27:28
悬赏:0 积分 收藏

一篇博客上手request和response

概念

request:获取请求数据
response:设置响应数据

Request

request继承体系

ServletRequest——Java提供的请求对象根接口
HttpServletRequest——Java提供的对http协议封装的请求对象接口
RequestFacade——tomcat实现定义类

request获取数据

package com.itheijma.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.BufferedReader;
import java.io.IOException;

@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String method() 获取请求方式
        String method = req.getMethod();
        System.out.println(method);
        //String getContextPath() 获取虚拟目录(项目访问路径)
        String contextPath = req.getContextPath();
        System.out.println(contextPath);
        //StringBuffer getRequestURL() 获取URL(统一资源定位符)
        StringBuffer url = req.getRequestURL();
        System.out.println(url.toString());
        //String getRequestURI() 获取URI(统一资源标识符)
        String uri = req.getRequestURI();
        System.out.println(uri);
        //String getQueryString() 获取请求参数(get方式)
        String queryString = req.getQueryString();
        System.out.println(queryString);

        //------------
        //获取请求头
        String agent = req.getHeader("user-agent");
        System.out.println(agent);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取post请求体:请求参数

        // 1. 获取字符输入流
        BufferedReader br = req.getReader();
        // 2. 读取数据
        String line = br.readLine();
        System.out.println(line);

    }
}

request通用的方式获取数据

package com.itheijma.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.Map;

@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //get请求逻辑
//        System.out.println("get...");

        // 1.获取所有参数的map集合
        Map<String, String[]> map = req.getParameterMap();
        for (String key : map.keySet()) {
            //username:zhangsan
            System.out.print(key+":");

            //获取值
            String[] values = map.get(key);
            for (String value : values) {
                System.out.print(value + " ");
            }

            System.out.println();
        }

        System.out.println("----------");

        // 2.根据key获取参数值,数组
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {

            System.out.println(hobby);
        }

        // 3. 根据key获取单个参数值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username);
        System.out.println(password);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //post请求逻辑
        this.doGet(req,resp);


//        System.out.println("post...");
//        // 1.获取所有参数的map集合
//        Map<String, String[]> map = req.getParameterMap();
//        for (String key : map.keySet()) {
//            //username:zhangsan
//            System.out.print(key+":");
//
//            //获取值
//            String[] values = map.get(key);
//            for (String value : values) {
//                System.out.print(value + " ");
//            }
//
//            System.out.println();
//        }
//
//        System.out.println("----------");
//
//        // 2.根据key获取参数值,数组
//        String[] hobbies = req.getParameterValues("hobby");
//        for (String hobby : hobbies) {
//
//            System.out.println(hobby);
//        }
//
//        // 3. 根据key获取单个参数值
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
//        System.out.println(username);
//        System.out.println(password);


    }
}

request请求参数中文乱码解决方法

package com.itheijma.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.nio.charset.StandardCharsets;


/**
 * 中文乱码问题解决方案
 */
@WebServlet("/req3")
public class RequestDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 解决乱码 POST 获取参数方式:getReader()读取数据流
        request.setCharacterEncoding("utf-8"); //设置字符输入流的编码


        // 2. 获取username
        String username = request.getParameter("username");
        System.out.println("解决乱码前:"+username);


        // 3. 解决乱码 GET 获取参数方式:getQueryString
        // 乱码原因:tomcat进行url解码,默认的字符集ISO-8859-1
//        // 3.1 先对乱码数据进行编码:转为字节数组
//        byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
//        // 3.2 字节数组解码
//        username = new String(bytes, StandardCharsets.UTF_8);

        username = new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);

        System.out.println("解决乱码后"+username);


    }
}

request请求转发

请求转发(forward):一种在服务器内部的资源跳转方式。
请求转发特点:

  1. 浏览器地址栏路径不发生变化
  2. 只能转发到当前服务器的内部资源
  3. 一次请求,可以在转发的资源间使用request共享数据
    req4
package com.itheijma.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.nio.charset.StandardCharsets;


/**
 * 请求转发
 */
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo4");

        //存储数据
        request.setAttribute("msg","hello");

        //请求转发
        request.getRequestDispatcher("/req5").forward(request,response);
    }
}

req5

package com.itheijma.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("/req5")
public class RequestDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo5");

        //获取数据
        Object msg = request.getAttribute("msg");
        System.out.println(msg);
    }
}

response

Response完成重定向

重定向:一种资源跳转的方式
resp1

package com.itheima.web.response;

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("/resp1")
public class ResponseDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("resp1...");

//        // 重定向
//        // 1. 设置状态码 302
//        response.setStatus(302);
//        // 2. 设置响应头 Location
//        response.setHeader("Location","/tomcat-demo2/resp2");

        // 简化方式完成重定向
        response.sendRedirect("/tomcat-demo2/resp2");

    }
}

resp2

package com.itheima.web.response;

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("/resp2")
public class ResponseDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("resp2...");
    }
}

重定向特点:

  1. 浏览器地址栏路径发生变化
  2. 可以重定向到任意位置的资源(服务器内、外部均可)
  3. 两次请求,不能在多个资源使用request共享数据

资源路径问题(什么时候加虚拟目录)
浏览器使用:需要加虚拟目录
服务端使用:不需要加虚拟目录

动态获取虚拟目录

        //动态获取虚拟目录
        String contextPath = request.getContextPath();
        response.sendRedirect(contextPath + "/resp2");

Response响应字符数据

package com.itheima.web.response;

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.io.PrintWriter;


/**
 * 响应字符数据:设置字符数据的响应体
 */
@WebServlet("/resp3")
public class ResponseDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取字符输出流
        PrintWriter writer = response.getWriter();
        //content-type
        //response.setHeader("content-type","text/html");
        writer.write("你好");
        writer.write("<h1>aaa</h1>");

        //细节:流不需要关闭
    }
}

Response响应字节数据

package com.itheima.web.response;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
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.io.PrintWriter;


/**
 * 响应字节数据:设置字节数据的响应体
 */
@WebServlet("/resp4")
public class ResponseDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

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

        // 1. 读取文件
        FileInputStream fis = new FileInputStream("e://a.jpg");

        // 2. 获取response字节输出流
        ServletOutputStream os = response.getOutputStream();

        // 3. 完成流的copy

//        byte[] buff = new byte[1024];
//        int len = 0;
//        while ((len = fis.read(buff)) != -1){
//            os.write(buff,0,len);
//        }
        IOUtils.copy(fis,os);//使用工具类

        fis.close();
    }
}

pom文件导入工具类

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
posted @ 2023-04-19 15:49  鹤城  阅读(0)  评论(0编辑  收藏  举报
回帖
    羽尘

    羽尘 (王者 段位)

    2335 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员