# servlet請求出現中文亂碼(編碼設置)
###### tags: `Java Web-問題以及解決`
### 輸入中文添加後,在mysql資料庫中,中文會呈現亂碼
添加畫面:

mysql資料庫:

### 原因:
表單是由此html文件發出,其中執行的method=post,是由AddServlet.java文件發出
```htmlmixed=
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="add" method="post">
名稱:<input type="text" name="fname"/><br/>
價格:<input type="text" name="price"/><br/>
庫存:<input type="text" name="fcount"/><br/>
備註:<input type="text" name="remark"/><br/>
<input type="submit" value="添加"/><br/>
</form>
</body>
</html>
```
AddServlet.java內容
```java=
public class AddServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
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 ? "添加成功" : "添加失敗!");
}
}
```
透過debug功能找出出現亂碼的原因(使用step over逐步找)
(1)看到fname的位置出現亂碼

### 解決方法:在此方式下設置編碼
添加編碼
```java=
request.setCharacterEncoding("UTF-8");
```
完整程式碼:
```java
public class AddServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
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 ? "添加成功" : "添加失敗!");
}
}
```
後台結果:

資料庫:

成功
### 注意事項
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");
注意:
需要注意的是,設置編碼這一句代碼必須在所有的獲取參數動作之前