public class Login extends HttpServlet { PRivate static final String CONTENT_TYPE = "text/Html; charset=UTF-8"; ..... //Initialize global variables public void init() throws ServletException { }
//Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("userid");//隐含的转换
name = new String(name.getBytes("iso-8859-1"), "GB2312");//还原字节,重新构造
response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Login</title></head>"); out.println("<body bgcolor=/"#ffffff/">"); out.println("<p>The servlet has received a GET. This is the reply.</p>"); out.println("</body>"); out.println("</html>"); out.close(); } }
public String uncompress(byte[] cmp) { String ret = ""; int i; byte[] buf = new byte[512]; try { /** *新的方式,始终保持以字节为核心,最后再按照合适的编码进行组装 */ BufferedInputStream bis = new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(cmp)));
/** * 以前的方式 * 在 new InputStreamReader()的时候发生了隐含的byte到char的转换,导致之后出来的都是乱码 */ // BufferedReader bis = new BufferedReader(new InputStreamReader(new // GZIPInputStream(new // ByteArrayInputStream(cmp))));
ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos);
while ( (i = bis.read(buf)) > 0) { bos.write(buf, 0, i); } bos.close(); baos.close(); bis.close(); ret = new String(baos.toByteArray());//用平台默认的编码进行组装,我是GB2312 } catch (IOException ex) { ex.printStackTrace(); }