1 下载pinyin.jar

下载jar包
2 Controller代码
字符串中间可能会有多个汉字,需要逐一将字符串中间的每个字符依次转换成拼音。所以需要根据字符串中间的字符数多次转换。
某些汉字会有多个读音,多音字,所以将字符转换成拼音的时候,可能会出现多个读音,所以返回一个数组,数组的每个元素是汉字的一个读音.
在字符串中间可能会出现符号或者数字等,不能转换成拼音的内容,所以转换结束,需要判断转换是否成功,如果不成功,本次转换放弃,可以直接执 行其他的转换.
代码:
package com.wanmait.pinyin.servlet;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "TestServlet", value = "/TestServlet")
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");//设置request的编码 否则中文可能会乱码
response.setCharacterEncoding("utf-8");//设置response的编码
String content = request.getParameter("content");//获得表单输入的字符串
//取汉字的拼音
HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();//创建转换品应的格式对象
//设置汉语拼音类型
hanyuPinyinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);//拼音小写
hanyuPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//不标声调
hanyuPinyinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);//u的声母替换成v
//content是输入的字符串 content.length()字符串的长度
for(int i=0;i<content.length();i++)//每个汉字循环一次
{
try {
String array[] = PinyinHelper.toHanyuPinyinStringArray(content.charAt(i),hanyuPinyinOutputFormat);
//一个汉字转换成拼音 数组的每个元素是一个拼音 如果汉字是多音字 数组才会出现多个元素
if(array==null||array.length==0)//其中某个字符不能转换拼音
{
continue;
}
//输出拼音 只取第一个发音
response.getWriter().write(array[0]);
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
}
}
}执行结果:



0条评论
点击登录参与评论