Response及案例(重定向、自動刷新、禁用緩存、中文亂碼、文件下載、驗證碼)

缺省的Servlethtml

在tomcat/conf/web.xml中java

 <init-param>web

            <param-name>listings</param-name>數組

            <param-value>false    這個改爲true</param-value>瀏覽器

        </init-param>緩存

 

response對象(響應對象)tomcat

  想要獲取客戶端的內容,使用request對象;對客戶端做出響應使用responsedom

 

狀態碼 jsp

setStatus(int sc)  設置狀態碼,如302字體

sendError(int sc):發送錯誤的狀態碼  如40四、500

sendError(int sc,String msg):發送錯誤的狀態碼,而且加上附加信息

 

   響應頭(key:value的形式出現的,一個key對應一個value 一個key對應多個value)    下面add開頭的不多見

   一、setHeader(String name,String value) 一個key對應一個value

        如 setHeader(「aa」, 「bb」);

           setHeader(「aa」, 「cc」);

         結果爲 aa:cc 會進行覆蓋

   二、addHeader(String name,String value) 一個key對應多個value

        如 setHeader(「aa」, 「bb」);

            setHeader(「aa」, 「cc」);

          結果 aa:bb,cc   會進行追加

   三、setIntHeader(String name,int value) 單值的int類型的響應頭

   四、addIntHeader(String name,int value) 多值的int類型的響應頭

   五、setDateHeader(String name,long value) 單值的毫秒類型的響應頭

   六、addDateHeader(String name,long value) 多值的毫秒類型的響應頭

   響應體

   ServletOutputStream getOutputStream() 字符輸出流

   PrintWriter getWriter()

 

重定向案例 

package cn.idcast.response;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 用戶請求訪問ResponseServlet,而後ResponseServlet響應302,給出Location頭
 *   瀏覽器會重定向到ResponseServlet2
 */
public class ResponseServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("ResponseServlet");
		// 下面2個方法均可以用,建議重定向用第二個比較方便
		// response.setHeader("Location", "/Day4/ResponseServlet2");   //重定向到下面的那個頁面  記得項目名前面要加 /
		// response.setStatus(302);

		response.sendRedirect("/Day4/ResponseServlet2");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

  

package cn.idcast.response;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseServlet2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("ResponseServlet2");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

  自動刷新案例

package cn.idcast.response;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseRefresh extends HttpServlet {
	// 自動刷新
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().write("5second");
		// 表示5秒後將會自動跳轉到/Day4/Refresh2這個頁面
		response.setHeader("Refresh", "5;Url=/Day4/Refresh2");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

  

package cn.idcast.response;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ResponseRefresh2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().write("hahah");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

  禁用瀏覽器緩存(三個頭信息)

Cache-Control   no-cache

expires     這裏是  -1       要用setDateHeader   其餘2個都是setHeader

pragma   no-cache

   不用記   只要在index.jsp裏面找 就能夠

  

   中文亂碼

字節輸入中文亂碼問題   不必定亂碼

 解決方法

一、設置瀏覽器打開文件時所採用的編碼。

二、獲取字符串byte數組時編碼和打開文件時編碼一致。

response.setHeader(「Content-Type」,「text/html;charset=UTF-8」);

os.write(「你好」.getBytes(「UTF-8」));

 

字符輸入中文亂碼問題   確定亂碼

解決方法

一、設置response緩衝編碼

二、設置瀏覽器打開文件所採用的編碼

response.setCharacterEncoding(「UTF-8」);

response.setHeader(「Content-Type」,「text/html;charset=UTF-8」);

  這2句能夠簡寫成response.setContentType(「text/html;charset=UTF-8」);

 案例

package cn.idcast.response;

import java.io.IOException;
import java.io.OutputStream;
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 OutServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 解決字節中文亂碼問題 記得解決亂碼要寫在前面
		// OutputStream os = response.getOutputStream();
		// response.setHeader("Content-Type", "text/html;charset=UTF-8");
		// os.write("你好啊".getBytes("UTF-8"));
		// 解決字符中文亂碼問題 記得解決亂碼要寫在前面
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write("哈哈哈");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

  

  文件下載 

一、先準備一個文件

二、讀取文件,讀入到輸出流中

三、經過response讀出到瀏覽器

四、設置頭信息

Content-Disposition      attachment;filename=文件名稱

以附件的形式打開

 代碼

package cn.idcast.response;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {
	// 實現文件的下載,以附件的形式
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String path = getServletContext().getRealPath("/img/1.jpg");
		/*
		 * 這步是把文件路徑設置讓他不要寫死了 好比文件是在c:\tomcat\1.jpg裏面
		 */
		String filename = null;
		int index = path.lastIndexOf("\\");
		// 若是文件存在的話
		if (index != -1) {
			filename = path.substring(index + 1);
		}
		// 設置頭信息,"Content-Disposition", "attachment;filename=文件名稱"
		response.setHeader("Content-Disposition", "attachment;filename="
				+ filename);
		// 獲得文件的路徑:絕對路徑
		InputStream is = new FileInputStream(path);
		OutputStream os = response.getOutputStream();
		// 字節流
		byte[] b = new byte[1024];
		int len = 0;
		while ((len = is.read(b)) != -1) {
			os.write(b, 0, len);
		}
		is.close();

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

    驗證碼案例

package cn.idcast.response;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 在內存中生成圖片,由於沒有方法設置背景顏色,因此要畫一個填充的矩形,而且和畫布的大小相同,矩形有顏色,最好要畫個矩形邊框
 * 獲取筆的對象(設置顏色、字體,畫驗證碼)
 * 先準備好數據,隨機生成4個字符,把字符畫到紙上
 * 畫干擾線
 * 把內存中的圖片輸出到客戶端上。
 * 
 * 
 */
public class DrawServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 在內存生成一張圖片
		int width = 100;
		int height = 50;
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 由於要用到弧度,因此用2D的畫筆對象
		Graphics2D g = (Graphics2D) bi.getGraphics();
		g.setColor(Color.YELLOW);
		// 用矩形填充
		g.fillRect(0, 0, width, height);
		g.setColor(Color.BLUE);
		// 畫一個邊框,由於旁邊會重合,因此-1
		g.drawRect(0, 0, width - 1, height - 1);
		// 得到驗證碼
		String s = "qwertyuiopasdfghjjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
		g.setColor(Color.BLACK);
		// 設置驗證碼的字體
		g.setFont(new Font("宋體", Font.BOLD, 20));
		Random r = new Random();
		int x = 20;
		int y = 20;
		for (int i = 0; i < 4; i++) {
			// 獲取角度和弧度 弧度的公式爲:角度*π/180,角度在正負30之間
			int jiaodu = r.nextInt(60) - 30;
			Double hudu = jiaodu * Math.PI / 180;
			g.rotate(hudu, x, y);
			// 獲取驗證碼的下標
			int index = r.nextInt(s.length());
			// 返回指定下標位置的字符,隨機獲取下標
			char ch = s.charAt(index);
			// 把驗證碼寫到畫布上
			g.drawString("" + ch, x, y);
			// 由於字體旋轉有可能會旋轉到畫布外面,因此要歸零
			g.rotate(-hudu, x, y);
			// 驗證碼得有間隔
			x += 20;
		}
		// 設置干擾線
		g.setColor(Color.RED);
		int x1, y1, x2, y2;
		// 干擾線的不能超出畫布的位置
		for (int i = 0; i < 4; i++) {
			x1 = r.nextInt(width);
			y1 = r.nextInt(height);
			x2 = r.nextInt(width);
			y2 = r.nextInt(height);
			g.drawLine(x1, y1, x2, y2);
		}
		// 把內存的圖片輸出到客戶端中
		ImageIO.write(bi, "jpg", response.getOutputStream());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
相關文章
相關標籤/搜索