JSP/Servlet --- 编码问题

情景1

描述:jsp页面page指定编码为UTF-8,在没有任何过滤器的情况下,向servlet容器发送HTTP请求,如通过表单提交数据,传递的信息会被封装在HttpServletRequest对象request里面,若直接处理提交过来的中文字符串,会出现乱码

<%@ page contentType="text/html; charset=UTF-8"%>
...
<form method="post" action="/ServletModel/model/UploadServlet">
    <input type="text" name="name">
    <input type="submit" value="提交"/>
</form>
...

servlet里面

System.out.println(request.getParameter("name")); //?????全是问号
看到request里面有一个方法是获取编码,但是返回值是null,说明request对象里面是没有设置编码的
request.getCharacterEncoding(); //null

那么应该就有一个set方法,应该是将传送过来的数据进行编码

request.setCharacterEncoding("UTF-8")

这样就正常了,这说明之前的默认编码方式并不是UTF-8,它并不受页面编码所控制。据网上资料所说默认为ISO- 8859-1编码

同时响应的时候也应该设置编码,如

response.setContentType("text/html; charset=UTF-8");


猜你喜欢

转载自blog.csdn.net/qq_24986539/article/details/79392265