这边写了一个方法,调用接口传递中文参数fname时,会获取不到中文参数,英文却能识别,那些UTF-8的设置全都设置了,为什么传递却不能识别到,下面是方法:
public void addFruit(){
System.out.print("请输入添加水果名称: ");
String fname = sc.next();
System.out.println("你输入的水果是: " + fname);
Fruit fruit = fruitDAO.getFruitByFname(fname);
System.out.println("查找到的水果是: " + fruit);
if(fruit == null){ //库存里不存在的水果
System.out.print("请输入水果价格: ");
int fprint = sc.nextInt();
System.out.print("请输入水果库存量: ");
int fcount = sc.nextInt();
System.out.print("请输入水果备注: ");
String fremark = sc.next();
fruit = new Fruit(0,fname, fprint, fcount, fremark); // 封装成新对象
fruitDAO.addFruit(fruit);
}else { //库存存在水果
System.out.print("请输入追加库存量: ");
int fcount = sc.nextInt();
fruit.setFcount(fruit.getFcount() + fcount);
// 调用DAO修改库存的方法
fruitDAO.updateFruit(fruit);
}
System.out.println("添加成功!");
}
接口实现是:
public Fruit getFruitByFname(String fname) {
try {
Class.forName(Driver);
conn = DriverManager.getConnection(URL,USER,PWD);
String sql = "select * from t_fruit where fname like ?";
psmt = conn.prepareStatement(sql);
psmt.setString(1,fname);
System.out.println("名称是: " + fname);
rs = psmt.executeQuery();
if(rs.next()){
int fid = rs.getInt(1);
int fprice = rs.getInt(3);
int fcount = rs.getInt(4);
String remake = rs.getString(5);
return new Fruit(fid, fname, fprice, fcount, remake);
}
} catch (ClassNotFoundException | SQLException e) {
throw new RuntimeException(e);
}
return null;
}
这里中文和英文运行是这样的:
很可能是字符编码不一致导致的。下面给出两种可能的解决方案:
修改参数编码方式
在接口中将传递的参数编码方式修改为UTF-8(或其它双字节字符集,可以与前端协商)。在Java中,可以使用“URLEncoder.encode()”将参数进行编码,例如:
String encodedParam = URLEncoder.encode(rawParam, "UTF-8");
修改服务端编码方式
如果修改参数编码方式无法解决问题,可以考虑修改服务端的编码方式,使其能够正确的解析中文字符。在Java中,可以使用“String.getBytes()”将字符串转成字节数组,并指定编码方式,例如:
String str = "中文字符串";
byte[] bytes = str.getBytes("UTF-8");
然后在服务端中使用字节数组进行解析操作,例如:
String decodedStr = new String(bytes, "UTF-8");
需要注意的是,服务端和前端的编码方式必须一致才能够正确解析中文字符。
数据库连接url也加上字符编码utf8