您的位置:首页 > 其它

Tocmat的中文问题解决方法总结:mxz

2007-07-03 12:11 423 查看
以下内容转自

http://blog.csdn.net/mxz391/archive/2007/06/27/1668818.aspx

http://blog.csdn.net/diaokegang/archive/2005/04/25/362653.aspx等文章

及自己的总结

问题描述:

1 表单提交的数据,用request.getParameter(“xxx”)返回的字符串为乱码或者??
2 直接通过url如http://localhost/a.jsp?name=中国,这样的get请求在服务端用request. getParameter(“name”)时返回的是乱码;按tomcat4的做法设置Filter也没有用或者用 request.setCharacterEncoding("GBK");也不管用

原因:
1 tomcat的j2ee实现对表单提交即post方式提示时处理参数采用缺省的iso-8859-1来处理
2 tomcat对get方式提交的请求对query-string 处理时采用了和post方法不一样的处理方式。(与tomcat4不一样,所以设置setCharacterEncoding(“gbk”))不起作用。

解决方法:

一。首先所有的jsp文件都加上: 所有JSP改为<%@ page language="java" pageEncoding="GBK" %>

1 实现一个Filter.设置处理字符集为GBK。(在tomcat的webapps/servlet-examples目录有一个完整的例子。请参考web.xml和SetCharacterEncodingFilter的配置。)

1) 只要把%TOMCAT安装目录%/ webapps/servlets-examples/WEB-INF/classes/filters/SetCharacterEncodingFilter.class 文件拷到你的webapp目录/filters下,如果没有filters目录,就创建一个。

2)在你的web.xml里加入如下几行:

<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3)完成.




import javax.servlet.Filter;


import javax.servlet.FilterChain;


import javax.servlet.FilterConfig;


import javax.servlet.ServletException;


import javax.servlet.ServletRequest;


import javax.servlet.ServletResponse;


import java.io.IOException;






public class SetCharacterEncodingFilter implements Filter ...{


protected String encoding = null;




protected FilterConfig filterConfig = null;




protected boolean ignore = true;






public void init(FilterConfig filterConfig) throws ServletException ...{


this.filterConfig = filterConfig;


this.encoding = filterConfig.getInitParameter("encoding");


String value = filterConfig.getInitParameter("ignore");


if (value == null)


this.ignore = true;


else if (value.equalsIgnoreCase("true"))


this.ignore = true;


else


this.ignore = false;


}




public void doFilter(ServletRequest request, ServletResponse response,




FilterChain chain) throws IOException, ServletException ...{


// TODO 自动生成方法存根




if (ignore || (request.getCharacterEncoding() == null)) ...{


String encoding = selectEncoding(request);


if (encoding != null)


request.setCharacterEncoding(encoding);


}


chain.doFilter(request, response);


}






public void destroy() ...{


// TODO 自动生成方法存根


this.encoding = null;


this.filterConfig = null;


}






protected String selectEncoding(ServletRequest request) ...{


return (this.encoding);


}


}



二、写一个过滤器类,在web.xml中配置(但是这是针对post提交的)。(过滤器类代码如上:)

<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

三、get方式的参数。针对URL的方法就是--修改tomcat的server.xml文件中URIEncoding。这个方法会改变服务器

1) 打开tomcat的server.xml文件,找到区块,加入如下一行:
URIEncoding=”GBK”
完整的应如下:

<Connector
port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true"
URIEncoding="GBK"
/>

2)重启tomcat,一切OK。

四、JSP页编码为UTF-8,web.xml和servel.xml均未做改动

(一)、对于参数为中文的,且不用分析的,如下例:

1.JSP页

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<a href="<%=request.getContextPath() %>/BbsCtrl?page=ShowPersonalPage&username=<%=java.net.URLEncoder.encode(viewUserInfo.getUserName())%>">管理</a>

2.处理的JAVA类




public class ShowPersonalPage extends HtmlPage ...{




public String print() throws Exception ...{


String n=req_.getParameter("username"); //取参数


String userName=null;




if(n!=null&&!n.equals(""))...{


userName = new String(req_.getParameter("userName").getBytes("ISO8859-1"));


}


}



(二)、对于参数为中文的,且用分析的,如下例:

JSP页:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<a href="<%=request.getContextPath() %>/u/<%=viewUserInfo.getUserName() %>">家庭主页</a>

处理的JAVA文件


package util;


import javax.servlet.http.HttpServlet;


import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;


import javax.servlet.ServletException;


import java.io.IOException;


import java.sql.Connection;


import java.sql.SQLException;


import util.HtmlPage;


import util.Mail;


import util.PubFun;




public class Test extends HttpServlet ...{




private static final long serialVersionUID = 8135385272669981701L;






public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ...{


String jspStr = "webapp/sign_in.jsp";


HtmlPage page = null;




resp.setContentType("text/html; charset=UTF-8");


//获取uri


String requestUri = "";


requestUri = java.net.URLDecoder.decode(new String(req.getRequestURI().getBytes("ISO8859_1")),"utf-8");


int isPos = requestUri.indexOf("/u/");




if (isPos == -1) ...{


resp.sendRedirect("http://www.xxx.com");


return;




} else ...{


//截取userName


int beginPos = isPos + 3;


String userName = requestUri.substring(beginPos);


int endPos = userName.indexOf("/");




if (endPos > 0) ...{


userName = userName.substring(0, endPos);


}




if (userName.equals("")) ...{


resp.sendRedirect("http://www.xxx.com");


return;




} else ...{


req.setAttribute("userName",userName);


System.out.println(userName);


page = (HtmlPage) new page.user.ShowPersonHomePage();


}


}






if (page == null) ...{


resp.sendRedirect(jspStr);


return;


}


Connection conn = null;




try ...{


conn = PubFun.getConn(true);


page.prepare(conn, req, resp);


jspStr = page.print();




} catch (Exception e) ...{


Mail.send("xxx@sohu.com", "xxx@sohu.com",req.getRequestURI()+"?"+ req


.getQueryString(), e.getMessage(), null, "xxx@sohu.com",


"xxx");


req.setAttribute("inf", e.toString());


jspStr = "/webapp/view_inf.jsp?for_user=1";




} finally ...{




if (conn != null) ...{




try ...{


conn.close();




} catch (SQLException e2) ...{


System.out.println("HomeMapCtrl conn.close() falied");


}


}


}




if(jspStr!=null)...{


req.getRequestDispatcher(jspStr).forward(req, resp);


}


}






public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ...{


doGet(req, resp);


}






}




public class ShowPersonHomePage extends HtmlPage ...{






public String print() throws Exception ...{




//这个类根据逻辑需具体处理工作




}



---------------------------------------------------------------------------------------------------------------------------------------------------

五、同时介绍另一个将长访问地址转为短访问地址的示例:(与上例/u/的访问形式相仿,与本文中文编码解决方式没有关联)

JSP页

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<a href="<%=request.getContextPath()%>/msg/<%=thr.getThreadId()%>" class="zifont"><%=topic.getHeading() %></a>
http://www.xxx.com/msg/2212这种访问方式

JAVA文件处理




/** *//**


* 迈兴志 2006-12-4 解析URL地址 BBS-->Msg


*/


import java.io.IOException;




import util.Mail;


import javax.servlet.ServletException;


import javax.servlet.http.HttpServlet;


import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;






public class MsgCtrl extends HttpServlet ...{




private static final long serialVersionUID = 0;




public void doGet(HttpServletRequest req, HttpServletResponse resp)




throws ServletException, IOException ...{


String jspStr = "webapp/sign_in.jsp";




resp.setContentType("text/html; charset=UTF-8");


String requestUri = req.getRequestURI();


String id = requestUri.substring(requestUri.indexOf("/msg/") + 5,


requestUri.length());


String info="您查看的页不存在,请确定";


long tid2 = -1;






try ...{


tid2=this.getLongParameter(id,-1);




if(tid2==-1)...{


req.setAttribute("inf", info);


req.getRequestDispatcher("/webapp/view_inf.jsp").forward(req,resp);


return ;


}




} catch (Exception e) ...{


e.printStackTrace();


return ;


}


jspStr = "/BbsCtrl?page=ShowMessagePage&fid=0&tid=" + tid2;


// jspStr = "/webapp/bbs/bbs_thread.jsp?tid="+tid2+"&fid="+fid;








if (jspStr != null) ...{


req.getRequestDispatcher(jspStr).forward(req, resp);


}


}




public void doPost(HttpServletRequest req, HttpServletResponse resp)




throws ServletException, IOException ...{


doGet(req, resp);


}




protected long getLongParameter(String key, long i)




throws Exception ...{




if ((key == null) || (key.trim().length() == 0)) ...{


return i;


}




try ...{


return Long.parseLong(key.trim());




} catch (NumberFormatException exc) ...{


System.out.println("格式转换错误,不是真正的长整型"+"--------------------MsgCtrl类");


return -1;




}


}






}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: