可用两种方式避免request对象获取的信息出现乱码:
1.对信息自身重新进行编码
将获取的信息用ISO-8859-1进行编码,再将编码存放到一个字节数组中,然后再将此字节数组转化为字符串。如:
String str=request.getParameter("message"); byte b[]=str.getBytes("ISO-8859-1"); str=new String(b);
例:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 4 <%! public String handleStr(String s) { 5 try { byte [] bb= s.getBytes("iso-8859-1"); 6 s = new String(bb); 7 } 8 catch(Exception exp){} 9 return s; 10 } 11 %> 12 13 <% String pic = request.getParameter("inout"); 14 if(pic == null) 15 pic = ""; 16 pic = handleStr(pic)+".jpg"; 17 18 %> 19 20 <!DOCTYPE html> 21 <html> 22 <head> 23 <meta charset="UTF-8"> 24 <title>Insert title here</title> 25 </head> 26 <center> 27 <body background="/upload/<%= pic %>"> 28 <FONT size=4> 29 <form action="" method=post name=form> 30 <input type="text" name="inout"> 31 <input type="submit" value="确定" name="submit"> 32 </form> 33 34 </FONT> 35 36 </body> 37 </center> 38 </html>
2.request设置编码
request在获取信息之前使用setCharacterEncoding方法设置自己的编码为gb2312:
request.setCharacterEncoding("gb2312");
例:
1 <%@ page contentType="text/html;charset=gb2312" %> 2 <HTML> 3 <body bgcolor=cyan><font size=3> 4 <form action="" method=post name=form> 5 <input type="text" name="information_fees" size=50> 6 <input type="submit" value="确定" name="submit"> 7 </form> 8 <% request.setCharacterEncoding("gb2312"); 9 String information_fees=request.getParameter("information_fees"); 10 double number=0; 11 if(information_fees==null) { 12 information_fees=""; 13 } 14 %> <b> 账单内容:<br><%= information_fees %><br> 15 <% String []a = information_fees.split("[^0123456789.]"); 16 double sum=0; 17 for(String s:a) { 18 try { 19 sum+=Double.parseDouble(s); 20 } 21 catch(NumberFormatException exp){} 22 } 23 %> <b> 账单总消费额:<%= sum %> 24 </font></body></HTML>