jsp传递中文参数、空格以及表单内容换行问题解决小结

来源:互联网 发布:淘宝扣48分怎么办 编辑:程序博客网 时间:2024/05/11 02:07

jsp传递中文参数、空格以及表单内容换行问题解决小结
作者:fbysss
Blog地址:blog.csdn.net/fbysss
MSN:jameslastchina@hotmail.com
声明:本文为fbysss原创,如需引用,请注明作者及引用地址
关键字:jsp,中文参数,换行,回车,空格
========================================================================
一、地址传递参数中文/空格问题
举例说明:
    String sContent = "中文 参数";
    如果不做任何处理就直接传递,中文也许没有问题(但不保证),但空格肯定会有问题,到接收页面无法识别。
解决办法1:java.net.URLEncoder.encode(sContent,"gb2312"); 然后再传递。比如url是"accept.jsp?content="+sContent;
读取时,使用
String sc = request.getParameter("content");
sc = new String(sc.getBytes("iso-8859-1"),"gb2312");

 

 

解决办法2:

 

 

传递前,先做以下替换

 

 

sContent=sContent.replaceAll("  ","%20");

 

 

接收到字符串之后,如果在td中显示,则需要使用

 

 

sContent=sContent.replaceAll("  "," ");//注意这里不是替换%20,而是替换空格。如果有中文,要先转码

 

 

如果在textarea中显示,则不需要处理。

 

 

 这样就没问题了。
二、回车换行问题
问题描述:
    表单中的textArea中有换行的内容,提交之后保存到数据库,再读取出来的时候,没有换行,全部连在一起了。
解决:
1. 在写入数据库的时候,加入
      sContent=sContent.replaceAll(" "," ");
    sContent=sContent.replaceAll("/r/n","<br/>");
      sContent=sContent.replaceAll("/n","<br/>");
2.在读取的时候,如果要在textArea中显示,需要加入
    sc = 数据库中的content字段值 ;
    sc=sc.replaceAll("<br/>","/r/n");
    sc=sc.replaceAll("<br>","/r/n");
    sc=sc.replaceAll("&nbsp;"," ");
如果是直接在td中显示,则不需要转换 。

 

 

另还有一种方法解决jsp页面上空格和换行的方法,一并放入此贴了。


/**
  *   Function   Detail   :   对输入的字符处理
  *   @param   pstrWord
  *   @return
  *   @throws   java.io.UnsupportedEncodingException
  */
public   static   String   replaceIn(String   pstrWord)   throws   Exception
{
//pstrWord   =   replace(pstrWord);
pstrWord   =   htmlEncode(pstrWord);  
pstrWord   =   pstrWord.replaceAll( "/n ", " <br> ");
pstrWord   =   pstrWord.replaceAll( "   ", "&nbsp ");
pstrWord   =   pstrWord.replaceAll( "   ", "&nbsp; ");
return   pstrWord;
}
/**
  *   Function   Detail   :   对输出的字符处理
  *   @param   pstrWord
  *   @return
  *   @throws   java.io.UnsupportedEncodingException
  */
public   static   String   replaceOut(String   pstrWord)   throws   Exception  
{
pstrWord   =   pstrWord.replaceAll( " <br> ", "/n ");
pstrWord   =   pstrWord.replaceAll( "&nbsp ", "   ");
pstrWord   =   pstrWord.replaceAll( "&nbsp; ", "   ");    
pstrWord   =   toChinese(pstrWord);  
return   pstrWord;
}