作者共发了2篇帖子。 内容转换:不转换▼
 
点击 回复
415 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)
 

本帖信息

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