一、Http响应案例:
1、请求重定向(Location):
package sram.response;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecondResponse extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 需求: 跳转到adv.html
* 使用请求重定向: 发送一个302状态码+location的响应头
*/
response.setStatus(302);
response.setHeader("location", "/servlet_test/adv.html");//后一个参数写成"/adv.html"也是OK的
response.sendRedirect("/servlet_test/adv.html");//请求重定向简化写法
}
}
2、定时刷新(refresh):
package sram.response;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ThirdResponse extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 定时刷新
* 原理:浏览器认识refresh头,得到refresh头之后重新请求当前资源
*/
response.setHeader("refresh", "1");//每隔1秒刷新次页面
response.setHeader("refresh","3;url=/servlet_test/adv.html");//这里就不能写成url=/adv.html
}
}
3、content-Type作用
package sram.response;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ForthResponse extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setHeader("content-type", "text/html");
//response.setContentType("text.html");//和上面代码等价,推荐使用此方法。
response.setContentType("text/xml");//格式有哪些可以查阅tomcat——>conf——>web.xml
response.getWriter().write("<html><head><title>this is tilte</title></head><body>HelloWorld</body></html>");
}
}
二、Http响应编码问题:
1、编码问题:
2、问题分析:
3、问题解决:
1)字符流:
2)字节流:
4、案例:设置以下载方式打开文件
三、Servlet项目编码问题总结图: