基于HttpServletResponse 相关常用方法的应用
public void filedownload(httpservletresponse response) throws exception {
servletcontext context = this.getservletcontext();
string path = context.getrealpath("/download/awf.jpg");
string filename = path.substring(path.lastindexof("\\") + 1);
// 如果下载文件为中文文件,则文件名需要经过url编码;
response.setheader("content-disposition", "attachment;filename="+ urlencoder.encode(filename, "utf-8"));
inputstream in = new fileinputstream(path);
int len = 0;
byte[] buffer = new byte[1024];
outputstream out = response.getoutputstream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
}
beanutils使用:
beanutils.pupulate(bean,mapinstance);//用map装载bean,map中存有bean属性对应的key以及key对应的值;
beanutils.copyproperties(bean,mapinstance);//将map拷贝到bean中;
转发是一次请求,使用的是相同的response和request;
页面跳转:
<1>string message = "<meta http-equiv='refresh' content='3;url=/webtwo/index.jsp'><a href='webtwo/index.jsp'>aaaa</a>";
this.getservletcontext().setattribute("message", message);
this.getservletcontext().getrequestdispatcher("/message.jsp").forward(request, response);//将消息带到message页面进行显示;
<2>response.setheader("refresh", "3;url='/webtwo/index.jsp'");
response.getwriter().write("恭喜登录成功,如果没有中转,请点击超链接<a href='webtwo/index.jsp'>aaaa</a>");
程序编码:
// 程序以什么码表输出,就一定要控制浏览器以什么码表打开;
// 用html中的meta技术模拟http响应头,来控制浏览器的行为;
// out.write("<meta http-equiv='content-type' content='text/html;charset=utf-8'>".getbytes());
response.setcharacterencoding("utf-8");// 设置response使用的码表,控制response以什么码表向浏览器写出数据;
response.setheader("content-type", "text/html;charset=utf-8");// 指定浏览器以什么码表打开数据;
// 相当上面两句话:
// response.setcontenttype("text/html;charset=utf-8");
response.setdateheader("expires",system.currenttimemillis() + 1000*3600);//设置session有效时间10分钟;
response.getwriter().write(data); response.getwriter() -- > return printwriter;
response.setheader("refresh","3");