步骤1:使用Servlet处理的局限性
步骤2:使用Filter处理
步骤3:配置web.xml
步骤4:测试
步骤 1 : 使用Servlet处理的局限性
在通过Servlet获取中文参数 的章节中知道,可以通过
request.setCharacterEncoding( "UTF-8" );
|
正确获取UTF-8编码的中文,但是如果有很多servlet都需要获取中文,那么就必须在每个Servlet中增加这段代码。
有一个简便的办法,那就是通过Filter过滤器进行中文处理 ,那么所有的Servlet都不需要单独处理了。
步骤 2 : 使用Filter处理
创建一个 EncodingFilter ,设置如下代码
HttpServletRequest request = (HttpServletRequest) req;
request.setCharacterEncoding( "UTF-8" );
|
doFilter方法的第一个参数req,是ServletRequest 类型的,不支持setCharacterEncoding,所以要先强制转换为HttpServletRequest
package filter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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;
import javax.servlet.http.HttpServletResponse;
public class EncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
request.setCharacterEncoding( "UTF-8" );
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
|
步骤 3 : 配置web.xml
配置EncodingFilter
<url-pattern>/*</url-pattern>
|
表示为所有的访问都使用该Filter
< filter >
< filter-name >EncodingFilter</ filter-name >
< filter-class >filter.EncodingFilter</ filter-class >
</ filter >
< filter-mapping >
< filter-name >EncodingFilter</ filter-name >
< url-pattern >/*</ url-pattern >
</ filter-mapping >
|
步骤 4 : 测试
测试前,记得把HeroAddServlet中的
request.setCharacterEncoding( "UTF-8" );
|
注释掉
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.Hero;
import dao.HeroDAO;
public class HeroAddServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// request.setCharacterEncoding("UTF-8");
Hero hero = new Hero();
hero.setName(request.getParameter( "name" ));
hero.setHp(Float.parseFloat(request.getParameter( "hp" )));
hero.setDamage(Integer.parseInt(request.getParameter( "damage" )));
new HeroDAO().add(hero);
response.sendRedirect( "/listHero" );
}
}
|
更多内容,点击了解: https://how2j.cn/k/filter/filter-encoding/589.html