【发布时间】:2013-08-19 08:23:04
【问题描述】:
我正在尝试解码 servlet 中的编码字符串,但未正确解码。
但是当我尝试使用普通的 java 程序时,它工作正常。
我的代码如下......
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class testsetrv extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
String sd="நல்வரவு";
String s="%E0%AE%A4%E0%AE%95%E0%AE%B5%E0%AE%B2%E0%AF%8D%20%E0%AE%B5%E0%AF%86%E0%AE%B1%E0%AF%8D%E0%AE%B1%E0%AE%BF%E0%AE%95%E0%AE%B0%E0%AE%AE%E0%AE%BE%E0%AE%95%20%E0%AE%9A%E0%AF%87%E0%AE%B0%E0%AF%8D%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AE%A4%E0%AF%81";
try {
decode(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();}
}
public void decode(String a) throws UnsupportedEncodingException
{
String s=URLDecoder.decode(a, "UTF-8");
System.out.println(s);
}
public static void main(String a[]) throws UnsupportedEncodingException
{
String sd="நல்வரவு";
String s="%E0%AE%A4%E0%AE%95%E0%AE%B5%E0%AE%B2%E0%AF%8D%20%E0%AE%B5%E0%AF%86%E0%AE%B1%E0%AF%8D%E0%AE%B1%E0%AE%BF%E0%AE%95%E0%AE%B0%E0%AE%AE%E0%AE%BE%E0%AE%95%20%E0%AE%9A%E0%AF%87%E0%AE%B0%E0%AF%8D%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AE%A4%E0%AF%81";
testsetrv f=new testsetrv();
f.decode(s);
}
}
当我尝试使用 servlet 时,我得到了??????
当我运行 main 方法时,它会正确显示结果为 ....
தகவல் வெற்றிகரமாக சேர்க்கப்பட்டது
在我添加的 server.xml 中
URIEncoding="UTF-8" useBodyEncodingForURI="true"
我添加了一个过滤器来处理所有请求,如下所示
public class UTFFilter implements Filter
{
private String encoding;
public void init(FilterConfig config) throws ServletException
{
encoding = config.getInitParameter("requestEncoding");
if( encoding==null ) encoding="UTF-8";
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
throws IOException, ServletException
{
// Respect the client-specified character encoding
// (see HTTP specification section 3.4.1)
System.out.println("asdasgadsgasdgasdgasdgsadgasgasdgsdgsgdsgsdg");
if(null == request.getCharacterEncoding())
request.setCharacterEncoding(encoding);
/**
* Set the default response content type and encoding
*/
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
next.doFilter(request, response);
}
public void destroy(){}
}
还是不行
帮助 PLZ!!!!
【问题讨论】:
-
读取 UTF-8 数据是一回事,对字符串进行 URL 编码是另一回事。你指的是哪两个?换句话说,您如何从
sd内部的doGet()生成s的值? -
我已经手动使用编码程序生成了 s 值。
-
您是否在同一个控制台中检查输出?可能是当你单独运行它时,eclipse控制台正确显示UTF-8输出而Web服务器控制台输出不是?
-
是的,我认为你是对的。我正在寻找不同的控制台。你能告诉我如何设置 tomcat 控制台以打印 utf-8 流。
-
@PremAnanth,
System.getProperty("file.encoding")从 tomcat 中运行然后作为独立运行时的输出是什么?