JavaWeb学习五(编码和路径)

xiaoxiao2021-02-28  109

一.编码

1.常见字符编码

iso-8859-1(不支持中文) gb2312 gbk gb18030(系统默认 中国国标码) utf-8(万国码 我们要用的)

2.响应编码

服务器发给浏览器

response.getWriter();之前使用response.setCharceterEncoding()来设置字符流的编码为utf-8 response.getWriter();之前使用 response.setHeader("Conntent-type","text/html;charset=uft-8")设置响应头 同时也通知浏览器服务器两边使用utf-8;

举例

public class FServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().print("呵呵"); } }

乱码了…再看看我们添加上两行代码的效果

public class FServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type","text/html;charset=utf-8"); //相当于上面这句response.setContentType("text/html;charset=utf-8"); response.getWriter().print("呵呵"); } }

3.请求编码

浏览器发给服务器请求编码处理分为两种:GET和POST,GET请求参数不再请求体中,而POST请求参数在请求体中 所以它们的处理方式是不同的

解决请求乱码方式有很多,其中这样也可以解决 去Tomcat安装目录下conf文件查看server.xml添加如下红框

注意:但是这种方式并不建议使用

(1).GET请求编码处理
String username = new String(request.getParameter("xxx").getByts("iso-8859-1"),"utf-8");

注意:在server.xml中配置URIEncoding=utf-8这种方式不能使用

(2).POST请求编码处理
String username = request.getParameter("xxx"); //在获取参数之前调用request.setCharacterEncoding("utf-8");

举例

public class GServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("username"); System.out.println(username); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String username=request.getParameter("username"); System.out.println(username); } }

4.URL编码

表单的类型:Content-Type:application/X-www-form-urlencoded 就是把中文转换成%后面跟随两位的16进制在客户端和服务器之间传递非英文时需要把它转换成网络适合的方式 URL编码: String username=URLEncoder.encode(username,"utf-8"); URL解码: String username=URLDecoder.decode(username,"utf-8"); public class Temp { //[-25, -77, -106, -25, -77, -106] //
转载请注明原文地址: https://www.6miu.com/read-96662.html

最新回复(0)