`

JSP中文参数传至JavaBean出现乱码

阅读更多

JSP中文参数传至JavaBean出现乱码

[关键字]:Tomcat,GBK,GB2312,Filter,乱码,JSP,charset,Servlet


[摘要]:书上说的都能看懂,但是真正做起来却会遇到问题。解决这些问题的过程,就是上机练习的意义。以前遇到的乱码问题要么通过request.setCharacterEnconding("GB2312")解决了,要么就是new String(str.getBytes("ISO-8859-1") , "GB2312")。但是这回是JavaBean出问题了。上面的两句行不通了,只能通过设置Filter来解决。希望遇到类似问题的朋友,站在我们的肩膀上,能看的更远。

[正文]:

写了一个简单的JavaBean,用于计算加减乘除。
CalculateBean.java:

package ch6.calcbean;
import java.io.*;

public class CalculateBean{
private int operandFirst;//操作数1
private char operator;//运算符
private int operandSecond;//操作数2
private double result;//运算结果

public int getOperandFirst(){
return this.operandFirst;
}
public void setOperandFirst(int op){
this.operandFirst = op;
}

public char getOperator(){
return operator;
}
public void setOperator(char operator){
this.operator = operator;
}

public int getOperandSecond(){
return this.operandSecond;
}
public void setOperandSecond(int op){
this.operandSecond = op;
}

public double getResult(){
return this.result;
}
public void setResult(double result){
this.result = result;
}

public void calculate(){
double temp;
switch(operator){
case '+':
temp = getOperandFirst() + getOperandSecond();
break;
case '-':
temp = getOperandFirst() - getOperandSecond();
break;
case '×':
temp = getOperandFirst() * getOperandSecond();
break;
case '÷':
temp = 1.0 * getOperandFirst() / getOperandSecond();
break;
default:
temp = 0;
}

setResult(temp);
}
}


由Calculate.jsp调用CalculateBean完成计算:
Calculate.jsp:

<%@page contentType="text/html;charset=GB2312" pageEncoding="GB2312"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
</head>
</body>
<form method="post" action="Calculate.jsp">
<input type="hidden" name="action" value="TRUE"/><!-- 表示是否提交 -->
第一个操作数:
<input type="text" name="operandFirst" />
运算符:
<select name = "operator" >
<option value="+">+
<option value="-">-
<option value="×">×
<option value="÷">÷
</select>
第二个操作数:
<input type="text" name="operandSecond" />
<input type="submit" value="提交"/>
</form>

<%if(request.getParameter("action")!=null){ %>

<jsp:useBean id="calcu" class="ch6.calcbean.CalculateBean" scope="request"/>
<jsp:setProperty name="calcu" property="*"/>
<% calcu.calculate(); %>
<jsp:getProperty name="calcu" property="operandFirst"/>
<jsp:getProperty name="calcu" property="operator"/>
<jsp:getProperty name="calcu" property="operandSecond"/>
=<jsp:getProperty name="calcu" property="result"/>

<%}%>

</body>
</html>



为了完成JavaBean的调用,需将编译生成的CalculateBean.class部署到WEB-INF/classes/ch6目录下。然后运行Calculate.jsp即可以看到结果。程序没有什么问题。但是运行结果总是不对,输出的运算结果result总是为0。怀疑<jsp:setProperty name="calcu" property="*"/> 有问题。也怀疑过<% calcu.calculate(); %> 是否执行到、、、总之,怎么调试也不正确。后来,再仔细看看书,找到了解决办法:"JavaBean部署完成之后,要重启Tomcat"。就这么简单!当然,我没有使用IDE,是手工编译部署的,如果使用IDE,也许就没这问题了。

一个问题解决了,另一个问题又来了。算加减时,没有问题。算乘除时,JavaBean并不能正确地接收"×"、"÷"。因为"×"、"÷"并不是标准的ASCII字符。在jsp/servlet中直接用request.setCharactorEncoding("gb2312")就可以了。但是这是在JavaBean中,而且用<jsp:setProperty name="calcu" property="*"/>也没办法设置Encoding。这回到网上搜,有人说应该加上<%@page contentType="text/html;charset=GB2312" pageEncoding="GB2312"%>,还有人说用new String(str.getBytes("ISO-8859-1") , "GB2312"),还有server.xml中加上URIEncoding="GB2312"(<Connector ...... port="8080" redirectPort="8443" URIEncoding="GB2312" >)。这些都没能解决问题。

最后,找到了答案。关于乱码,Skytiger讲述的比较清楚。步骤如下(我用的是JDK1.6/Tomcat6.0,所以对Skytiger的讲述稍作修改):
1、实现一个Filter,设置处理字符集为GB2312。(Tomcat下Tomcat\webapps\examples\WEB-INF\classes\filters有完整的例子,请参考web.xml和SetCharacterEncodingFilter的配置。)
a、只要把Tomcat\webapps\examples\WEB-INF\classes\filters \SetCharacterEncodingFilter.class文件拷到你的\WEB-INF\classes\filters下,如果没有filters目录,就创建一个。
b、在你的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>GB2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



2、打开tomcat的Tomcat/conf/server.xml文件,加入URIEncodeing="GB2312",完整的如下:
<Connector port="8080" protocol="HTTP/1.1"
maxThreads="150" connectionTimeout="20000"
redirectPort="8443" URIEncodeing="GB2312"/>

3、别忘了重启Tomcat。

这样改完,再运行就正确了。

致谢:
多谢Skytiger。但是关于Skytiger的内容,是在archaic的blog上找到的(archaic也遇到了类似的问题),在此一并致谢。

正文内容到此结束。
==============================
==============================
==============================
==============================
为了方便大家,再附上SetCharacterEncodingFilter.java 和 archaic原文。

==============================
SetCharacterEncodingFilter.java:
==============================

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package filters;


import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


/**
* <p>Example filter that sets the character encoding to be used in parsing the
* incoming request, either unconditionally or only if the client did not
* specify a character encoding. Configuration of this filter is based on
* the following initialization parameters:</p>
* <ul>
* <li><strong>encoding</strong> - The character encoding to be configured
* for this request, either conditionally or unconditionally based on
* the <code>ignore</code> initialization parameter. This parameter
* is required, so there is no default.</li>
* <li><strong>ignore</strong> - If set to "true", any character encoding
* specified by the client is ignored, and the value returned by the
* <code>selectEncoding()</code> method is set. If set to "false,
* <code>selectEncoding()</code> is called <strong>only</strong> if the
* client has not already specified an encoding. By default, this
* parameter is set to "true".</li>
* </ul>
*
* <p>Although this filter can be used unchanged, it is also easy to
* subclass it and make the <code>selectEncoding()</code> method more
* intelligent about what encoding to choose, based on characteristics of
* the incoming request (such as the values of the <code>Accept-Language</code>
* and <code>User-Agent</code> headers, or a value stashed in the current
* user's session.</p>
*
* @author Craig McClanahan
* @version $Revision: 500674 $ $Date: 2007-01-28 00:15:00 +0100 (dim., 28 janv. 2007) $
*/

public class SetCharacterEncodingFilter implements Filter {


// ----------------------------------------------------- Instance Variables


/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;


/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;


/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;


// --------------------------------------------------------- Public Methods


/**
* Take this filter out of service.
*/
public void destroy() {

this.encoding = null;
this.filterConfig = null;

}


/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {

// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}

// Pass control on to the next filter
chain.doFilter(request, response);

}


/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
*/
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 if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;

}


// ------------------------------------------------------ Protected Methods


/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
* <code>null</code>.
* <p>
* The default implementation unconditionally returns the value configured
* by the <strong>encoding</strong> initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
*/
protected String selectEncoding(ServletRequest request) {

return (this.encoding);

}
}




==============================
archaic原文如下:http://archaic.blog.hexun.com/5576058_d.html
==============================

JSP 页面传中文到javaBean中出现乱码 [原创 2006.09.12 14:51:31]
刚接触JSP..乱码让我头疼了好几天.看了好多贴子.,都没搞对..

在JSP页面中

<%@page contentType="text/html;charset=GBK" language="java"%>

在server.xml文件中加入URIEncoding="GBK"

<Connector ...... port="8080" redirectPort="8443" URIEncoding="GBK" >

在eclips中编辑好的jsp在publish后竟然不能更新到tomcat v5.0 server运行目录下..百思不得其解.我现在只好编辑完后再另存一次..

郁闷了...~!

关于乱码..Skytiger讲述的比较清楚

·jsp中文乱码问题 -|Skytiger 发表于 2006-3-17 15:56:00
 在tomcat5中发现了以前处理tomcat4的方法不能适用于处理直接通过url提交的请求,上网找资料终于发现了最完美的解决办法,不用每个地方都转换了,而且无论get,和post都正常。写了个文档,贴出来希望跟我有同样问题的人不再像我一样痛苦一次:-)

  问题描述:

  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文件都加上:

  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)完成.

  2 get方式的解决办法

  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与servlet 上传文件 javaBean上传文件

    jsp与servlet文件上传代码,可以上传中文文件名,不乱码 jsp与javaBean文件上传代码,但上传中文文件名乱码 刚写完的。

    jsp与javabean

    简单的jsp与Javabean例子,介绍了设置属性和得到属性的方法,以及如何解决乱码

    JSP+JavaBean留言本 一款JSP+JavaBean留言本程序源码,后台用户名是admin,密码是qipeng 如果不行,可以打开数据库修改md5的数值,可以到cmd5.com上去查找MD5的具体对应值。留言本推荐环境为Tomcat6.0,如果用5.0,可能会出现乱码,因为5.0对中文的支持还是有一定的问题。

    JSP+JavaBean留言本 一款JSP+JavaBean留言本程序源码,后台用户名是admin,密码是qipeng 如果不行,可以打开数据库...留言本推荐环境为Tomcat6.0,如果用5.0,可能会出现乱码,因为5.0对中文的支持还是有一定的问题。

    JSP动态输出Excel及中文乱码的解决

    最近在网上看到一个用java来操纵excel的open source,在weblogic上试用了一下,觉得很不错,... 写一个javaBean,利用JExcelApi来动态生成excel文档,我这里写一个最简单的,示意性的。复杂的你可能还要查询数据库什么的。

    jsp传参 servlet接收中文乱码问题的解决方法

    毕竟数据是根本嘛,首先我用的是hibernate+servlet,但是在jsp页面传参到servlet的时候中文一直乱码,我尝试了好多方法,最后还是解决了。 第一,首先看清项目的编码,jsp页面的编码 第二,修改tomcat 下面的server....

    JSP版简单的入门级留言本

    纯JSP版的简单入门留言本,不涉及自己编写的JAVA类....是JSP初学者的入门好程序,本人近期内还将推出model1(jsp+javabean)版以及mvc(jsp+javabean+servlet)版,多谢支持!本人QQ:503108946,欢迎探讨技术问题!

    简单的JSP+JAVABEAN+ACCESS留言簿

    定义了一些常用的方法,比如中文字体处理(解决乱码问题),数据库数据转换为HTML格式显示的方法等。 7. javascript脚本 用来检查表单数据是否为空。 //用于管理员登陆的验证 function check() {  var adminName=...

    JSP聊天+BBS论坛

    这个BBS和聊天室完全采用JSP开发,开发运行环境linux+tomcat,数据库oracle9i,JSP 通过JDBC与数据库相连。 一、功能 BBS和chatroom两者有机的结合在一起,用户可以在这两部分取得经验值,达到10000分 后升级为巫师,...

    网页教程《跟姐姐学JSP》

    2.2. 中文乱码 2.2.1. 先解决响应中的乱码 2.2.2. POST乱码 2.2.3. GET乱码 3. 请求的跳转与转发 3.1. 范例 3.2. 如果用forward 3.3. 如果用redirect 3.4. forward和redirect的问题 3.4.1. 绝对路径与相对...

    java+servlet+javabean实验报告(6)

    jsp的标准动作的用法,适合初学者,里头含有他人关于中文乱码的总结,实验报告加源代码

    JSP+JavaBean留言本

    JSP网络聊天,JSP网络聊天源码,JSP聊天源码,JSP聊天源码下载。一款JSP+JavaBean留言本程序源码,后台用户名是admin,...留言本推荐环境为Tomcat6.0,如果用5.0,可能会出现乱码,因为5.0对中文的支持还是有一定的问题。

    java+servlet+javabean实验报告(3)

    jsp的标准动作的用法,适合初学者,里头含有他人关于中文乱码的 总结,实验报告加源代码掌握如何操作session对象,会使用session相关的属性和方法,Map、Set对象的用法。;利用session实现购物车功能。

    港深热线BBS聊天室.rar_JSP 聊天_bbs_java 聊天室_jsp bbs_jsp 网站

    一共分三种用户:会员用户、社区用户、游客(我也不想搞的这么复杂,可是头儿硬要和整个网站连起来,:( 没办法)二、中文乱码问题 在OPDB javabean中写了两个方法,GBK和AsciiToChineseString进行转码,彻底的解决了...

    学生信息管理系统jsp+servlet

    用到的技术:jsp、javabean、servlet、mysql 用到的开发工具:eclipse 登陆用户分为:普通用户和管理员 普通用户 具有按学号学好查询学生资料功能,普通用户必须先注册,然后登陆、查询。 管理员 可以对学生进行添加...

    jsp基本语法 学习指南

    jsp 基础的学习笔记 第一章语法和el表达式语言的使用 JSP学习要点记录 jsp乱码解决大全 基础开发入门级:JSP与ASP的比较 用EL访问javabean pro jsp第三章第五节代码 .......

    JAVA WEB 开发详解:XML+XSLT+SERVLET+JSP 深入剖析与实例应用.part2

    全书一共被压缩为5个rar,这是第二个!...21.2 中文乱码问题的解决方案 614 21.3 使用过滤器解决中文问题 616 21.4 让tomcat支持中文文件名 620 21.5 国际化与本地化 621 21.5.1 locale 621.. 21.5.2 资源包 623 ...

    J2EE实验指导书*******

    (2)在javabean下新建register_check.jsp,使用页面指令导入JavaBean类或其所在的包:“javabean.Student”%&gt; 24 4、使用&lt;jsp:useBean&gt;访问JavaBean 25 四、实验报告 25 实验八 JSP+JavaBean开发模式1 26 一、实验...

Global site tag (gtag.js) - Google Analytics