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

查看:214
本文介绍了将请求参数作为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-Type 头的响应字符编码和 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()

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天全站免登陆