request方式请求post中文乱码处理
                        程序开发
                        2023-09-20 18:56:27 
                    
                    1.详解
Request接收参数时有get和post两种请求方式,但是处理中文的编码却不一样,我们在做项目时会全站都采用统一的编码,最常用的就是UTF-8,在UTF-8编码的项目中当我们使用post请求时:
处理post编码问题,请求信息中,只有POST存在正文,所谓POST参数编码就是请求正文的编码。
默认情况下,使用getParameter()获取POST请求参数时,使用的是ISO-8859-1编码。


每个请求在开头只需要调用request的setCharacterEncoding()一次,便可所有的编码都会以这种方式来解读,但要注意,只对请求正文有效(POST参数)。
2.演示
第一种方式:
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 test01 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}/** post方式请求处理中文乱码* */@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String name = req.getParameter("name");String introduce = req.getParameter("introduce");// 第一种方式name = new String(name.getBytes("ISO-8859-1"), "UTF-8");System.out.println(name);}
 }
  
 第二种方式:
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 test02 extends HttpServlet {/** post方式请求处理中文乱码* */@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 第二种方式  给request设置编码为:UTF-8(必须在getParameter之前使用)req.setCharacterEncoding("UTF-8");String name = req.getParameter("name");String introduce = req.getParameter("introduce");System.out.println(name);System.out.println(introduce);}
 } 
 
标签:
                            上一篇:
                             Spring MVC教程四
                                                        下一篇:
                                                    
                        相关文章
- 
                    			无相关信息                            
 
