url,sendRedirect当中有中文
3.url,sendRedirect当中有中文
中文当想出现在url当中,或通过网络http header或request的parameter或response传送时,得需要变成iso格式传送,到目的地后,再用GBK转换一下,人才能看懂。
例 1.3.1
jsp5.jsp:
<%@ page contentType="text/html; charset=GBK" %>
<html>
<body>
<h1>
<a href="MarkToWinServlet?name=马克-to-win">ok</a>
<a href="show.jsp?name=马克-to-win">ok</a>
</h1>
<form action="MarkToWinServlet" method="POST">
<input type="submit"/>
</form>
</body>
</html>
package com;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
// out.println("马克-to-win");
String str="马克-to-win";
/* you can use the following either one to encode.
str.getBytes("GBK"),用GBK方式把字符串变成数组,
public static String encode(String s,String enc) : Translates a string into
application/x-www-form-urlencoded format using a specific encoding scheme.
*/
// str=java.net.URLEncoder.encode(str,"GBK");
/* 中文当想出现在url当中,或通过网络传送时,得需要变成iso格式传送,URLEncoder方法的用意和下面一模一样,只不过地址栏里人眼看不懂, 其他都一样。这里不能变成UTF-8,也许我们机器缺省是GBK,所以eclipse用GBK等。*/
str = new String(str.getBytes("GBK"), "iso-8859-1");
response.sendRedirect("home.jsp?username="+str);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
/*中文当想出现在url当中,或通过网络传送时,得需要变成iso格式传送,*/
String str = request.getParameter("name");
System.out.println(str);
if(str != null){
try {
str = new String(str.getBytes("ISO-8859-1"), "GBK");
System.out.println(str);
/*下句话不能少, 否则response不是中文*/
response.setContentType(CONTENT_TYPE);
response.getWriter().println("response STR"+str);
}
catch (UnsupportedEncodingException ex) {
}
}
}
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44638460/article/details/104157305
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义