学习笔记,javaWeb中的Response

Response用来封装服务器向客户端返回的数据。

示例1,简单使用response返回数据

package response;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
 * Response负责服务器的响应,这个对象封装了向客户端发送数据,发送响应头和发送响应状态码的方法
 */
public class ResponseDemo extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//获得输出流
		OutputStream out = resp.getOutputStream();
		
		//解决浏览器乱码问题,方法一:同时设置数据编码和解码的方式
		//设置response使用的码表,控制response以什么码表向浏览器写出数据
		resp.setCharacterEncoding("UTF-8");
		//通过response设置响应头,控制浏览器解码方式,控制浏览器以什么码表显示数据
		resp.setHeader("Content-type", "text/html;charset=UTF-8");
		
		//解决浏览器乱码问题,方法二:通过<meta>设置浏览器解码方式
		//<meta>标签可以模拟一个http响应头,所以解码方式也可以通过下面的方式来设置,对IE有效
//		out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());
		
		//解决浏览器乱码问题,方法三:通过response的方法设置解码方式
//		resp.setContentType("text/html;charset=UTF-8");
		
		//测试数据为中文时
		String s = "中文";
		out.write(s.getBytes());
		out.write(s.getBytes("UTF-8"));
		
		out.write(97);//输出时进行了转换,因此会输出a
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}

示例2,向客户端提供下载,以及验证码

package 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.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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;


/*
 * 1. 服务器提供下载
 * 2. 验证码图片生成
 */
public class ResponseDemo2 extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//下载文件方法
		download(resp);
		
		//验证码图片生成
//		checkImage(resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	//下载文件方法
	private void download(HttpServletResponse resp)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		//获得文件在服务器中的绝对路径
		String path = this.getServletContext().getRealPath("/download/1.mp3");
		//从全路径中截取出文件名
		String filename = path.substring(path.lastIndexOf("\\")+1);
		
		//设置可下载文件属性
		//如果下载文件是中文文件名,则文件名需要经过url编码,URLEncoder.encode(filename, "UTF-8")
		resp.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename, "UTF-8"));
		
		//文件传输(下载文件)
		InputStream in  = new FileInputStream(path);
		OutputStream out = resp.getOutputStream();
		int len = 0;
		byte[] buf = new byte[1024];
		while((len=in.read(buf))!=-1){
			out.write(buf, 0, len);
		}
		
		in.close();
		out.close();
	}
	
	//生成验证码
	private void checkImage(HttpServletResponse resp)throws ServletException, IOException{
		//设置图片大小和颜色
		BufferedImage image = new BufferedImage(120, 25, BufferedImage.TYPE_INT_RGB); 
		//获得图形对象
		Graphics  g = image.getGraphics();
		
		//这是背景
		setBackGround(g);
		//设置边框
		setBorder(g);
		//设置干扰线
		drawRandomLine(g);
		//设置随机字
		drawRandomNum((Graphics2D)g);
		
		//设置头清空缓存
		resp.setDateHeader("expries", -1);
		resp.setHeader("Cache-Control", "no-cache");
		resp.setHeader("param", "no-cache");
		
		//设置图片输出类型
		resp.setContentType("image/jpeg");
		//向浏览器输出图像
		ImageIO.write(image, "jpg", resp.getOutputStream());
	}

	//填入随机数字
	private void drawRandomNum(Graphics2D g) {
		//随机字,取值范围[\u4e00-\u9fa5]
		String[] s = {"1","2","3","4","5","6","7","8","9","0",
					  "一","二","三","四","五","六","七","八","九","零",
					  "壹","贰","叁","肆","伍","陆","柒","捌","玖"};
		//设置颜色为红色
		g.setColor(Color.RED);
		//设置字体为宋体,加粗,20px大小
		g.setFont(new Font("宋体", Font.BOLD, 20));
		//连续输出四个字
		for(int i=0;i<4;i++){
			//获得随机数字-30~30,用于字的旋转
			int degree = new Random().nextInt()%30;
			//按数值进行相应的旋转
			g.rotate(degree*Math.PI/180, i*20+20,20);
			
			//从数组中随机获得一个字符
			int index = new Random().nextInt(s.length);
			//输出字符图像
			g.drawString(s[index], i*20+20, 20);
			//将弧度还原,便于下一个字的旋转
			g.rotate(-degree*Math.PI/180, i*20+20,20);
		}
	}
	//填入干扰线
	private void drawRandomLine(Graphics g) {
		//设置颜色为灰色
		g.setColor(Color.GRAY);
		for(int i=0;i<5;i++){
			//随机设置起始点
			int startX = new Random().nextInt(120);
			int startY = new Random().nextInt(25);
			int endX = new Random().nextInt(120);
			int endY = new Random().nextInt(25);
			//输出干扰线,
			g.drawLine(startX, startY, endX, endY);
		}
		
	}
	//设置边框
	private void setBorder(Graphics g) {
		//设置颜色为蓝色
		g.setColor(Color.BLUE);
		//边框要画在图片内, 因此起点和终点要计算
		g.drawRect(1, 1, 118, 23);
	}
	//设置背景
	private void setBackGround(Graphics g) {
		//背景颜色为白色
		g.setColor(Color.WHITE);
		//填充整个矩形
		g.fillRect(0, 0, 120, 25);
	}
}
</pre><p>验证码展示页面:</p><p></p><pre name="code" class="html"><!DOCTYPE>
<html>
	<head>
		<title>验证码</title>
                <!-- 点击图片刷新验证码 -->
		<script type="text/javascript">
			function change(img){
				img.src=img.src+"?"+new Date().getTime();
			}
		</script>
	</head>
	<body>
		<form action=""> 
			用户名:<input type="text" name="username"><br />
			密 码:<input type="password" name="password"><br />
			验证码:<input type="text" name="checkCode" ><img src="/javaWeb/ResponseDemo2" οnclick="change(this);" style="cursor:hand"/><br />
			<input type="submit" value="注册">
		</form>
	</body>
</html>


示例3,控制页面定时跳转

package 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 ResponseDemo3 extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//定时刷新
//		refresh(resp);
		refresh2(req,resp);
	}
	
	//定时刷新,并跳转到新链接
	private void refresh(HttpServletResponse resp) throws IOException {
		
		//设置浏览器编解码
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Content-type", "text/html;charset=UTF-8");
		//控制3秒刷新后,跳转到url='/javaWeb/register.html'地址
		resp.setHeader("refresh", "3;url='/javaWeb/register.html'");
		//向浏览器输出消息
		String s = "浏览器会在3秒后跳转到指定页面,如果没有跳转,请点击<a href='http://www.baidu.com'>超链接进行跳转</a>";
		resp.getOutputStream().write(s.getBytes());
	}
	
	//定时刷新,并跳转到新链接
	private void refresh2(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
		//设置浏览器编解码
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Content-type", "text/html;charset=UTF-8");
		//通过设置jsp中的<meta>实现3秒定时跳转
		String message = "<meta http-equiv='refresh' content='3;url=/javaWeb/index.jsp'>浏览器会在3秒后跳转到指定页面,如果没有跳转,请点击<a href='/javaWeb/index.jsp'>超链接进行跳转</a>";
		//将消息传递给message.jsp
		this.getServletContext().setAttribute("message", message);
		this.getServletContext().getRequestDispatcher("/message.jsp").forward(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
}

跳转前页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>定时跳转</title>
	</head>
	<body>
		<% 
			String message = (String)application.getAttribute("message"); 
			out.write(message); 
		 %>
	</body>
</html>


示例4,设置页面缓存,页面重定向

package 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;

/*
 * 1. 控制缓存
 * 2. 重定向
 */

public class ResponseDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//控制缓存
		controlCache(response);
		//重定向
		redirect(response);
	}

	private void controlCache(HttpServletResponse response) throws IOException {
		//设置缓存1分钟
		response.setDateHeader("expires", System.currentTimeMillis()+1000*60);
		//缓存页面内容就是AAA
		String a = "AAA";
		response.getOutputStream().write(a.getBytes());
	}
	//请求重定向的两种方式
	private void redirect(HttpServletResponse response) throws IOException {
		
		//方法一,设置相应状态码为302表示重定向,提供重定向地址。这样服务器接收到后会重定向到指定页面
//		response.setStatus(302);
//		response.setHeader("location", "/javaWeb/index.jsp");
		//方法二,使用response直接设置重定向
		response.sendRedirect("/javaWeb/index.jsp");
		
	}

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

}

控制缓存:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>缓存设置</title>
  </head>
  
  <body>
    <a href="http://localhost:8080/javaWeb/servlet/ResponseDemo4">缓存1分钟</a>
  </body>
</html>

最后要记得在web.xml中配置好,其实配置与之前的都相同,这里去一个作为示例



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值