世界视点!一篇博客上手request和response

2023-04-20 17:00:15 | 来源:博客园


(资料图)

概念

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

Requestrequest继承体系

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 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 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):一种在服务器内部的资源跳转方式。请求转发特点:

浏览器地址栏路径不发生变化只能转发到当前服务器的内部资源一次请求,可以在转发的资源间使用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);    }}
responseResponse完成重定向

重定向:一种资源跳转的方式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...");    }}

重定向特点:

浏览器地址栏路径发生变化可以重定向到任意位置的资源(服务器内、外部均可)两次请求,不能在多个资源使用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("

aaa

"); //细节:流不需要关闭 }}
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文件导入工具类

            commons-io            commons-io            2.6        
上一篇 下一篇

相关新闻

世界视点!一篇博客上手request和response

狂野之心1.2版爆矢弓箭配装搭配攻略一览

【世界时快讯】概念动态|品高股份新增“人工智能”概念

微速讯:【新华500】新华500指数(989001)19日下跌0.9%

千红制药(002550)4月20日主力资金净卖出1441.40万元_最新资讯

这个火车站客流暴增,原因竟是…… 全球微头条

世界实时:浐灞生态区获评西北首个“中国产学研合作创新示范基地”

速读:子州路125号

打新请关注!新一周1只可转债上市(4月24日-4月28日)-天天实时

泡泡玛特(09992)第一季度整体收益同比增长0%-5%

Meta(META.US)公布业绩前,美银上调目标价至250美元 环球速看

“名人堂成员”驾到 特斯拉将在Q3举行Cybertruck交付仪式|全球新动态

sus316和316l的区别_316和316l有什么区别_全球观热点

智慧家庭业务成运营商新“宠” 平治信息乘势而上构建智慧家庭“神经末梢”

数字基建扩容提速|世界报道

最新新闻

世界视点!一篇博客上手request和response

狂野之心1.2版爆矢弓箭配装搭配攻略一览

【世界时快讯】概念动态|品高股份新增“人工智能”概念

微速讯:【新华500】新华500指数(989001)19日下跌0.9%

千红制药(002550)4月20日主力资金净卖出1441.40万元_最新资讯

这个火车站客流暴增,原因竟是…… 全球微头条

世界实时:浐灞生态区获评西北首个“中国产学研合作创新示范基地”

速读:子州路125号

打新请关注!新一周1只可转债上市(4月24日-4月28日)-天天实时

泡泡玛特(09992)第一季度整体收益同比增长0%-5%

Meta(META.US)公布业绩前,美银上调目标价至250美元 环球速看

“名人堂成员”驾到 特斯拉将在Q3举行Cybertruck交付仪式|全球新动态

sus316和316l的区别_316和316l有什么区别_全球观热点

智慧家庭业务成运营商新“宠” 平治信息乘势而上构建智慧家庭“神经末梢”

数字基建扩容提速|世界报道

环球时讯:鼓励家庭搬离首都圈,日本政府提高未成年人迁居补助

86岁谢贤登山聚餐被偶遇,双腿快和女生一样细,穿黑夹克潮流有范-最新

生化试剂有哪些(生化试剂) 环球头条

世界信息:电视节目主持人 李蕾_电视节目主持人

当前短讯!翼龙贷借款逾期24年会上征信系统吗

国际实业:4月19日融资买入1268.98万元,融资融券余额3.29亿元|时快讯

【港股异动】海尔智家(06690.HK)跌3.01%

找临时工在哪个平台上找比较真实可靠_找临时工

辣椒炒鸡蛋

主播说联播丨4.5%背后,是活力满满

让库克张大嘴巴:顾客抱着Macintosh参加印度首家苹果零售店开幕|天天报资讯

如何解决生成式AI不断增长的碳足迹问题

2023胡润全球独角兽榜:前十名中国占五席 字节跳动蝉联第一 今日报

怎么添加网络打印机 网络打印机连接不上?

生命的价值阅读答案第一题_生命的价值阅读答案_天天热资讯