在tomcat中,读取的表单数据需要使用getBytes( "8859_1 ")转换后入库,resin则不需要,要没有办法做到通用得?
------解决方案--------------------
给你两个转换的工具类
页面与页面之间的
public class ParamUtil {
/**
* 获得request中指定名称的参数值,若有中文乱码问题请增加转码部分
*
* @param request
* ServletRequest对象
* @param paramName
* 参数名称
* @return 如果该变量值存在则返回该值,否则返回 " "
*/
public static String getParameter(ServletRequest request, String paramName) {
String temp = request.getParameter(paramName);
if (temp != null && !temp.equals( " ")) {
// 若有中文问题,请将下面语句注释
try {
temp = new String(temp.getBytes( "8859_1 "), "GB2312 ");
} catch (Exception e) {
return " ";
}
return temp;
} else {
return " ";
}
}
/**
* 获得request中的int型参数值
*
* @param request
* ServletRequest对象
* @param paramName
* 参数名称
* @param defaultNum
* 默认值,如果没有返回该值
* @return 如果该参数值存在则返回其转换为int型的值,否则返回defaultNum
*/
public static int getIntParameter(ServletRequest request, String paramName,
int defaultNum) {
String temp = request.getParameter(paramName);
if (temp != null && !temp.equals( " ")) {
int num = defaultNum;
try {
num = Integer.parseInt(temp);
} catch (Exception ignored) {
}
return num;
} else {
return defaultNum;
}
}
}
页面到数据库的 我用的是过滤器
public class EncodingFilter extends HttpServlet implements Filter {
private static final long serialVersionUID = 1L;
/* 过滤器引用 */
private FilterConfig filterConfig = null;
/* 字符集变量 */
private String charSet = null;
/* 过滤器转换字符集 */
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
/* 获得应用程序配置的字符集 */
charSet = (String) filterConfig.getInitParameter( "charSet ");
/* 设置Http字符集的请求为系统的默认字符集 */
HttpServletRequest req = (HttpServletRequest) request;
req.setCharacterEncoding(charSet);
/* 获得Http的响应 */
HttpServletResponse res = (HttpServletResponse) response;
/* 转发道请求的资源 */
chain.doFilter(req, res);
} catch (Exception e) {
System.out.println( "EncodingFilter " + e.getMessage());
// PrintWriter out = response.getWriter();
// out.println( "Please Login ");
}
}
/* 过滤器销毁 */
public void destroy() {
this.filterConfig = null;
this.charSet = null;
}
/* 过滤器初始化 */
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
}
在web.xml中加上
<filter>
<filter-name> EncodingFilter </filter-name>
<filter-class> com.menu.servlet.EncodingFilter(EncodingFilter类在工程中的位置) </filter-class>
<init-param>
<param-name> charSet </param-name>
<param-value> UTF-8 </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name> EncodingFilter </filter-name>
<url-pattern> /* </url-pattern>
</filter-mapping>
------解决方案--------------------
up
------解决方案--------------------
一楼的是个好方法.
------解决方案--------------------