您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> jsp编程 >> 正文

常见JSP中文乱码例子及其解决方法

作者:佚名    责任编辑:admin    更新时间:2022-06-22

      JSP开发应用是,中文乱码是个比较常见的问题,其根源是:Web容器默认的字符处理编码是ISO-8859-1。

实例一、JSP页面显示时

  1. <html> 
  2.     <head> 
  3.        <title>中文乱码——JSP页面显示时</title> 
  4.     </head> 
  5.     <body> 
  6.        <center> 
  7.            <br/> 
  8.            <h1>木兰辞拟古决绝词柬友</h1> 
  9.            <p>人生若只如初见,何事秋风悲画扇。</p> 
  10.        <p>等闲变却故人心,却道故人心易变。</p> 
  11.        <p>骊山语罢清宵半,泪雨霖铃终不怨。</p> 
  12.        <p>何如薄幸锦衣郎,比翼连枝当日愿。</p> 
  13.        </center> 
  14.     </body> 
  15. </html> 

运行结果:

解决方法:为其指定中文字符集,<html>前加入

  1. <%@ page contentType="text/html;charset=gb2312" %> 

实例二、JSP页面传递中文参数时

注册页面:

  1. <%@ page contentType="text/html;charset=gb2312" %> 
  2. <html> 
  3.     <head> 
  4.        <title>中文乱码——JSP页面传递中文参数时</title> 
  5.     </head> 
  6.     <body> 
  7.        <h2>申请账号:</h2> 
  8.        <form action="userMsg.jsp" method="POST"> 
  9.            <p>邮箱:&nbsp;<input type="text"name="email" id="email"/><p/> 
  10.            <p>昵称:&nbsp;<input type="text"name="nickname" id="nickname"/><p/> 
  11.  &n

bsp;         <p>密码:&nbsp;<input type="password"name="password" id="password"/><p/> 

  •            <p>性别:&nbsp;<input type="radio"name="sex" id="sex"value="男" /> 男  
  •                          <input type="radio" name="sex"id="sex" value="女" /> 女<p/> 
  •            <textarea  name="introduction"id="introduction" rows="5" cols="27">一句话介绍自己...</textarea> 
  •            <p><input type="submit"value="提交申请"></p> 
  •        </form> 
  •     </body> 
  • </html> 

个人信息页面:

  1. <%@ page contentType="text/html;charset=gb2312" %> 
  2. <html> 
  3.     <head> 
  4.        <title>中文乱码——JSP页面传递中文参数时 </title> 
  5.     </head> 
  6.     <body> 
  7.        <center> 
  8.            <h2>用户信息:</h2> 
  9.            <% String email = request.getParameter("email"); %> 
  10.            <% String nickname = request.getParameter("nickname"); %> 
  11.            <% String password = request.getParameter("password"); %> 
  12.            <% String sex = request.getParameter("sex"); %> 
  13.            <% String introduction = request.getParameter("introduction");%> 
  14.            <p>邮箱:&nbsp;<

;% out.print(email); %><p/> 

  •            <p>昵称:&nbsp;<% out.print(nickname); %><p/> 
  •            <p>密码:&nbsp;<% out.print(password); %><p/> 
  •            <p>性别:&nbsp;<% out.print(sex); %><p/> 
  •            <p>个人介绍:<%out.print(introduction); %></p> 
  •        </center> 
  •     </body> 
  • </html> 

运行结果:

解决方法:修改个人信息页面如下

  1. <%@ page contentType="text/html;charset=gb2312" %> 
  2. <html> 
  3.     <head> 
  4.        <title>中文乱码——JSP页面传递中文参数时 </title> 
  5.     </head> 
  6.     <body> 
  7.        <h2>用户信息:</h2> 
  8.        <%&nb