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");