站内搜索: 请输入搜索关键词

当前页面: 开发资料首页JSP 专题中文字符从jsp传送到servlet的处理

中文字符从jsp传送到servlet的处理

摘要: 中文字符从jsp传送到servlet的处理
对于在jsp和servlet中的request.getParameter()方法,如果你想要传入
中文字符,有几种解决方法,
一:可以在String temp = request.getParameter("xx");
temp = new String(temp.getBytes("ISO8859_1"));
二:常用的方法为,设置一个过滤器:
1. java文件为com.esoon.shabc.utils.SetCharacterEncodingFilter
源文件:
package com.esoon.shabc.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
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 javax.servlet.http.HttpServletRequest;

public class SetCharacterEncodingFilter
implements Filter {

protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;

/**
* 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.
*/
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); //设置request编码的地方
}

// Pass control on to the next filter
// 传递控制到下一个过滤器
chain.doFilter(request, response);
}

/**
* Place this filter into service.
* 从web-app的web.xml文件中读取初始参数的值
*/

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;
}

/**
* 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
* null.
* 选择request原来的编码
*/
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
2. 然后在web.xml文件中中间添加:

Set_Character_Encoding
com.esoon.shabc.utils.SetCharacterEncodingFilter

encoding
gb2312



Set_Character_Encoding
/*

3. 如果所提交的字段在form里面,则这个form应该设置为:method="post"
类似于: <form method="post" name="firstPriInfoForm" ></form>
通过这种方法,即使你所提交有多个中文字段,那么你在servlet中只需要
request.getParameter("##");
而无需再一次new String() 的转换。

↑返回目录
前一篇: 使用jsp实现word、excel格式报表打印
后一篇: 利用JSP 2.0开发Web应用程序