第一部分:? jsp? ---> java/servlet
對(duì)于流行的Tomcat來(lái)說(shuō),有以下三種解決方法:
1) 更改 D:\Tomcat\conf\server.xml,指定瀏覽器的編碼格式為“簡(jiǎn)體中文”:
方法是找到 server.xml 中的
??? <Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
??? enableLookups="false" redirectPort="8443" acceptCount="100"
??? connectionTimeout="20000" disableUploadTimeout="true" URIEncoding='GBK' />
標(biāo)記,粗體字是我添加的。
可以這樣驗(yàn)證你的更改是否成功:在更改前,在你出現(xiàn)亂碼的頁(yè)面的IE瀏覽器,點(diǎn)擊菜單“查看|編碼”,會(huì)發(fā)現(xiàn)“西歐(ISO)”處于選中狀態(tài)。而更改后,點(diǎn)擊菜單“查看|編碼”,會(huì)發(fā)現(xiàn)“簡(jiǎn)體中文(GB2312)”處于選中狀態(tài)。注意你的Tomcat的common下要有"endorsed"和"i18n"文件夾,其中包含編碼所需的lib
???
2)更該 Java 程序,
?public class ThreeParams extends HttpServlet {
? public void doGet(HttpServletRequest request, HttpServletResponse response)
?? throws ServletException, IOException {
????? response.setContentType("text/html; charset=GBK");
????? ...
? }?
}
粗體字是必需要有的,它的作用是讓瀏覽器把Unicode字符轉(zhuǎn)換為GBK字符。這樣頁(yè)面的內(nèi)容和瀏覽器的顯示模式都設(shè)成了GBK,就不會(huì)亂碼了。
??
第二部分??? java/servlet?? ---->?? mysql
mysql和Hibernate中的中文問(wèn)題解決方法
另一種解決方法(mysql-4.1.11).低版本的mysql似乎沒(méi)出現(xiàn)過(guò)中文問(wèn)題(mysql-4.0.17). :)
1.添加一個(gè)過(guò)濾器,將字符集編碼設(shè)為GBK.
修改web.xml:
?<filter>
??<filter-name>SetCharacterEncoding</filter-name>
??<filter-class>hxz.filter.SetEncodingFilter</filter-class>
??<init-param>
???<param-name>encoding</param-name>
???<param-value>GBK</param-value>
??</init-param>
?</filter>
?
?<filter-mapping>
??<filter-name>SetCharacterEncoding</filter-name>
??<url-pattern>/*</url-pattern>
?</filter-mapping>
新建一個(gè)過(guò)濾器:
package hxz.filter;
import java.io.IOException;
import javax.servlet.*;
public class SetEncodingFilter implements Filter {
?
?// default character encoding
?String defaultEncoding = "GBK";?
?
?public void init(FilterConfig config) throws ServletException {
??String encoding = config.getInitParameter("encoding");
??if (encoding != null) {
???defaultEncoding = encoding;
??}
?}
?public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
??request.setCharacterEncoding(defaultEncoding);
??chain.doFilter(request, response);
?}
?public void destroy() {
??defaultEncoding = null;
?}
}
2.修改hibernate配置文件:
<property name="url">
? <value>jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK</value>
</property>
注意后面的:useUnicode=true&characterEncoding=GBK, 在xml中&要改為;amp;
3.在新版本中mysql建表時(shí),你可以選擇一種字符集,將它設(shè)為GBK.
jsp或servlet中把字符集改為GBK.
?