将请求参数作为 UTF-8 编码字符串传递 [英] Passing request parameters as UTF-8 encoded strings

查看:26
本文介绍了将请求参数作为 UTF-8 编码字符串传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的登录页面,我想将登录名和密码参数作为 UTF-8 编码字符串传递.正如您在下面的代码中看到的,第一行是我将编码设置为 UTF-8 的地方,但这似乎毫无意义,因为它不起作用.当我使用带有重音符号的登录名和密码参数时,结果页面会收到奇怪的字符.

I am creating a simple login page and I want to pass login and password parameters as UTF-8 encoded strings. As you can see in the code below, the first line is where I set encoding to UTF-8, but it seems this is pointless because it doesn't work. When I use login and password parameters with accents the result page receives strange characters.

如何以一种适用于所有浏览器的方式正确设置字符编码?

How to set character encoding correctly in a way that works in all browsers?

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>My Page</title>
    </head>

    <body>
        <h1>Welcome to My Page</h1>

        <form name="login" action="login.jsp" method="POST">
            Login:<br/>
            <input type="text" name="login" value="" /><br/>
            Password:<br/>
            <input type="password" name="password" value="" /><br/>
            <br/>
            <input type="submit" value="Login" /><br/>
        </form>

    </body>
</html>

推荐答案

pageEncoding 只设置响应字符编码和 HTTP Content 的 charset 属性- 输入 标题.基本上,它告诉服务器在将 JSP 生成的字符发送到客户端之前将其解码为 UTF-8,标头告诉客户端使用 UTF-8 对它们进行编码,并在同一页面中的任何表单是提交回服务器.contentType 已经默认为 text/html,所以下面就足够了:

The pageEncoding only sets the response character encoding and the charset attribute of the HTTP Content-Type header. Basically, it tells the server to decode the characters produced by JSP as UTF-8 before sending it to the client and the header tells the client to encode them using UTF-8 and also to use it when any forms in the very same page is to be submitted back to the server. The contentType already defaults to text/html, so below is sufficient:

<%@page pageEncoding="UTF-8"%>

当页面通过 HTTP 提供时,HTML 元标记将被忽略.仅当页面被客户端保存为本地磁盘系统上的 HTML 文件并然后在浏览器中通过 file:// URI 打开时使用.

The HTML meta tag is ignored when the page is served over HTTP. It's only been used when the page is by the client saved as a HTML file on local disk system and then opened by a file:// URI in browser.

在您的特定情况下,HTTP 请求正文编码显然未设置为 UTF-8.请求正文编码需要通过 ServletRequest#setCharacterEncoding() 在 servlet 或过滤器中 before request.getXxx() 的第一次调用 曾经在请求中涉及的任何 servlet 或过滤器中创建.

In your particular case, the HTTP request body encoding is apparently not been set to UTF-8. The request body encoding needs to be set by ServletRequest#setCharacterEncoding() in the servlet or a filter before the first call on request.getXxx() is ever made in any servlet or filter involved in the request.

request.setCharacterEncoding("UTF-8");
String login = request.getParameter("login");
String password = request.getParameter("password");
// ...

另见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆