request.getParameter(pName)传参中文问题

本文介绍了解决Web应用程序中UTF-8字符集下出现乱码的方法,包括配置Servlet容器、创建过滤器设置请求编码、配置JSP页面编码等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question:

After a lot of trial and error I still can’t figure out the problem. The JSP, servlet, and database are all set to accept UTF-8 encoding, but even still whenever I use request.getParameter on anything that has any two-byte characters like the em dash they get scrambled up as broken characters.

I’ve made manual submissions to the database and it’s able to accept these characters, no problem. And if I pull the text from the database in a servlet and print it in my jsp page’s form it displays no problem.

The only time I’ve found that it comes back as broken characters is when I try and display it elsewhere after retrieving it using request.getParameter.

Has anyone else had this problem? How can I fix it?

Answer:

That can happen if request and/or response encoding isn’t properly set at all.

For GET requests, you need to configure it at the servletcontainer level. It’s unclear which one you’re using, but for in example Tomcat that’s to be done by URIEncoding attribute in <Connector> element in its /conf/server.xml.

<Connector ... URIEncoding="UTF-8">
For POST requests, you need to create a filter which is mapped on the desired URL pattern covering all those POST requests. E.g. .jsp or even /. Do the following job in doFilter():

request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);

For HTML responses and client side encoding of submitted HTML form input values, you need to set the JSP page encoding. Add this to top of the JSP (you’ve probably already done it properly given the fact that displaying UTF-8 straight form DB works fine).

<%@page pageEncoding="UTF-8" %>
Or to prevent copypasting this over every single JSP, configure it once in web.xml:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

For source code files and stdout (IDE console), you need to set the IDE workspace encoding. It’s unclear which one you’re using, but for in example Eclipse that’s to be done by setting Window > Preferences > General > Workspace > Text File Encoding to UTF-8.

enter image description here

Do note that HTML <meta http-equiv> tags are ignored when page is served over HTTP. It’s only considered when page is opened from local disk file system via file://. Also specifying <form accept-charset> is unnecessary as it already defaults to response encoding used during serving the HTML page with the form. See also W3 HTML specification.

### Java Servlet中 `request.getParameter` 的使用方法及常见问题 在Java Servlet中,`request.getParameter(String name)` 是一个非常重要的方法,用于从客户端请求中获取参数值。它主要用来处理通过GET或POST请求传递的表单数据或其他查询字符串中的参数[^1]。以下是关于该方法的详细说明和常见问题解答: #### 1. 基本用法 `request.getParameter(String name)` 方法会根据指定的参数名从请求中提取对应的值。例如: ```java String username = request.getParameter("username"); ``` 上述代码会从请求中获取名为 `username` 的参数值,并将其存储为一个 `String` 类型的变量。需要注意的是,`getParameter` 方法只能返回 `String` 类型的值[^1]。 #### 2. 处理多值参数 当同一个参数名对应多个值时(例如复选框),可以使用 `request.getParameterValues(String name)` 方法来获取所有值。该方法返回一个 `String[]` 数组。例如: ```java String[] hobbies = request.getParameterValues("hobby"); if (hobbies != null) { for (String hobby : hobbies) { System.out.println(hobby); } } ``` #### 3. 参数不存在时的行为 如果请求中不存在指定的参数名,`request.getParameter(String name)` 方法将返回 `null`[^4]。例如: ```java String age = request.getParameter("age"); if (age == null) { System.out.println("Age parameter is not provided."); } else { System.out.println("Age: " + age); } ``` 此外,如果参数存在但未填写值,则会返回一个空字符串 `""` 而不是 `null`。例如: ```html <input type="text" name="username"> ``` 如果用户未填写 `username` 字段,`request.getParameter("username")` 将返回 `""`。 #### 4. 编码问题 在处理中文或其他非ASCII字符时,可能会遇到乱码问题。为了避免这种情况,可以在读取参数之前设置请求的字符编码: ```java request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); ``` 需要注意的是,此设置必须在调用 `getParameter` 方法之前完成[^4]。 #### 5. 请求方式的影响 `request.getParameter(String name)` 可以同时处理GET和POST请求中的参数。对于GET请求,参数通常出现在URL的查询字符串中;而对于POST请求,参数则位于请求体中。 --- ### 示例代码 以下是一个完整的Servlet示例,展示如何使用 `request.getParameter` 方法: ```java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/login") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置字符编码 request.setCharacterEncoding("UTF-8"); // 获取用户名和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); // 检查参数是否存在 if (username == null || password == null || username.isEmpty() || password.isEmpty()) { response.getWriter().println("Username or password is missing."); return; } // 简单验证逻辑 if ("admin".equals(username) && "123456".equals(password)) { response.getWriter().println("Login successful!"); } else { response.getWriter().println("Invalid username or password."); } } } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值