服务器之家

服务器之家 > 正文

JavaWeb入门:HttpResponse和HttpRequest详解

时间:2021-10-14 11:47     来源/作者:宁在春

HttpResponse 讲解

HttpServletResponse概述:

​ 在创建Servlet时会覆盖service()方法,或doGet()/doPost(),这些方法都有两个参数,一个为代表请求的request和代表响应response。service方法中的response的类型是ServletResponse,而doGet/doPost方法的response的类型是HttpServletResponse,HttpServletResponse是ServletResponse的子接口,功能和方法更加强大。

Response运行流程

JavaWeb入门:HttpResponse和HttpRequest详解

响应头有很多这里只介绍常用的。

JavaWeb入门:HttpResponse和HttpRequest详解

在浏览器可以按F12 抓包看响应头、请求头、具体的可以再查。

设置响应行

设置响应的状态码

 /** * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test3") public class HttpResponseTest3 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("设置状态码,前台通过判断状态码,来判断请求是否成功"); resp.setStatus(404); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

测试

JavaWeb入门:HttpResponse和HttpRequest详解

设置响应头

刷新 跳转页面

 /** * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test4") public class HttpResponseTest4 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置响应头 每1秒自动刷新 System.out.println("设置响应头 每1秒自动刷新"); resp.setHeader("Refresh", "1"); //定时跳转 3秒后将自动跳转 //        resp.setHeader("Refresh","3;URL=hello.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

测试

JavaWeb入门:HttpResponse和HttpRequest详解

一个小demo 实现刷新 页面累加

 /** * response * @author Adimi */ @WebServlet("/test4") public class ResponseTest4 extends HttpServlet { private static Integer id=1; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Refresh","1"); PrintWriter writer = response.getWriter(); id++; writer.print("id==>"+id); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

设置字符编码 解决中文乱码问题

 /** * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test1") public class HttpResponseTest1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决中文乱码问题 // 设置响应头 // 设置字符编码 resp.setCharacterEncoding("UTF-8"); // 设置响应内容以什么格式展示到页面 什么编码格式 包含了设置字符编码 resp.setContentType("text/html;charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.print("中国,你好!!!"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

测试

JavaWeb入门:HttpResponse和HttpRequest详解

重定向 redirect

 /** * 重定向 * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test5") public class HttpResponseTest5 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("hello.jsp"); //        resp.setHeader("location","www.baidu.com"); 通过设置响应头转发 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

request转发

 /** * 重定向 * @Author: crush * @Date: 2021-05-09 19:35 * version 1.0 */ @WebServlet("/test5") public class HttpResponseTest5 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //        resp.sendRedirect("hello.jsp"); req.getRequestDispatcher("hello.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

重定向和转发的区别

文件下载

获取路径资源

 String path=this.getServletContext().getRealPath("WEB-INF\\classes\\8.jpg");

读取资源

 FileInputStream fileInputStream=new FileInputStream(path);

获取到文件名,路径在电脑上保存的形式是 \ \

 String fileName=path.substring(path.lastIndexOf("\\")+1);

设置消息头告诉浏览器,我要下载1.png这个图片 设置编码

 resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); 

把读取到的内容回送给浏览器

 int len=0; byte[] bytes=new byte[1024]; // ServletOutputStream 提供用于将二进制数据发送到客户端的输出流 ServletOutputStream servletOutputStream=resp.getOutputStream(); while((len=fileInputStream.read(bytes))>0) { servletOutputStream.write(bytes,0,len); } 

关闭资源

 

 servletOutputStream.close(); fileInputStream.close();

注:8.jpg 放在我的resources 文件夹下 但是这里需要写的是编译完8.jpg存放的位置

JavaWeb入门:HttpResponse和HttpRequest详解

具体代码

 /** * @Author: crush * @Date: 2021-05-09 19:40 * version 1.0 */ @WebServlet("/down") public class ResponseDownFile extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取路径资源 String path=this.getServletContext().getRealPath("WEB-INF\\classes\\8.jpg"); //读取资源 FileInputStream fileInputStream=new FileInputStream(path); //获取到文件名,路径在电脑上保存的形式是\\ String fileName=path.substring(path.lastIndexOf("\\")+1); //设置消息头告诉浏览器,我要下载1.png这个图片 // 该方式文件名为中文时会乱码 //防止中文乱码 resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); //把读取到的内容回送给浏览器 int len=0; byte[] bytes=new byte[1024]; ServletOutputStream servletOutputStream=resp.getOutputStream(); while((len=fileInputStream.read(bytes))>0) { servletOutputStream.write(bytes,0,len); } // 关闭资源 servletOutputStream.close(); fileInputStream.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

HttpRequest 讲解

HttpServletRequest概述

​ 我们在创建Servlet时会覆盖service()方法,或doGet()/doPost(),这些方法都有两个参数,一个为代表请求的request和代表响应response。service()方法中写了根据请求方式的不同调用doget()和dopost().

service方法中的request的类型是ServletRequest,而doGet/doPost方法的request类型HttpServletRequest,HttpServletRequest是ServletRequest的子接口,功能和方法更加强大.

Request 运行流程

JavaWeb入门:HttpResponse和HttpRequest详解

获取请求携带的参数

 /** * @Author: crush * @Date: 2021-05-11 16:52 * version 1.0 */ @WebServlet("/request1") public class RequestTest1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 这里是请求的参数名  必须是同名的 String username = req.getParameter("username"); String password = req.getParameter("password"); PrintWriter writer = resp.getWriter(); writer.print("

"+username+":"+password+"

"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

JavaWeb入门:HttpResponse和HttpRequest详解

获取多个参数的值

 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置请求的编码  不然会乱码 req.setCharacterEncoding("utf-8"); Enumeration  names = req.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[]  values = req.getParameterValues(name); System.out.println(name+":"+ Arrays.toString(values)); } } 

获得请求行的信息

 /** * @Author: crush * @Date: 2021-05-11 16:52 * version 1.0 */ @WebServlet("/request3") public class RequestTest3 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获得请求的url StringBuffer requestURL = req.getRequestURL(); System.out.println("请求的URL===>"+requestURL); // 获得请求的Servlet的路径 String path = req.getServletPath(); System.out.println("请求的Servlet的路径===>"+path); //返回发出此请求的HTTP方法的名称,例如GET,POST或PUT String method = req.getMethod(); System.out.println("返回发出此请求的HTTP方法的名称==>"+method); //返回发送请求的客户端或最后一个代理的Internet协议(IP)地址 String remoteAddr = req.getRemoteAddr(); System.out.println("remoteAddr==>"+remoteAddr); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

request实现转发

 /** * @Author: crush * @Date: 2021-05-11 16:52 * version 1.0 */ @WebServlet("/request2") public class RequestTest2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 访问request2 转发到 request4去 req.getRequestDispatcher("/request4").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 

request是一个域对象

request对象也是一个存储数据的区域对象,所以也具有如下方法:

setAttribute(String name, Object o)

getAttribute(String name)

removeAttribute(String name)

ServletContext 作用域:

创建:启动web应用程序的时候创建

销毁:关闭web应用程序的时候销毁

域的作用范围:整个web应用的启动周期

request作用域:

创建:访问时创建request

销毁:响应结束request销毁

域的作用范围:一次请求中

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/weixin_45821811/article/details/116671015

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部