java web筆記之認識request和response

1.認識request

客戶端瀏覽器發出的一個請求被封裝成一個HttpServletRequest對象。所有的信息包括請求的地址,請求的參數,提交的數據,上傳的文件,客戶端的IP地址甚至客戶端操作系統都包含在HttpServletRequest對象中。

2.認識response

服務器對客戶端瀏覽器的響應被封裝成一個HttpServletResponse對象。要對瀏覽器進行操作,只需要操作HttpServletResponse對象就可以了。通過HttpServletResponse.getWriter()獲得一個PrintWriter對象,該對象爲OutputStream的子類。然後使用該對象輸出信息就可以了。
通過HttpServletResponse獲取的PrintWriter對象只能寫字符型的數據。如果需要在客戶端寫二進制數據,可以使用HttpServletResponse.getOutputStream()。方法getWriter()可以看做是方法getOUtoutStream()的一個封裝。

3.response生成圖片驗證碼

IdentityServlet
package com.wang.indentity;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

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

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class IdentityServlet extends HttpServlet{
	//隨機字符串,不包括0O1I等難以辨認的字符串
	public static final char[] CHARS = {'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'};

	public static Random random = new Random(); //隨機數
	
	//獲取6爲隨機數
	public static String getRandomString(){
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			buffer.append(CHARS[random.nextInt(CHARS.length)]);  //每次區一個隨機字符串
		}
		return buffer.toString();
	}
	//獲取隨機顏色
	public static Color getRandomColor(){
		return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
	}
	
	//返回某顏色的反色
	public static Color getReverseColor(Color c){
		return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
	}
	
	public void doGet(HttpServletRequest request,HttpServletResponse response) {
		response.setContentType("image/jpeg");
		
		String randomString = getRandomString();
		
		request.getSession(true).setAttribute("randomString", randomString);//放到session中
		
		int width = 100;//圖片寬度
		
		int height = 30;//圖片高度
		
		Color color = getRandomColor();//隨機顏色用於背景色
		
		Color reverse = getReverseColor(color);//反色用於前景色
		
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//創建一個彩色圖片
		
		Graphics2D g = bi.createGraphics();//獲取繪圖對象
		
		g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));//設置字體
		
		g.setColor(color);//設置顏色
		
		g.fillRect(0, 0, width, height);//繪製背景
		
		g.setColor(reverse);  //設置顏色
		
		g.drawString(randomString, 18, 20); //繪製隨機字符串
		
		for (int i = 0 , n=random.nextInt(100); i < n; i++) {
			g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);//畫最多100個噪點
		}
		
		ServletOutputStream out;
		try {
			out = response.getOutputStream();//轉成JPEG格式
			
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);//編碼器
			
			encoder.encode(bi);//對圖片進行編碼
			out.flush();//輸出到客戶端
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>IdentityServlet</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>IdentityServlet</servlet-name>
  	<servlet-class>com.wang.indentity.IdentityServlet</servlet-class>
  	<load-on-startup>1</load-on-startup>
  
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>IdentityServlet</servlet-name>
  	<url-pattern>/servlet/IdentityServlet</url-pattern>
  </servlet-mapping>
  
  
</web-app>
identity.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>

<script>
		function reloadImage(){
			//document.getElementById('btn').disabled = true;
			
			document.getElementById('identity').src = 'servlet/IdentityServlet?ts='+new  Date().getTime();
		}

</script>
</head>
<body>

<img  id = "identity" src="servlet/IdentityServlet" onload = "btn.disable = false;">

<input type="button" value="換個圖片" onclick = "reloadImage()" id="btn" >

</body>
</html>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章