JavaWeb中HttpResponse和HttpRequest如何使用,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
在创建Servlet时会覆盖service()方法,或doGet()/doPost(),这些方法都有两个参数,一个为代表请求的request和代表响应response。service方法中的response的类型是ServletResponse,而doGet/doPost方法的response的类型是HttpServletResponse,HttpServletResponse是ServletResponse的子接口,功能和方法更加强大。
响应头有很多这里只介绍常用的。
在浏览器可以按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); } }
测试
刷新 跳转页面
/** * @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); } }
测试
/** * 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); } }
测试
/** * 重定向 * @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); } }
/** * 重定向 * @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存放的位置
具体代码
/** * @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); } }
我们在创建Servlet时会覆盖service()方法,或doGet()/doPost(),这些方法都有两个参数,一个为代表请求的request和代表响应response。service()方法中写了根据请求方式的不同调用doget()和dopost().
service方法中的request的类型是ServletRequest,而doGet/doPost方法的request类型HttpServletRequest,HttpServletRequest是ServletRequest的子接口,功能和方法更加强大.
/** * @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("<h2>"+username+":"+password+"</h2>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置请求的编码 不然会乱码 req.setCharacterEncoding("utf-8"); Enumeration<String> 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); } }
/** * @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对象也是一个存储数据的区域对象,所以也具有如下方法:
setAttribute(String name, Object o)
getAttribute(String name)
removeAttribute(String name)
创建:启动web应用程序的时候创建
销毁:关闭web应用程序的时候销毁
域的作用范围:整个web应用的启动周期
创建:访问时创建request
销毁:响应结束request销毁
域的作用范围:一次请求中
关于JavaWeb中HttpResponse和HttpRequest如何使用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。