汉字自动转换成拼音:
流程:
- 先引入相对应的jar包
<!-- pinyin4j -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>${pinyin4j.version}</version>
</dependency>
- 编写一个工具类
public class PinyinUtils {
// 返回一个拼音字符串,并且首字母大写
public static String getPingYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
String output = "";
if (inputString != null && inputString.length() > 0 && !"null".equals(inputString)) {
char[] input = inputString.trim().toCharArray();
try {
for (int i = 0; i < input.length; i++) {
if (Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
output += temp[0];
} else
output += Character.toString(input[i]);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
return "*";
}
return output;
}
public static void main(String[] args) {
String yin = getPingYin("测试");
System.out.println(yin);
}
}
- 在控制器里面写一个对应的方法
/**
* 把用户名转成拼音
*/
@RequestMapping("changeChineseToPinyin")
public Map<String,Object> changeChineseToPinyin(String username){
Map<String,Object> map=new HashMap<>();
if(null!=username) {
map.put("value", PinyinUtils.getPingYin(username));
}else {
map.put("value", "");
}
return map;
}
- 在前端界面进行展示
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">用户姓名</label>
<div class="layui-input-inline">
<input type="text" name="name" id="username" lay-verify="required" autocomplete="off" placeholder="请输入用户姓名" class="layui-input">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">登陆名称</label>
<div class="layui-input-inline">
<input type="text" name="loginname" id="loginname" lay-verify="required" autocomplete="off" placeholder="请输入登陆名称" class="layui-input">
</div>
</div>
</div>
对应的js代码
//监听用户名的失去焦点事件
$("#username").on("blur",function(){
var username=$(this).val();
$.get("/user/changeChineseToPinyin",{username:username},function(res){
$("#loginname").val(res.value);
})
});