之前的章节使用转发(RequestDispatcher),将使用者送往下一个页面。如下:
request.getRequestDispatcher("/main/hello.jsp").forward(request, response);
但是转发前与转发後属於同一次HTTP request,所以url列也会保持一样。
如果使用者按了重新整理的话,可能就会造成问题。
例如在登入或付款页面这种关键操作,就必须使用重定向(sendRedirect)。如下例:
String path = request.getContextPath();
response.sendRedirect(path + "/main/hello.jsp");
由於重定向是两次不同的HTTP request,因此无法像转发一样使用request物件携带资料趴趴造,而是需要用生命周期更长的session来传递讯息。
召唤session的方式如下例:
request.getSession().setAttribute("username",username);
page 在当前页面有效(仅用於JSP中)
request 在当前请求中有效
session 在浏览器关闭前有效(也可设置逾期时间)
application 在服务器关机前有效
召唤application的方式如下例:
request.getServletContext();
Servlet除了返回给使用者HTML页面外,也可以返回文字列或byte stream资料(例如图片)。
这在使用AJAX技术(部分更新页面的技术)时会被使用到。
PrintWriter out = response.getWriter();
out.write("ABC"); //将文字写到暂存区
out.flush(); //将暂存区的文字输出
out.close(); //关闭writer
//取得专案路径,并加上"/"。
String path = request.getServletContext().getRealPath("/");
//组合成完整图片路径
String picName = path + "/pic/picture.png";
//以二次元阵列的方式读取档案
byte[] pic = FileUtils.readFileToByteArray(new File(picname));
//使用ServletOutputStream输出byte stream资料
ServletOutputStream out = response.getOutputStream();
out.write(pic);
out.flush();
out.close();
在使用PrintWriter写出资料时,也可以搭配include()来加入页首页尾。
RequestDispatcher head = request.getRequestDispatcher("/public/head.jsp");
RequestDispatcher foot = request.getRequestDispatcher("/public/foot.jsp");
PrintWriter out = response.getWriter();
head.include(request, response);
out.write("ABC");
foot.include(request, response);
out.flush();
out.close();
include()和forword()一样都是属於RequestDispatcher的方法。只不过一个是用来组装页面,一个用来前往页面。
<<: 老肝哥-菜鸟Java的LeetCode历程,第九题:Palindrome Number,朝远大目标前进!
来到了第四天,还在第一个练习,但每天都有一点不一样的收获, 今天练习到在Shape 底下加使用Rep...
Vim 编辑器 入门指南 (上) 思考速度多快 写程序速度就多快 目录 前言 什麽是 Vim ? 三...
最近正在学习git,想要透过把学到的东西写下来,来记录一下自己学到的东西,也方便以後回顾这些知识。 ...
上一篇我们说到怎样才算是把菜单送到老板手上呢? 送出菜单有两个步骤 顾客送出菜单 老板接收菜单 我们...
有鉴於我的Macbook pro开unreal engine时,实在是真的卡,所以只好先放着。 ...