1.response响应生成非字符响应:
1 <%@ page language="java" contentType="image/png" 2 pageEncoding="utf-8"%> 3 <%@ page import="java.awt.image.*,javax.imageio.*,java.io.*,java.awt.*"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 8 <title>通过contentType属性指定响应数据是图片</title> 9 </head> 10 <body> 11 <% 12 //创建BufferImage对象 13 BufferedImage image = new BufferedImage(340, 160, BufferedImage.TYPE_INT_RGB); 14 //以Image对象获取Graphics对象 15 Graphics g = image.getGraphics(); 16 //使用Graphics画图,所画的图像将会出现在image对象中 17 g.fillRect(0, 0, 400, 400); 18 //设置颜色:红 19 g.setColor(new Color(255, 0, 0)); 20 //画出一段弧 21 g.fillArc(20, 20, 100, 100, 30, 120); 22 //设置颜色:绿 23 g.setColor(new Color(0, 255, 0)); 24 //画出一段弧 25 g.fillArc(20, 20, 100, 100, 150, 120); 26 //设置颜色:蓝 27 g.setColor(new Color(0, 0, 255)); 28 //画出一段弧 29 g.fillArc(20, 20, 100, 100, 270, 120); 30 //设置颜色:黑 31 g.setColor(new Color(0, 0, 0)); 32 g.setFont(new Font("Arial Black", Font.PLAIN, 16)); 33 //画出三个字符 34 g.drawString("red:climb", 200, 60); 35 g.drawString("green:swim", 200, 100); 36 g.drawString("blue:jump", 200, 140); 37 g.dispose(); 38 //将图像输出到页面的响应 39 ImageIO.write(image, "png", response.getOutputStream()); 40 41 %> 42 </body> 43 </html>
然后就可以生成一个这样的PNG图片:
2.response重定向:
实现:
<% response.sendRedirect("new.jsp"); %>
与forward不同的是:
forward仍然是一次请求,地址栏URL不会改变,并且request作用域属性均存在
response实际上是第二次请求,其request作用域属性均已全部失去。
3.实现cookie:
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>Cookie</title> 8 </head> 9 <body> 10 <!-- 如果cookie中含有中文,同样需要URLDecoder俩解决 --> 11 <% 12 //以后编码后的字符串为值,创建一个Cookie对象 13 Cookie c = new Cookie("cnName" 14 , java.net.URLEncoder.encode("啦啦啦~", "gbk")); 15 //设置Cookie对象的生存期限 16 c.setMaxAge(60); //以秒单位计算 17 //项客户端增加Cookie对象 18 response.addCookie(c); 19 20 //获取本站在客户端上保留的所有Cookie 21 Cookie[] cookies = request.getCookies(); 22 //遍历客户端上的每个Cookie 23 for (Cookie cookie : cookies) { 24 //如果Cookie的名为username,表明该Cookie是需要访问的Cookie 25 if(cookie.getName().equals("cnName")) { 26 //使用java.util.URLDecoder对Cookie值进行解码 27 out.println(java.net.URLDecoder 28 .decode(cookie.getValue())); 29 } 30 } 31 %> 32 </body> 33 </html>
浙公网安备 33010602011771号