get请求正确书写中文
- 以一个登陆界面为例
package com.itheima.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 LoginServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println("username="+username+"==password="+password);//这个是没有转嘛之前的
//get请求在地址栏上已经编过码了,所以我们收到的就是乱码
//tomcat收到这批数据getParamter默认使用的就是ISO-8859-1去解码
//先让文字回到ISO-8859-1对应的自己数组然后按utf-8组拼字符串
username=new String(username.getBytes("ISO-8859-1"),"utf-8");
System.out.println("username="+username+"==password="+password);
}
}
因为在地址栏上已经转码了,所以再接收的时候需要再转一次,就是负负为正的意思,默认的是ISO-8859-1,想要看见中文就要转为utf-8
- 登陆界面也给大家放在这里
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>请输入以下内容,完成登录</h2>
<form action="/LoginServlet2" method="get">
账号<input type="text" name="username"><br>
密码<input type="text" name="password"><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>
- 解决post请求中文乱码问题
- `package com.itheima.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class LoginServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//qingqiu(request);
//post请求处理方法
request.setCharacterEncoding("UTF-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println("post:username="+username+"==password="+password);
}
private void qingqiu(HttpServletRequest request) throws UnsupportedEncodingException {
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println("username="+username+"==password="+password);//这个是没有转嘛之前的
//get请求在地址栏上已经编过码了,所以我们收到的就是乱码
//tomcat收到这批数据getParamter默认使用的就是ISO-8859-1去解码
//先让文字回到ISO-8859-1对应的自己数组然后按utf-8组拼字符串
username=new String(username.getBytes("ISO-8859-1"),"utf-8");
System.out.println("username="+username+"==password="+password);
}
}
`