new String(temp_p.getBytes("ISO8859_1"), "GBK");
temp =
sqlStrchop(temp);
return temp;
} catch (Exception e) {
return null;
}
}
5、Solaris下Servlet编程的中文
问题及解决办法
在使用Java开发Internet上的一个应用
系统时,发现在Windows下调试完全正常的Servlet,上传到Solaris 服务器上,运行却出现故障--返回的网页不能显示中文,应为中文的信息全为乱码;用中文信息做关键字,不能正确检索数据库。后来采用加入检查代码等方法探知故障原因如下:
显示乱码主要是因为通过类 HttpServletResponse提供的方法setContentType 无法改变返回给客户的数据的编码方式,正确的编码方式应为GB2312或者GBK,而事实上为缺省的ISO8859-1。无法检索中文信息则是因为,客户提交的中文信息经浏览器编码到达服务器后,Servlet无法将其正确解码。
举例说明显示乱码解决方法
Servlet 一般通常做法如下:
public class ZldTestServlet extends HttpServlet {
public void doGet (HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
//在使用 Writer向浏览器返回数据前,设置 content-type header ,在这里设置相应的字符集gb2312
response.setContentType("text/html; charset=gb2312");
PrintWriter out = response.getWriter(); //*
// 正式返回数据
out.println("〈html〉〈head〉〈title〉Servlet test〈/title〉〈/head〉" );
out.println("这是一个测试页!");
out.println("〈/body〉〈/html〉");
out.close();
}
...
}
解决页面显示乱码问题,需将*处代码换成如下内容:
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStrea
m(),"gb2312"));
Solaris中文信息检索问题的解决
浏览器利用表单向服务器提交信息时,一般采用x-www-form-urlencoded 的MIME格式对数据进行编码。如果使用get方法,参数名称和参数值经编码后附加在URL后,在
Java中称作
查询串(query string)。
在Servlet
程序中,如果采用ServletRequest的方法getParameter取得参数值,在Solaris环境下,对汉字却不能正确解码。因而无法正确检索数据库。
在Java 1.2的包--java.net中提供了URLEncode和URLDecode类。类URLEncode提供了按x-www-form-url
encoded格式对给定串进行转换的方法。类URLEncode则提供了逆方法。
6、Common Mail乱码问题
common mail是一个小而方便的mail包,他实现了对Java Mail的封装,使用起来十分的方便,但是我在使用他的时候发现,使用纯文本的内容发送,结果是乱码,代码如下:
public class TestCommonMail {
public static void main(String[] args) throws EmailException, MessagingException {
SimpleEmail email = new SimpleEmail();
email.setCharset("GB2312");
email.setHostName("smtp.163");
email.setSubject("test");
email.addTo("test@163");
email.setFrom("test@163");
email.setMsg("我的测试");
email.setAuthentication("test", "test");
email.send();
}
}
分析了一下commons mail的源码找到了原因。源码如下:
public class SimpleEmail extends Email
{
public Email setMsg(String msg) throws EmailException, MessagingException
{
if (EmailUtils.isEmpty(msg))
{
throw new EmailException("Invalid message supplied");
}
setContent(msg, TEXT_PLAIN);
return this;
}
}
Email代码片段
public void setContent(Object aObject, String aContentType)
{
this.content = aObject;
if (EmailUtils.isEmpty(aContentType))
{
this.contentType = null;
}
else
{
// set the content type
this.contentType = aContentType;
// set the charset if the input was properly formed
String strMarker = "; charset=