中文乱码,貌似在java里很常见,请看简单代码:
很简单的faces
<div class="td-block"> <h:outputLabel class="first-td fl">测试取值:</h:outputLabel> <h:inputText value="#{summary.title}" > </h:inputText> </div> <h:commandButton value="查询" class="btn-12" action="#{summary.search()}"> </h:commandButton>
bean
private String title; public String search() { if(i==2) { return "ok"; } if(title.equals("一本书")) return "ok"; else{ return "false"; } } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; }
当输入中文 在获取输入值时始终是乱码,各种解决不行。。
后来看到一篇文章(具体文章不记得)使用转换器。
在看使用转换器具体实现:
package com.cnpdx; import java.io.UnsupportedEncodingException; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; /** * * @author taoxy */ public class StringConverter implements Converter{ /** * * @param context * @param component * @param newValues * @return * @throws ConverterException */ @Override public Object getAsObject(FacesContext context, UIComponent component,String newValues) throws ConverterException { String newstr = ""; if (newValues == null) { newValues = ""; } byte[] byte1 = null; try { byte1 = newValues.getBytes("ISO-8859-1"); newstr = new String(byte1, "UTF-8"); UIInput input=(UIInput)component;// input.setSubmittedValue(newstr); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return newstr; } public String getAsString(FacesContext context, UIComponent component, Object Values) throws ConverterException { return (String) Values; } }
配置一下faces-config
<converter> <converter-id>com.cnpdx.stringconverter</converter-id> <converter-class>com.cnpdx.StringConverter</converter-class> </converter>
最后修改下faces
修改如下:
<div class="td-block"> <h:outputLabel class="first-td fl">测试取值:</h:outputLabel> <h:inputText value="#{summary.title}" > <f:converter converterId="com.cnpdx.stringconverter"></f:converter> </h:inputText> </div>
OK 中文乱码问题算是解决了