一个汉字utf-8的字符串3个字节,转成GB2312是2个字节,转成GB2312的字符串是4个字节。
英文字母和数字不管编码是什么编码,都是一个字节。
数据传输的时候一般,转码后,字节不够的话,一般在后面补0
package servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CustomerServlet extends HttpServlet {
public static void main(String[] args) throws Exception {
String a="行一";
byte[] b=a.getBytes("GB2312");
System.out.println( bytesToHexFun1(b).toUpperCase());
int c= 0 >> 8;
System.out.println(c);
}
public static String bytesToHexFun1(byte[] bytes) {
char[] HEX_CHAR = {'0','1','2','3','4','5',
'6','7','8','9','a','b','c','d','e','f'};
// 一个byte为8位,可用两个十六进制位标识
char[]buf = new char[bytes.length*2];
int a = 0;
int index = 0;
for(byte b : bytes){// 使用除与取余进行转换
if(b<0){
a=256+b;
}else{
a=b;
}
buf[index++]=HEX_CHAR[a/16];
buf[index++]=HEX_CHAR[a%16];
}
return new String(buf);
}
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设定请求的字符集
req.setCharacterEncoding("utf-8");
//设置响应的文本类型
resp.setContentType("text/html;charset=utf-8");
//通过请求对象获取用户输入的内容
String username = req.getParameter("username");
String password = req.getParameter("userpwd");
System.out.println(username+" "+password);
//如果输入的用户名是abc,密码是123,则表示注册成功,反之注册失败
if("abc".equals(username)&&"123".equals(password)){
//使用响应对象,重定向到成功页面
//resp.sendRedirect("success.html");
//请求转发
req.getRequestDispatcher("success.html").forward(req, resp);;
}else{
//使用响应对象,重定向到注册页面
resp.sendRedirect("register.html");
}
}