转发、重定向与域的概念
之前的章节使用转发(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返回文字列
PrintWriter out = response.getWriter();out.write("ABC"); //将文字写到暂存区out.flush(); //将暂存区的文字输出out.close(); //关闭writer
使用ServletOutputStream输出byte stream资料
//取得专案路径,并加上"/"。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();
使用include动态嵌入页首页尾
在使用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的方法。只不过一个是用来组装页面,一个用来前往页面。