1. 程式人生 > >對於Servlet的get請求和post請求的兩種資料請求的編碼格式

對於Servlet的get請求和post請求的兩種資料請求的編碼格式

@WebServlet(name = "EncodingServlet",urlPatterns = "/e/es")
public class EncodingServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        System.out.println(request.getCharacterEncoding());
        //這裡的引數是在jsp檔案中設定的引數屬性 在獲取引數之前要使用上面的轉碼
System.out.println("POST---username:"+request.getParameter("username")); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //同理 這裡的引數也是jsp檔案設定的引數屬性 String uname = request.getParameter("username"); //通過iso編碼,將字串uname回退到位元組陣列狀態
byte[] bytes = uname.getBytes("iso-8859-1"); System.out.println(request.getCharacterEncoding()); //根據該位元組陣列,建立一個符合utf-8編碼的字串 uname = new String(bytes,"utf-8"); System.out.println("GET---username:"+uname); } }