页面重定向概述
向客户浏览器发送页面重定向指令,浏览器接收后将向Web服务器重新发送页面请求,所以执行完后浏览器的url显示的是跳转后的页面。跳转页面可以是一个任意的URL。
HttpServletResponse的sendRedirect方法向客户浏览器发送页面重定向指令
HttpServletResponse接口
继承自ServletResponse接口。是一个返回到客户端的HTTP响应。
重要方法:
sendRedirect
public void sendRedirect(String location) throws IOException;
使用给定的路径, 给客户端发出一个临时转向的响应
ServletResponse接口
重要方法:
1.getCharacterEncoding
public String getCharacterEncoding();
返回相应使用字符解码的名字,默认为ISO-8859-1。
2.getOutputStream
public ServletOutputStream getOutputStream() throws IOException;
返回一个记录二进制的响应数据的输出流。
3.getWriter
public PrintWriter getWriter throws IOException;
这个方法返回一个PringWriter对象用来记录格式化的响应实体。
4.setContentLength
public void setContentLength(int length);
设置响应的内容的长度,这个方法会覆盖以前对内容长度的设定。
5.setContentType
public void setContentType(String type);
这个方法用来设定响应的content类型。
案例
一个具有表单的jsp页面(temp.jsp),点击提交按钮后,Servlet接收表单数据,不直接生成HTML页面输出接收到的这个数据。而是通过重定向技术后跳转到一个新的jsp页面(welcome.jsp),表单的数据直接作为重定向的URL参数值的方式传递给这个jsp页面。
具体编码:
jsp页面:
<body>
<form action="Output">
对我说Hello:<input name="word"type="text"><br>
<input name="enter"type="submit" value="确定">
<input id="cancel" type="reset" value="取消">
</form>
</body>
Servlet程序:
Output.java:
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String word =request.getParameter("word");
response.setContentType("text/html;charset=utf-8");
java.io.PrintWriter out=response.getWriter();
out.println(name);
}
转换成:不由servlet直接输出网页内容,而从Servlet中进行页面重定向,由另一个新的页面输出结果值。即是完成了jsp页面负责了“输出”。
Servlet程序:
protectedvoid doGet(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name =request.getParameter("word");
response.setContentType("text/html;charset=utf-8");
response.sendRedirect("welcome.jsp");
// java.io.PrintWriter out=response.getWriter();
// out.println(name);
}
提交数据到该页面:
protectedvoid doGet (HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String word=request.getParameter("name");
response.setContentType("text/html;charset=utf-8");
response.sendRedirect("welcome.jsp?word="+word);
// java.io.PrintWriter out=response.getWriter();
// out.println(name);
}
welcome.jsp:
<body>
文本框输入的是:<%=request.getParameter("word") %>
</body>
视频
对Serlvet页面重定向进行了介绍,并通过案例对比页面重定向和上节Serlvet生成页面构成客户端响应的对比。

