目前共有2篇帖子。 字体大小:较小 - 100% (默认)▼  内容转换:港澳繁體▼
 
点击 回复
640 1
JSP獲取GB2312編碼的URL參數的方法
一派掌门 二十级
1楼 发表于:2017-5-3 21:26
<%@ page import="java.net.*" pageEncoding="gb2312" %><%
int num;
try {
    num = Integer.valueOf(request.getParameter("num"));
} catch (NumberFormatException e) {
    num = 0;
}
%><!doctype html>
<html>
<head>
<meta charset="gb2312">
<title>簡體中文網頁</title>
</head>

<body>
<p>Tomcat8中server.xml的&lt;Connector&gt;標籤下必須加上URIEncoding=&quot;ISO-8859-1&quot;, 否則將無法解析GB2312字符串!</p>
<p><%
String str = request.getParameter("value");
str = new String(str.getBytes("ISO-8859-1"), "gb2312");
out.print(str);
%></p>
<form id="form1" name="form1" method="get">
  <input name="value" type="text" id="value" value="<%= str %>">
  <input type="submit" value="確 定">
  <input name="num" type="hidden" id="num" value="<%= num + 1 %>">
</form>
<p><%
str = request.getQueryString();
str = URLDecoder.decode(str, "gb2312");
out.print(str);
%></p>
</body>
</html>
一派掌门 二十级
2楼 发表于:2017-5-3 21:37
【解決HTML標籤問題】
<%@ page import="java.net.*, org.apache.commons.lang3.*" pageEncoding="gb2312" %><%
int num;
try {
    num = Integer.valueOf(request.getParameter("num"));
} catch (NumberFormatException e) {
    num = 0;
}
%><!doctype html>
<html>
<head>
<meta charset="gb2312">
<title>簡體中文網頁</title>
</head>

<body>
<p>Tomcat8中server.xml的&lt;Connector&gt;標籤下必須加上URIEncoding=&quot;ISO-8859-1&quot;, 否則將無法解析GB2312字符串!</p>
<p><%
String str = request.getParameter("value");
str = new String(str.getBytes("ISO-8859-1"), "gb2312");
str = StringEscapeUtils.escapeHtml4(str); // HTML編碼
out.print(str);
%></p>
<form id="form1" name="form1" method="get">
  <input name="value" type="text" id="value" value="<%= str %>">
  <input type="submit" value="確 定">
  <input name="num" type="hidden" id="num" value="<%= num + 1 %>">
</form>
<p><%
str = request.getQueryString();
str = URLDecoder.decode(str, "gb2312");
str = StringEscapeUtils.escapeHtml4(str); // HTML編碼
out.print(str);
%></p>
</body>
</html>

需要在WEB-INF/lib/文件夾里放入commons-lang3-3.5.jar,下載地址是:
http://mirrors.hust.edu.cn/apache//commons/lang/binaries/commons-lang3-3.5-bin.tar.gz
該jar文件位於壓縮包內。

這樣當URL參數中含有HTML標籤時網頁也能正常顯示:
http://localhost:8080/test/get_encoding.jsp?value=%BC%F2%CC%E5%D6%D0%CE%C4%3Cscript%3E&num=10
 

回复帖子

内容:
用户名: 您目前是匿名发表
验证码:
(快捷键:Ctrl+Enter)
 

本帖信息

点击数:640 回复数:1
评论数: ?
作者:巨大八爪鱼
最后回复:巨大八爪鱼
最后回复时间:2017-5-3 21:37
 
©2010-2025 Purasbar Ver2.0
除非另有声明,本站采用知识共享署名-相同方式共享 3.0 Unported许可协议进行许可。