[Servlet编程]Request,Response使用与码表原理

16 篇文章 0 订阅

在servlet中用OutputStream输出中文的问题:

1.使用OutputStream对象输出中文,需要先用String对象的getBytes方法通过查码表(默认gb2312)把中文字符串转换成相应字节发给浏览器,浏览器是个文本解析工具,按照其设置的默认码表(gb2312)把字节解码成中文.如果二者码表不一致,就会造成乱码。

2.浏览器访问Servlet程序,服务器调用其service方法。在Servlet中可以通过建立的response对象设置响应头来控制浏览器以什么码表解码字节流,有两种方式:response.setHeader方法和通过输出meta标签。

3.写数字1的小问题:浏览器是文本解析工具,会用1取查其默认码表,显示乱码。如果要输出1要写成字符串"1",用指定码表输出(OutputStream的write方法默认gb2312),并设置响应头通知浏览器以同一码表显示。

图解:


示例:

一切数据都是先写给response,response打给浏览器
采用字节流方式,是解码成原始字节,浏览器那边默认以gb2312打开
如果按UTF-8解码发送,则要发送一个头控制浏览器也以UTF-8打开

private void test1(HttpServletResponse response) throws IOException,
			UnsupportedEncodingException {
		//向浏览器发送响应头(Http协议)
		//程序以什么码表输出,就一定要控制浏览器以什么码表打开
		response.setHeader("Content-type", "text/html;charset=UTF-8");//这里第二个参数中间写成,就变成下载
		
		String ss="中国";
		
		OutputStream out=response.getOutputStream();
		
		out.write(ss.getBytes("UTF-8"));//以UTF-8编码输出,浏览器那边默认gb2312,乱码
	}

private void test2(HttpServletResponse response) throws IOException,
			UnsupportedEncodingException {
		//Meta模拟响应头发给浏览器,浏览器可以解析html,把它当作响应头,从而控制浏览器的码表
		String ss="中国强";
		OutputStream out=response.getOutputStream();
		
		out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());
		out.write(ss.getBytes("UTF-8"));
	}

private void test3(HttpServletResponse response) throws IOException {
		//写1---->直接写,因为浏览器是文本解析工具,会去查码表,显示乱码,所以要变成字符写
		OutputStream out=response.getOutputStream();
		out.write((1+"").getBytes());
	}

用Writer输出中文:

图解:


在Servlet中可以用Writer对象直接输出中文,Writer流先把字符写给response对象,response对象默认按ISO-8859-1码表编码,浏览器打开导致乱码。解决办法是设置response对象编码字符的码表。并且仍然需要设置响应头通知浏览器那边用什么码表打开。

示例:

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置response码表
		response.setCharacterEncoding("UTF-8");
		//response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setContentType("text/html;charset=UTF-8");//这一句涵盖了上面两句,但还是建议写第一句和这一句,清晰一些
		
		
		String ss="中国中国";
		//writer流一定只写字符串!!!
		PrintWriter out=response.getWriter();//默认iso-8859
		out.write(ss);//字符流
	}

(注:还是要强调,一定不能用字符流去写一部电影这样的二进制数据!)


中文文件下载案例:

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//分析:用户发出Servlet请求,服务端程序获取Web应用中的资源(web编程,相对于服务器程序,而不是java编程,相对于虚拟机):两种方式--->Servlet内访问用ServletContext,普通java程序(Web应用中的,也是相对于服务器的不是相对于虚拟机的)中通过类装载器
		//ServletContext获取资源有两种方式:获取资源流方式和获取资源绝对地址方式----->这里要获得地址,因为要通过地址获取文件名,显示给用户供下载
		//获取文件绝对地址,/代表Web应用,服务器调用
		String path=this.getServletContext().getRealPath("/download/代码女神.jpg");
		String filename=path.substring(path.lastIndexOf("\\")+1);
		
		//设置头信息
		//中文文件名需要经过url编码--->那边浏览器会以同样码表解码
		response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
		//传统方式读写
		InputStream in=null;
		OutputStream out=null;
		try{
			in=new FileInputStream(path);
			out=response.getOutputStream();
			byte buffer[]=new byte[1024];
			int length=0;
			while((length=in.read(buffer))>0){
				out.write(buffer,0,length);
			}
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		finally{
			if(in!=null){
				try{
					in.close();
				}catch(Exception e){
					throw new RuntimeException(e);
				}
			}
			if(out!=null){
				try{
					out.close();
				}catch(Exception e){
					throw new RuntimeException(e);
				}
			}
		}
	}

登录表单验证相关:生成随机认证图片,JavaScript,防缓存,session验证,跳转技术(逐步更新)

表单与JavaScript:

<script type="text/javascript">
    	function changeImage(image){
    		image.src=image.src+"?"+new Date().getTime();
    		}
    </script>

<form action="">
    	用户名:<input type="text" name="username"><br/>
    	密码:<input type="password" name="password"><br>
    	认证码:<input type="text" name="checkcode"><img src="/practice6/servlet/MyServlet2" οnclick="changeImage(this)" alt="换一张" style="cursor:hand"><br>
    	<input type="submit" value="注册">
    </form>

Servlet端生成和输出随机认证图片:

public class MyServlet2 extends HttpServlet {
	
	public static final int WIDTH=120;
	public static final int HEIGHT=25;//常量
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//生成随机验证码图片输出
		
		//在内存中构建图片
		BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
		Graphics g=image.getGraphics();
		
		//设置背景色
		setBackGround(g);
		//设置边框
		setBorder(g);
		//画干扰线
		drawRandomLine(g);
		//写随机数
		drawRandomNum((Graphics2D)g);//兼容考虑,返回的本来就是Graphics2D
		//图形写给浏览器
		response.setContentType("image/jpeg");//设置浏览器以图形方式打开
		//发头设置浏览器不要缓存--->地址栏敲回车,默认会拿缓存给你,而刷新则是重发请求
		response.setDateHeader("expires", -1);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		
		ImageIO.write(image,"jpg",response.getOutputStream());
	}

	private void setBackGround(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, WIDTH, HEIGHT);
	}

	private void setBorder(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(Color.BLUE);
		g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
	}

	private void drawRandomLine(Graphics g) {
		// TODO Auto-generated method stub
		g.setColor(Color.GREEN);
		for(int i=0;i<5;i++){
			//图形内随机位置
			int x1=new Random().nextInt(WIDTH);
			int y1=new Random().nextInt(HEIGHT);
			
			int x2=new Random().nextInt(WIDTH);
			int y2=new Random().nextInt(HEIGHT);
			g.drawLine(x1, y1, x2, y2);
		}
	}

	private void drawRandomNum(Graphics2D g) {
		// TODO Auto-generated method stub
		g.setColor(Color.RED);
		g.setFont(new Font("宋体",Font.BOLD,20));
		
		//utf-8表示的常见汉字
		String base="\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";
		int x=5;
		for(int i=0;i<4;i++){
			//-30-30的随机数
			int degree=new Random().nextInt()%30;
			//常用字中随机
			String ch=base.charAt(new Random().nextInt(base.length()))+"";
			//设置旋转角
			g.rotate(degree*Math.PI/180,x,20);
			g.drawString(ch,x,20);//写字
			//转回来
			g.rotate(-degree*Math.PI/180,x,20);
			//下一个位置
			x+=30;
		}
	}

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

		doGet(request, response);
	}

}

访问表单,图片位置点击切换随机认证图片。


Servlet向jsp页面forward的情形下完成跳转(refresh重定向,用于登录):利用meta标签--->jsp构建响应给浏览器,所以在Servlet页面设置头刷新无效!

代码:

//实用的自动跳转技术
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//这里写入ServletContext和显示到jsp如何改编码?显示乱码。这里不能用响应头设置了,因为是跳到jsp页面,不是直接访问直接响应!--->应该也可以用meta设置!
		//转到jsp页面后如何跳转到首页:利用meta头模拟响应头,让浏览器识别jsp的meta完成跳转
		String message="<meta http-equiv='refresh' content='3;url=/workday12/index.jsp'>恭喜你登录成功,本浏览器将在3秒钟跳到首页,如果没有跳转请点击<a href=''>超链接</a>";
		this.getServletContext().setAttribute("message", message);//ServletContext中的数据为整个应用共享
		//跳转到jsp消息显示页面(不是首页)
		this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
	}

设置缓存(!!注意:这里是设-置-要-缓-存,不是设置不要缓存!!),重定向与跳转的区别和应用及一次请求中不可同时调用getOutputStream和getWriter等细节问题

代码:

//getOutputStream和getWriter不能在一次请求中同时调用,否则抛出异常!!!尤其注意在转发过程中在不同的页面上调用,忘记这一茬!!!
	//如果有需求,一切都可以转换成字节流写的!!!
	//如果是重定向则没事,因为是两次请求,两次request/response
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//实现请求重定向
		//特点:1.浏览器会向服务器发两次请求,两个request/response
		//2.浏览器地址栏会发生变化
		//用户登录和显示购物车时通常会用到重定向(不然购物车刷一次购买一次,因为跳转和购买是一个请求,而用户登录需要在地址栏变化以通知用户登录策划你成功,通常跳转到首页地址)
		//response.setStatus(302);
		//response.setHeader("location","/workday12/index.jsp");
		response.sendRedirect("/workday12/message.jsp");
	}
	
	//设置缓存:注意一定是当前时间加上缓存的时间长!!不然从1970年开始算!!!
	private void test(HttpServletResponse response) throws IOException {
		response.setDateHeader("expires", System.currentTimeMillis()+1000*3600);
		
		String data="aaaaaaaaaaa";
		response.getWriter().write(data);
	}


注:链接的写法(浏览器访问,而不是服务器)

Servlet中发往jsp页面的字符串中写本应用下某个资源的链接:

String message="<meta http-equiv='refresh' content='3;url=/practice_servlet/index.jsp'>恭喜您登录成功,3秒跳转...没跳转就点击<a href='"+this.getServletContext().getContextPath()+"/index.jsp'>这里</a>";
		
		this.getServletContext().setAttribute("message", message);
		//这里都用ServletContext就会出问题,所有用户并发访问这同一个对象(代表这同一个应用嘛)--->此后用Request!!
		this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);

 

jsp中直接写链接---->/后带着应用名就行了,不用http开头:

<a href="/practice_servlet/servlet/ResponseDemo">查看图书</a>

缓存补充:从链接点进去,总是新的请求,要在链接到的页面设置缓存,缓存一些图片,css,js等一般不变的数据,减轻服务器压力!!

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>

  </head>
  
  <body>
    This is my JSP page. <br>
    <a href="/practice_servlet/servlet/ResponseDemo">查看图书</a>
  </body>
</html>

被请求页面的设置:

//设置缓存:注意一定是当前时间加上缓存的时间长!!不然从1970年开始算!!!
		response.setDateHeader("expires",System.currentTimeMillis()+1000*3600);
		
		String data="lsjffdls";
		response.getWriter().write(data);


登录认证:


grereg



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值