Use the function below to store the String or value in DB in Encoded form.
if (st== null ){
st= "" ;
}
InputStream inp = new ByteArrayInputStream(st.getBytes());
Reader reader = null ;
try {
//Correct encoding type need to be set before storing in DB. No need to change the DB field datatype from Varchar2 to NVarchar2.
reader = new BufferedReader( new InputStreamReader(inp, "UTF-8" ));
pstmt.setCharacterStream(index, reader, st.length());
} catch (UnsupportedEncodingException e) {
log .fatal( "encodeStringInPstmt() | UnsupportedEncodingException = " +e);
} catch (SQLException s){
log .fatal( "encodeStringInPstmt() | SQLException = " +s);
}
}
public static final String utf8Convert(String utf8String) throws java.io.UnsupportedEncodingException {
if (utf8String== null ){
utf8String = "" ;
}
byte [] bytes = new byte [utf8String.length()];
for ( int i = 0; i < utf8String.length(); i++) {
bytes[i] = ( byte ) utf8String.charAt(i);
}
reader = new BufferedReader( new InputStreamReader(inp, "UTF-8" ));
pstmt.setCharacterStream(index, reader, st.length());
} catch (UnsupportedEncodingException e) {
log .fatal( "encodeStringInPstmt() | UnsupportedEncodingException = " +e);
} catch (SQLException s){
log .fatal( "encodeStringInPstmt() | SQLException = " +s);
}
}
This function converts the encoding type of the value to be printed on JSP. The value retrieved from DB, which was stored using function above. The value need to be converted to correct encoding type before printing on JSP. Don't forget to set the encoding type of JPS to UTF-8.
public static final String utf8Convert(String utf8String) throws java.io.UnsupportedEncodingException {
if (utf8String== null ){
utf8String = "" ;
}
byte [] bytes = new byte [utf8String.length()];
for ( int i = 0; i < utf8String.length(); i++) {
bytes[i] = ( byte ) utf8String.charAt(i);
}
String outputString = new String(bytes, "UTF-8" );
return outputString;
}
return outputString;
}
No comments:
Post a Comment