JavaWeb之不同Tomcat版本對get、post請求,中文亂碼問題
阿新 • • 發佈:2018-12-30
Myeclipse安裝時的前期工作空間的編碼準備,就不說了
Tomcat8
Tomcat8.x 以前版本public class dd extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Tomcat8 resp.setContentType("text/html;UTF-8"); req.setCharacterEncoding("UTF-8"); System.out.println(req.getParameter("name")); } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(req.getParameter("name")); //不用進行ISO轉碼 } }
測試:jsppublic class ee extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(request.getParameter("name")); //?????? //需要進行 ISO 解碼 ,utf 編碼 String name = request.getParameter("name"); System.out.println(new String(name.getBytes("ISO-8859-1"),"UTF-8"));//你好 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); System.out.println(request.getParameter("name")); // post請求 } }
也可以使用直接修改配置檔案的辦法:<body> <a href="${pageContext.request.contextPath}/dd?name=你好">GET</a> <form action="${pageContext.request.contextPath}/dd" method="post"> <span style="white-space:pre"> </span><input type="text" name="name" /> <span style="white-space:pre"> </span><input type="submit" value="提交post" /> </form> <form action="${pageContext.request.contextPath}/dd" method="get"> <span style="white-space:pre"> </span><input type="text" name="name" /> <span style="white-space:pre"> </span><input type="submit" value="提交get"/> </form> </body>
再Tomcat根目錄下的config.xml檔案,找到<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
再其中新增:URIEncoding="UTF-8" 和 useBodyEncodingForURI=“true”
useBodyEncodingForURI(預設false):引數表示是否用 與 request.setCharacterEncoding一致的編碼
如果是true,引數對URL提交的資料和表單中GET方式提交的資料進行重新編碼。
URIEncoding (預設ISO8859-1)引數指定對所有GET方式請求進行統一的重新編碼(解碼)的編碼。
URIEncoding |
This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, UTF-8will be used unless the |
PS:極其不建議在Tomcat的配置檔案上做編碼的修改,因為你不知道使用者用的什麼版本或根本就不是Tomcat,總不能和使用者說:別用weblogic,你用tomcat 吧,再順便那個配置檔案改改