关于Servlet编码的问题
问题描述:
在下面这个Servlet方法中加了两行输出编码格式的代码(粉红色代码),目的是为了能够正确显示中文,因为我在测试的时候如果不加这两行代码,浏览器总是显示乱码.加上之后才能够正确显示中文.现在我的问题是有什么方法可以不采用这种方法去改变中文乱码的问题啊.如果我有几十个Servlet的页面呢.我总不能在这些页面中每个都加入这两行代码吧.我觉得这是一种很笨的方法.而且对于代码的管理很不好.我希望你能够给我一种好的解决方案.
解决方案:
请在此书写解决过程.谢谢.
public void doPost(HttpServletRequest request, HttpServletResponse response)throws
ServletException,
IOException {
/** 统一编码,否则乱码 */
response.setContentType( "text/html ");
response.setCharacterEncoding( "UTF-8 ");
PrintWriter out = response.getWriter();
String username = request.getParameter( "username ");
String password = request.getParameter( "password ");
Member member = new Member();
member.setUsername(username);
member.setPassword(password);
out.println( "Usernmae is: "+username+ "Password is "+password);
LoginUser lu = new LoginUser();
lu.queryByName(username, password);
out.println( "登录成功 ");
}
------解决方案--------------------写一个filter
这个写在web.xml中
<filter>
<filter-name> SetCharacterEncoding </filter-name>
<filter-class>
com.classmate.struts.common.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name> encoding </param-name>
<param-value> gb2312 </param-value>
</init-param>
<init-param>
<param-name> enable </param-name>
<param-value> true </param-value>
</init-param>
</filter>
这个是过滤器的实现
/**
* CharacterEncodingFilter.java
*
* 功 能:字符集过滤器
* 类 名:CharacterEncodingFilter
*
* 版本 日期 担当 操作
*---------------------------------------------------
* v1.00.00 '07-05-20 ' 新规
*
*/
package com.classmate.struts.common;
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;
public class CharacterEncodingFilter implements Filter {
protected FilterConfig filterConfig;
protected String encodingName;
protected boolean enable;
public CharacterEncodingFilter() {
this.encodingName = "gb2312 ";
this.enable = false;
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
loadConfigParams();
}
private void loadConfigParams() {
// encoding
this.encodingName = this.filterConfig.getInitParameter( "encoding ");
// filter enable flag...
String strIgnoreFlag = this.filterConfig.getInitParameter( "enable ");
if (strIgnoreFlag.equalsIgnoreCase( "true ")) {
this.enable = true;
} else {