目前共有2篇帖子。 內容轉換:不轉換▼
 
點擊 回復
394 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)
 

本帖信息

點擊數:394 回複數:1
評論數: ?
作者: 巨大八爪鱼
最後回復:巨大八爪鱼
最後回復時間:2017-5-3 21:37
 
©2010-2024 Arslanbar Ver2.0
除非另有聲明,本站採用創用CC姓名標示-相同方式分享 3.0 Unported許可協議進行許可。