日期:2014-05-16  浏览次数:20348 次

JSP 字符串编码转换的实现
charset.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="html/css">
<!--
.STYLE1{
      font-size:large;
}
-->
</style>
<script>
function convertToUTF8(){
form1.action="changeUTF-8.jsp";
form1.submit();
}
function convertToISO(){
form1.action="changeISO.jsp";
form1.submit();
}
function convertToGBK(){
form1.action="changeGBK.jsp";
form1.submit();
}
</script>
</head>
<body>
<form name="form1" action="" method="post">
<div class="STYLE1">请输入一串字符</div>
<input type="text" name="str"/>
<hr />
<input type="button" value="转成UTF-8" onclick="convertToUTF8"/>
<input type="button" value="转成ISO-8859-1" onclick="convertToISO"/>
<input type="button" value="转成GBK" onclick="convertToGBK"/>
</form>
</body>
</html>


changeGBK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//设置request对象的字符串编码集为"gb2312"
//以正确的字符编码读入
request.setCharacterEncoding("UTF-8");
String input=request.getParameter("str");
%>
<p>您输入的字符串:<font color="red"><%=input %></font>的GBK编码在ASCII编码下的表示为:</p>
<font size="5">
<%
String gbk=new String(input.getBytes(),"GBK");
for(int i=0;i<gbk.length();i++){
      out.println(gbk.charAt(i));
}
  %>
  </font>
</body>
</html>



changeISO.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//设置request对象的字符串编码集为"gb2312"
//以正确的字符编码读入
request.setCharacterEncoding("UTF-8");
String input=request.getParameter("str");
%>
<p>您输入的字符串:<font color="red"><%=input %></font>的ISO-8859-1编码在ASCII编码下的表示为:</p>
<font size="5">
<%
String gbk=new String(input.getBytes(),"ISO-8859-1");
for(int i=0;i<gbk.length();i++){
      out.println(gbk.charAt(i));
}
  %>
  </font>
</body>
</html>


changeUTF-8.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//设置request对象的字符串编码集为"gb2312"
//以正确的字符编码读入
request.setCharacterEncoding("UTF-8");
String input=request.getParameter("str");