用eclipse运行JSP实验2_1,所出现的汉字处理问题的总结
实验要求:
编写两个JSP页面,名字分别为inputName.jsp和people.jsp。
具体要求文字太多就不显示啦😽
书上给的实验代码:
inputName.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<html><body bgcolor=cyan><font size=3></font>
<form action="people.jsp" method=get name= form>
请输入名字:<input type="text" name="name">
<br><input type="submit" value="送出" name=submit>
</form>
</body></html>
people.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<html><body bgcolor=#90d7ec><font size=3>
<%!int count;
StringBuffer personList;
public void judge(){
if(count==0)
personList=new StringBuffer();
}
public void addPerson(String p){
if(count==0)
personList.append(p);
else
personList.append(","+p);
count++;
}
%>
<% String name=request.getParameter("name");
byte bb[]=name.getbytes("iso-8859-1");
name=new String(bb);
if(name.length()==0||name.length()>10){
%> <jsp:forward page="inputName.jsp"/>
<% }
judge();
addPerson(name);
%>
<br> 目前共有<%= count %>人浏览了该网页,他们的名字是:
<br><%= personList %>
</font></body></html>
将以上代码在eclipse中运行,输入文字,结果会变成乱码。运行截图如下:


在eclipse中运行时,
String name=request.getParameter(“name”);
byte bb[]=name.getbytes(“iso-8859-1”);
name=new String(bb);
这几行代码总是会报错,急得小A抓耳挠腮,让人头秃🤔😐😑😶🙄😫😱🤖(偷偷附上心路历程,别让其他人知道🤫)。
终于,功夫不负有心人😭,在小A的猛烈攻势下,这道题,也被我这该死的魅力😎折服了。
以下是攻略秘籍(勿外传🤫):
因为字母,数字的字符编码都是固定的,但汉字是后追加的,运行时才会出现乱码(个人理解,也欢迎大家把自己的理解打在评论区)。重新改用setCharacterEncoding方法,并将编码全改为utf-8。
即先将上面几行报错的代码改为:
request.setCharacterEncoding(“utf-8”);
String name=request.getParameter(“name”);
再将两个jsp文件的第一行
<%@ page contentType=“text/html; charset=gb2312” %>
改为
<%@ page contentType=“text/html; charset=utf-8” %>
然后重新运行,就成功啦。
附上改进后的代码:
inputName.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<html><body bgcolor=cyan><font size=3></font>
<form action="people.jsp" method=get name= form>
请输入名字:<input type="text" name="name">
<br><input type="submit" value="送出" name=submit>
</form>
</body></html>
people.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<html><body bgcolor=#90d7ec><font size=3>
<%!int count;
StringBuffer personList;
public void judge(){
if(count==0)
personList=new StringBuffer();
}
public void addPerson(String p){
if(count==0)
personList.append(p);
else
personList.append(","+p);
count++;
}
%>
<% request.setCharacterEncoding("utf-8");
String name=request.getParameter("name");
if(name.length()==0||name.length()>10){
%> <jsp:forward page="inputName.jsp"/>
<% }
judge();
addPerson(name);
%>
<br> 目前共有<%= count %>人浏览了该网页,他们的名字是:
<br><%= personList %>
</font></body></html>


成功运行,撒花🎉撒花🎉
本文记录了一位开发者在Eclipse中运行JSP实验时遇到的汉字乱码问题及其解决方案。实验涉及两个JSP页面(inputName.jsp和people.jsp),原本的代码使用gb2312编码导致汉字乱码。通过修改请求的字符编码为utf-8,并统一调整文件的charset属性为utf-8,成功解决了乱码问题。修复后的代码在Eclipse中正常运行,实现了预期功能。
576

被折叠的 条评论
为什么被折叠?



