servlet-处理请求参数中文乱码问题

servlet-处理请求参数中文乱码问题

设置编码
    tomcat8之前,设置编码:
      1)get请求方式:
        //get方式目前不需要设置编码(基于tomcat8)
        //如果是get请求发送的中文数据,转码稍微有点麻烦(tomcat8之前)
        String fname = request.getParameter("fname");
        //1.将字符串打散成字节数组
        byte[] bytes = fname.getBytes("ISO-8859-1");
        //2.将字节数组按照设定的编码重新组装成字符串
        fname = new String(bytes,"UTF-8");
      2)post请求方式:
        request.setCharacterEncoding("UTF-8");
    tomcat8开始,设置编码,只需要针对post方式
        request.setCharacterEncoding("UTF-8");
    注意:
        需要注意的是,设置编码(post)这一句代码必须在所有的获取参数动作之前
/**
 * @author 程家亮
 * @version 1.0
 */
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
        //get方式目前不需要设置编码方式(基于tomcat8)
        //如果是get请求发送的中文数据,转码稍微有点麻烦(tomcat8之前)
        String fname = request.getParameter("fname");
        //1.将字符串打散成字节数组
        byte[] bytes = fname.getBytes("ISO-8859-1");
        //2.将字节数组按照设定的编码重新组装成字符串
        fname = new String(bytes,"UTF-8");
        */

        //post方式下,设置编码,防止中文乱码
        //需要注意的是,设置编码这一句代码必须在所有的获取参数动作之前
        request.setCharacterEncoding("UTF-8");
        String fname = request.getParameter("fname");
        String priceStr = request.getParameter("price");
        Integer price = Integer.parseInt(priceStr);
        String fcountStr = request.getParameter("fcount");
        Integer fcount = Integer.parseInt(fcountStr);
        String remark = request.getParameter("remark");

        FruitDAO fruitDAO = new FruitDAOImpl();
        boolean flag = fruitDAO.addFruit(new Fruit(0,fname,price,fcount,remark));

        System.out.println(flag ? "添加成功!":"添加失败!");

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值