Javaweb接收表单数据并处理中文乱码的方法-创新互联-古蔺大橙子建站
RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
Javaweb接收表单数据并处理中文乱码的方法-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名虚拟主机、营销软件、网站建设、宁洱网站维护、网站推广。

这篇文章主要讲解了Javaweb接收表单数据并处理中文乱码的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

前端表单数据

常见的表单项的传值,如:

  • 普通input
  • 单选radio
  • 多选checkbox
  • select下拉选择
  • textarea文本域
     

普通 input : name属性值为后台接收时的参数值。

用户名:

密码:

单选 radio :单选按钮的 name 值相同才能实现只能点击一个。

性别:


多选checkbox :name值相同。

爱好:


跳舞
rap
篮球

select下拉选择 :后台通过degree作为参数,获取选中的那个option的value值。

下拉选择:

textarea文本域 :rows定义显示的行数,cols定义的是显示的列数。

文本域:

后台接收数据

接收表单数据:

String 表单name= request.getParameter(表单name);

普通input、单选radio、select下拉选择、textarea文本域可通过此方法获取。

String[] hobbies = request.getParameterValues("hobby");

多选checkbox可通过此方法获取。

中文乱码处理

GET方式提交的数据

先通过 String username = request.getParameter(username) 获得该表单的值,此时是乱码的。

使用String new_username = new String(username.getBytes("iso8859-1"), "utf-8") 进行编码转换

相关APi :

String(byte[] bytes, Charset charset) 构造一个新的String,由指定的字节的数组转化为指定编码的字节数组。

getBytes(Charset charset)使用指定的编码方式将该String编码为字节序列,将结果存储到新的字节数组中。

解释:通过get方式提交的数据的编码方式为iso8859-1, 先获取该编码方式的字节数组,再将该字节数组转化为utf-8编码的字节数组,然后将该字节数组转换为字符串。

POST方式提交的数据

request.setCharacterEncoding("utf-8");

服务器端向客户端发送的数据

response.setContentType("text/html;charset=utf-8");

以下是全部代码:

GET提交方式:

@WebServlet(name = "RegisterServlet",urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //get提交方式处理中文乱码
    String username = request.getParameter("username");
    String new_username = new String(username.getBytes("iso8859-1"), "utf-8");
    
    String password = request.getParameter("password");
    String new_password = new String(password.getBytes("iso8859-1"), "utf-8");
    
    String gender = request.getParameter("gender");
    String new_gender = new String(gender.getBytes("iso8859-1"), "utf-8");
    
    String[] hobbies = request.getParameterValues("hobby");
    for (int i = 0; i < hobbies.length; i++) {
      hobbies[i]=new String(hobbies[i].getBytes("iso8859-1"), "utf-8");
    }
    
    String degree = request.getParameter("degree");
    String new_password = new String(password.getBytes("iso8859-1"), "utf-8");
    
    String other = request.getParameter("other");
    String new_password = new String(password.getBytes("iso8859-1"), "utf-8");
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }
}

网站名称:Javaweb接收表单数据并处理中文乱码的方法-创新互联
浏览地址:http://scgulin.cn/article/ddecdh.html