问题一:
下面这两段代码差别不大,为何test1结果不同:
代码1:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
test(response);
test1(response);
} //这样写会乱码,返回两个? 原因是外国人默认用ISO8859码表,当数据存到response中时,ISO8859中没有汉字对应的码表,所以返回?所以解决乱码的关键在于码表的更换,
public void test(HttpServletResponse response) throws IOException{
String data = "中国";
PrintWriter out = response.getWriter();
out.write(data); }
//解决test里面的乱码问题
public void test1(HttpServletResponse response) throws IOException{
//设置response用的码表是UTF-8,以控制response以什么码表像浏览器写出数据
response.setCharacterEncoding("UTF-8");
//因为浏览器默认GB2312,所以现在必须控制浏览器打开数据的码表为UTF-8
response.setHeader("content-type","text/html;charset=UTF-8");
String data = "中国";
PrintWriter out = response.getWriter();
out.write(data);
}
代码2:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//test(response);
test1(response);
} //这样写会乱码,返回两个? 原因是外国人默认用ISO8859码表,当数据存到response中时,ISO8859中没有汉字对应的码表,所以返回?所以解决乱码的关键在于码表的更换,
public void test(HttpServletResponse response) throws IOException{
String data = "中国";
PrintWriter out = response.getWriter();
out.write(data); }
//解决test里面的乱码问题
public void test1(HttpServletResponse response) throws IOException{
//设置response用的码表是UTF-8,以控制response以什么码表像浏览器写出数据
response.setCharacterEncoding("UTF-8");
//因为浏览器默认GB2312,所以现在必须控制浏览器打开数据的码表为UTF-8
response.setHeader("content-type","text/html;charset=UTF-8");
String data = "中国";
PrintWriter out = response.getWriter();
out.write(data);
}
两段代码区别在于:第一段test和test1方法同时调用,输出结果是????
第二段只调用了test1方法,结果输出 “中国”
为什么?????
问题二:
下列代码,想从浏览器访问对应位置的图片,为什么总显示NullPointException
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、先设置浏览器要以什么方式打开
response.setHeader("Content-type","image/jpeg");
//2、再把目标文件加载成一个输入流 输入流才有读的方法 F://10.jpg这样写是错误的
InputStream in = this.getServletContext().getResourceAsStream("F://10.jpg");
//3、定义字符数组长度的中间变量
int len = 0;
//4、定义一个字符数组
byte by[] = new byte[1024];
//5、先定义好一个输出到浏览器的流
//6、把输入流里的东西读入到字符数组中
OutputStream out = response.getOutputStream();
while((len = (in.read(by)))!=-1){ out.write(by,0,len);
out.flush();
}
out.close();
in.close();
}
当把”F://10.jpg”改成“10.jpg”就对了???是不能指定图片所在路径吗?(F盘下有10.jpg,web应用下也有10.jpg)