使用HttpServletResponse修改響應數(shù)據(jù):
response.setStatus(404) 設置狀態(tài)碼
response.setHeader("name","value") 修改響應頭
response.getWriter().write() 以字符形式發(fā)送實體內(nèi)容
response.getOutputStream().write() 以字節(jié)形式發(fā)送實體內(nèi)容
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//設置狀態(tài)碼
//response.setStatus(404);
//response.sendError(404); // 404+404錯誤頁面
//修改響應頭
response.setHeader("server", "webLogic");
//修改實體內(nèi)容
response.getWriter().write("this is content!"); //字符流
//response.getOutputStream().write("this is content!!!".getBytes()); //字節(jié)流
}
請求重寫向案例:
定時刷新或每隔n秒跳轉(zhuǎn)頁面案例:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//定時2秒刷新
//response.setHeader("refresh", "2");
response.setContentType("text/html;charset=utf-8");
//每隔n秒跳轉(zhuǎn)頁面
response.getWriter().write("注冊成功涌韩!3秒之后會跳轉(zhuǎn)到主頁");
//設置refresh
response.setHeader("refresh", "3;/ServletStudy/register.html");
}
content-type案例:
服務器發(fā)送給瀏覽器的數(shù)據(jù)類型和數(shù)據(jù)編碼格式
具體MIME類型可以參考:
設置數(shù)據(jù)編碼格式 兩個作用:
- 設置輸出數(shù)據(jù)的編碼
- 告訴瀏覽器自動適應輸出數(shù)據(jù)的編碼
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//設置content-type響應
//response.setHeader("content-type", "text/html;charset=utf-8");
//response.setContentType("text/html;charset=utf-8");//等價于上面的代碼
response.setContentType("text/html;charset=utf-8"); //和下面的代碼是效果是一樣的踱启。
//response.setCharacterEncoding("utf-8"); //不會告訴瀏覽器自動跳轉(zhuǎn)解碼的碼表
response.getWriter().write("<b>程序員擼碼一生</b>");
}