Servlet 中文编码问题

本文详细介绍了在Servlet中处理中文编码问题的方法,包括如何正确获取中文参数和返回中文响应,确保网页显示正常。

Servlet 中文编码问题

Servlet 中涉及到两大中文编码问题:

  1. 获取中文的参数
  2. 返回中文的响应

获取中文的参数

为了成功获取中文参数,需要做如下操作

  1. login.html 中加上 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  2. login.html 中的 formmethod 修改为 post

  3. servlet进行解码和编码

    byte[] bytes=  username.getBytes("ISO-8859-1");
    username = new String(bytes,"UTF-8");
    

    先根据 ISO-8859-1 解码,然后用 UTF-8 编码,这样就可以得到正确的中文参数。这样需要对每一个提交的数据都进行编码和解码处理,也可以使用一句话代替:

    request.setCharacterEncoding("UTF-8");  // 放在 request.getParameter() 之前
    

以上是使用 UTF-8 的方式获取中文。也可以使用 GBK

<!DOCTYPE html>
 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
<form action="login" method="post">
    账号 : <input type="text" name="username"> <br> 
    密码: <inpu type="password" name="password"> <br> 
    <input type="submit" value="登录">
</form>
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class LoginServlet extends HttpServlet {

    @override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("username");
        // byte[] bytes = name.getBytes("ISO-8859-1");
        // name = new String(bytes, "UTF-8");
        String password = request.getParameter("password");
        System.out.println("username:" + username);
    }

}

返回中文的响应

LoginServlet 中,加上 response.setContentType("text/html; charset=UTF-8");

import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class LoginServlet extends HttpServlet {

    @override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        String html = null;
        if ("admin".equals(username) && "admin".equals(password)) {
            html = "<div style='color:green'>登录成功</div>";
        } else {
            html = "<div style='color:red'>登录失败</div>";
        }
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.println(html);
    }
 
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值