第一种:原始编码转换
- 在get请求中,每次获取参数,都使用下列方式转化
- new String(name.getBytes(“ISO-8859-1”), “UTF-8”);
- post方式在获取参数前转化编码格式即可
- req.setCharacterEncoding(“UTF-8”);
- 缺点:需要在每个Servlet上每次请求都需要转化处理,太过麻烦,推荐使用第二种或第三种
代码
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String name = req.getParameter("name");
name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("Get name:" + name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
System.out.println("Post name:" + name);
}
第二种:动态代理编码过滤
过滤器代码
public class EncodingFilter implements Filter
{
@Override
public void destroy()
{
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest request