報getOutputStream() has already been called for this response 這個錯誤

           getOutputStream() has already been called for this response 這個錯誤遇到過不少次,網上看到大多不能解決問題。
              下面兩點是我自己總結出來的:
              1、在我們應用驗證碼時,都會用到字節流response.getOutputStream()來將驗證碼輸出,但是jsp頁面自己最后會調用字符流JspWriter的out()方法將頁面的內容輸出。通過查看servlet的API我們可以看到知道,在servlet中不能夠同時利用這兩個流輸出,解決辦法將驗證碼寫在servlet中,具體見下面。
              2、相信請求轉發( request.getRequestDispacher().forward() )和請求跳轉( response.sendRedirect() )的區別大家都知道。其中request.getRequestDispacher().forward() 方法的調用者與被調用者之間共享相同的request對象和response對象,它們屬于同一個訪問請求和響應過程。JSP頁面轉譯為的_servlet會最后調用releasePageContext()方法( All PageContext objects obtained via this method shall be released by invoking releasePageContext().)釋放我們頁面所有的實體對象,當我們的調用者有頁面輸出時,就會拋出這個異常。具體原因也沒有弄清楚,各位大俠如果誰知道可以告知一下。其實驗證碼也是同一個原理,如果我們將驗證碼的代碼寫在jsp頁面中,因為jsp頁面會調用JspWriter的out()方法將內容輸出,同時我們的圖片又調用了response.getOutputStream()方法因此會拋出這個異常;如果我們將驗證碼寫在servlet中,就不會同時使用兩種輸出也就不會出錯。有時即使調用者頁面沒有輸出,也會拋出這個異常,仔細看jsp轉譯以后的源碼發現輸出了換行,因此,我們最好把調用者頁面的%>和<%之間換行去掉,把%>和<%直接寫在一起。
              另外,如果我們實在要在jsp中用到response.getOutputStream(),比如驗證碼、jspSmartUpload,我們需要在最后加入如下代碼:
                  response.reset();
                  out.clear();
                  out=pageContext.pushBody();

          posted @ 2012-09-24 17:33 youngturk 閱讀(437) | 評論 (0)編輯 收藏

          excel文件下載,數據庫字段datafiled檢索--JS URL傳值給servlet亂碼

           

          1 //javascript里面加密兩次,兩次才可以的。2 var url = "servlet/getText?name=" + encodeURI(encodeURI(name));
          <script language="javascript" type="text/javascript">
                  function show()
                  {
                   var name="test";
                   var admin="ok";
                   var url = "http://localhost:7001/sosuo/ggld/fleet?reloadVessel=" 
                     + encodeURI(encodeURI(name))+"
          &reloadVoyage="+ encodeURI(encodeURI(admin));
                      window.open(url);
                  }
              
          </script>

          1 //在java里面,通過指定的編碼解密即可。2 String name = URLDecoder.decode(request.getParameter("name"),"utf-8");

          web.xml配置:
          <servlet> <!-- 新添加 車隊 download -->        <servlet-name>fleetDataDownload</servlet-name>        <servlet-class>com.cenin.util.FleetDataDownload</servlet-class>    </servlet>
          <servlet-mapping>        <servlet-name>fleetDataDownload</servlet-name>        <url-pattern>/ggld/fleet</url-pattern>    </servlet-mapping>

          DataDownload.java頁面:

          package com.cenin.util;


          import java.io.*;
          import javax.servlet.*;
          import javax.servlet.http.*;
          import java.net.*;
          import java.sql.*;

          import org.apache.commons.digester.Digester;
          import org.apache.log4j.Logger;
          import com.cenin.database.DBManager;



          public class DataDownload  extends HttpServlet 
          {
              private static   Logger logger = Logger.getLogger(DataDownload .class);
              
              public void init(ServletConfig config) throws ServletException 
              {
                  super.init(config);
                  try
                  {
                  }
                  catch(Exception ex)
                  {
                      logger.info(ex.getMessage());
                  }

              }
              public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException 
              {
                  doPost(request,response);
              }
              public void doDownload(HttpServletRequest request, HttpServletResponse response, String fileName, String vessel, String voyage)
              {
                  try
                  {
                      
                      response.reset();
                      response.setContentType("application/vnd.ms-excel");
                      response.setHeader("Content-Disposition", "inline; filename=\""+ fileName  + "\"");
                      ServletOutputStream sos = response.getOutputStream();
                      String title = "數據導出";


                      String[] fieldTitles = {"船名", "航次", "提單號", "箱號", "鉛封號", "箱型", "貨名", "重量", "體積", "發貨人", "收貨人", "裝貨港", "卸貨港"};
                      String[] fieldNames = {"szVessel", "szVoyage", "szBlNo", "szCtnNo", "szSealNo", "szCtnType", "szCargoName", "fWeight", "fVolume", "szReceiver", "szSender", "szLoadPortCode", "szDischargePortCode"};
                      int[] widths = {100, 50, 100, 120, 120, 50, 100, 50, 50, 80, 80, 80, 80};

                      Connection conn = DBManager.getInstance().getConnection();
                      Statement stmt=conn.createStatement(); 
                      String sql = "select * from NmhContainer where szVessel='" + 
                              vessel + "' and szVoyage='" + voyage + "'"; // and szBlNo='" + blno + "'";
                      ResultSet rs = stmt.executeQuery(sql);
                      OutputUtil.excelOutput(title, fieldTitles, fieldNames, widths, rs, sos, "ISO-8859-1", "GBK");
                      
                      DBManager.getInstance().freeDBResource(rs, stmt, conn);
                      
                  }
                  catch(Exception ex)
                  {
                      logger.info(ex.getMessage());
                  }
                  
              }
              public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              {
                  try
                  {
                      String vessel = request.getParameter("reloadVessel");
                      String voyage = request.getParameter("reloadVoyage");
                      //String blno = request.getParameter("reloadBlno");
                      String name = vessel + "_" + voyage + "_" + ".xls";
                      doDownload(request, response, name, vessel, voyage);
                      
                  }
                  catch(Exception ex)
                  {
                      logger.info(ex.getMessage());
                  }

                  
                  
              }
          }

          OutputUtil.java頁面:

          package com.cenin.util;
          /*
           * 輸出PDF, Excel等格式
           * 2005.5.12 by chenyong@cenin
           * 2005.12.19
           */


          import jxl.Workbook;
          import jxl.write.*;
          import com.lowagie.text.Document;
          import com.lowagie.text.Rectangle;
          import com.lowagie.text.Font;
          import com.lowagie.text.PageSize;
          import com.lowagie.text.HeaderFooter;
          import com.lowagie.text.Phrase;
          import com.lowagie.text.Element;
          import com.lowagie.text.Table;
          import com.lowagie.text.pdf.*;
          import java.io.*;
          import java.util.*;
          import java.sql.*;
          import org.apache.log4j.Logger;


          public class OutputUtil  
          {
              private static Logger logger = Logger.getLogger(OutputUtil.class);
              /*******************************************************
              * pdf輸出表格
              * title為pdf head
              * fieldtitles為 表頭項目名稱數組
              * filenames 為  對象屬性名數組
              * widths 為 寬度%數組
              * rs為resultset
              * os 為輸出流
              * codefrom , codeto 如果需要編碼轉換
              *******************************************************/    
              public static void excelOutput(String title, String[] fieldtitles, String[] fieldnames, int[] widths, ResultSet rs, OutputStream os, String codefrom, String codeto)
              {
                  
                  try
                  {
                      int fieldnumber = fieldnames.length; //, cellnumber = fieldnumber*5;
                      if(fieldnumber!=fieldtitles.length||fieldnumber!=fieldnames.length)
                          return;

                      WritableWorkbook workbook = Workbook.createWorkbook(os);
                      WritableSheet sheet = workbook.createSheet(title, 0);
                      
                      //add field title
                      for(int i=0;i
          <fieldnumber;i++)
                      {
                          //String temp 
          = new String(fieldtitles[i].getBytes(codefrom), codeto);
                          sheet.addCell(new Label(i, 0, fieldtitles[i]));
                          
                      }
                      //add values
                      int i
          =0;
                      
          while(rs.next())
                      {
                          for(int j
          =0; j<fieldnames.length; j++)
                          {
                              if(rs.getString(fieldnames[j])!
          =null)
                              
          {
                                  //String temp1 
          = rs.getString(fieldnames[j]);
                                  
          String temp = new String(rs.getString(fieldnames[j]).getBytes("ISO-8859-1"), "GBK");
                                  sheet.addCell(new Label(j, i+1, temp));
                              }
                              else
                                  sheet.addCell(new Label(j, i+1, ""));
                          }
                          i++;
                      }
                      //write to excel
                      workbook.write();
                      workbook.close();
                      
                  }
                  catch(Exception e)
                  {
                      logger.info(e.toString());
                  }
                      
              }

          }

          /*例子
          FileOutputStream os 
          = new FileOutputStream("e:\\a.xls");
          String[] titles 
          = {"系統編號","員工","用戶帳號"};
          String[] fieldnames = {"lsystemUserId","staff.szname","szaccount"};
          int[] widths = {20,20,20}; 
          //OutputUtil.pdfOutput("my pdf輸出", titles, fieldnames, widths,objectList,os);
          //OutputUtil.excelOutput("excel輸出", titles, fieldnames, widths,objectList,os);

          */

           

          posted @ 2012-09-20 17:04 youngturk 閱讀(457) | 評論 (0)編輯 收藏

          java創建文件和目錄

          創建文件和目錄的關鍵技術點如下:
              1、File類的createNewFile根據抽象路徑創建一個新的空文件,當抽象路徑制定的文件存在時,創建失敗
              2、File類的mkdir方法根據抽象路徑創建目錄
              3、File類的mkdirs方法根據抽象路徑創建目錄,包括創建必需但不存在的父目錄
              4、File類的createTempFile方法創建臨時文件,可以制定臨時文件的文件名前綴、后綴及文件所在的目錄,如果不指定目錄,則存放在系統的臨時文件夾下。
              5、除mkdirs方法外,以上方法在創建文件和目錄時,必須保證目標文件不存在,而且父目錄存在,否則會創建失敗
             
          實例演示

           

           

          package book.io;

          import java.io.File;
          import java.io.IOException;

          public class CreateFileUtil {
             
              public static boolean createFile(String destFileName) {
                  File file = new File(destFileName);
                  if(file.exists()) {
                      System.out.println("創建單個文件" + destFileName + "失敗,目標文件已存在!");
                      return false;
                  }
                  if (destFileName.endsWith(File.separator)) {
                      System.out.println("創建單個文件" + destFileName + "失敗,目標文件不能為目錄!");
                      return false;
                  }
                  //判斷目標文件所在的目錄是否存在
                  if(!file.getParentFile().exists()) {
                      //如果目標文件所在的目錄不存在,則創建父目錄
                      System.out.println("目標文件所在目錄不存在,準備創建它!");
                      if(!file.getParentFile().mkdirs()) {
                          System.out.println("創建目標文件所在目錄失敗!");
                          return false;
                      }
                  }
                  //創建目標文件
                  try {
                      if (file.createNewFile()) {
                          System.out.println("創建單個文件" + destFileName + "成功!");
                          return true;
                      } else {
                          System.out.println("創建單個文件" + destFileName + "失敗!");
                          return false;
                      }
                  } catch (IOException e) {
                      e.printStackTrace();
                      System.out.println("創建單個文件" + destFileName + "失敗!" + e.getMessage());
                      return false;
                  }
              }
             
             
              public static boolean createDir(String destDirName) {
                  File dir = new File(destDirName);
                  if (dir.exists()) {
                      System.out.println("創建目錄" + destDirName + "失敗,目標目錄已經存在");
                      return false;
                  }
                  if (!destDirName.endsWith(File.separator)) {
                      destDirName = destDirName + File.separator;
                  }
                  //創建目錄
                  if (dir.mkdirs()) {
                      System.out.println("創建目錄" + destDirName + "成功!");
                      return true;
                  } else {
                      System.out.println("創建目錄" + destDirName + "失敗!");
                      return false;
                  }
              }
             
             
              public static String createTempFile(String prefix, String suffix, String dirName) {
                  File tempFile = null;
                  if (dirName == null) {
                      try{
                          //在默認文件夾下創建臨時文件
                          tempFile = File.createTempFile(prefix, suffix);
                          //返回臨時文件的路徑
                          return tempFile.getCanonicalPath();
                      } catch (IOException e) {
                          e.printStackTrace();
                          System.out.println("創建臨時文件失敗!" + e.getMessage());
                          return null;
                      }
                  } else {
                      File dir = new File(dirName);
                      //如果臨時文件所在目錄不存在,首先創建
                      if (!dir.exists()) {
                          if (!CreateFileUtil.createDir(dirName)) {
                              System.out.println("創建臨時文件失敗,不能創建臨時文件所在的目錄!");
                              return null;
                          }
                      }
                      try {
                          //在指定目錄下創建臨時文件
                          tempFile = File.createTempFile(prefix, suffix, dir);
                          return tempFile.getCanonicalPath();
                      } catch (IOException e) {
                          e.printStackTrace();
                          System.out.println("創建臨時文件失敗!" + e.getMessage());
                          return null;
                      }
                  }
              }
             
              public static void main(String[] args) {
                  //創建目錄
                  String dirName = "D:/work/temp/temp0/temp1";
                  CreateFileUtil.createDir(dirName);
                  //創建文件
                  String fileName = dirName + "/temp2/tempFile.txt";
                  CreateFileUtil.createFile(fileName);
                  //創建臨時文件
                  String prefix = "temp";
                  String suffix = ".txt";
                  for (int i = 0; i 
          < 10; i++) {
                      System.out.println("創建了臨時文件:"
                              + CreateFileUtil.createTempFile(prefix, suffix, dirName));
                  }
                  //在默認目錄下創建臨時文件
                  for (int i 
          = 0; i < 10; i++) {
                      System.out.println("在默認目錄下創建了臨時文件:"
                              + CreateFileUtil.createTempFile(prefix, suffix, null));
                  }
              }

          }
          輸出結果:


          創建目錄D:/work/temp/temp0/temp1成功!
          目標文件所在目錄不存在,準備創建它!
          創建單個文件D:/work/temp/temp0/temp1/temp2/tempFile.txt成功!
          創建了臨時文件:D:work emp emp0 emp1 emp5171.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5172.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5173.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5174.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5175.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5176.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5177.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5178.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5179.txt
          創建了臨時文件:D:work emp emp0 emp1 emp5180.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5181.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5182.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5183.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5184.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5185.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5186.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5187.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5188.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5189.txt
          在默認目錄下創建了臨時文件:C:Documents and SettingsAdministratorLocal SettingsTemp emp5190.txt
          文章出處:http://www.diybl.com/course/3_program/java/javaxl/20071129/89522.html

          posted @ 2012-09-13 14:18 youngturk 閱讀(8829) | 評論 (0)編輯 收藏

          flex回調js,在主頁面html中添加,

          private function onLinkBtnClick(event:Event):void{
                          if(linkBtnClickLoad!=null && linkBtnClickLoad!=""){
                                 //CommonUtil.openWebPage(linkBtnClickLoad,null);
                                 //var urlRequest:URLRequest = new URLRequest(Setting.serverUrl+linkBtnClickLoad); 
                                 //navigateToURL(urlRequest,"_blank");
          //                       ExternalInterface.call("linkButtonOpen",Setting.serverUrl+linkBtnClickLoad);
                                 ExternalInterface.call("linkButtonOpen","http://localhost:7002/greatSpringCXFWebservice/"+linkBtnClickLoad);
                                 return;
          主頁面Html添加:
          <script  type="text/javascript">
               function linkButtonOpen(values){
                  window.open(values,'_blank','top=0,left=0,toolbar=no,menubar=no,resizable=yes,location=no,scrollbars=yes,status=no');
           }
           
          </script>
                          }
          ExternalInterface.addCallback("selectMenu",selectMenu);

          posted @ 2012-09-13 11:41 youngturk 閱讀(505) | 評論 (0)編輯 收藏

          對于復雜javabean到json串的轉換,建議使用FlexJSON

          http://fins.iteye.com/blog/253493

          posted @ 2012-09-12 17:22 youngturk 閱讀(361) | 評論 (0)編輯 收藏

          flex url http后臺傳遞參數方法

          request=new URLRequest("http://localhost:7002/greatSpringCXFWebservice/FileUploaded");
                          var variables:URLVariables = new URLVariables();
                          var userName = Setting.userInfo.userLoginName; 
                              variables.filedir = Setting.userInfo.userLoginName;
                              request.data=variables;
                               request.method=URLRequestMethod.GET;//為了后臺java創建用戶自己的圖片庫
          file.upload(req
          flex:
          file=new FileReference();
                          file.addEventListener(Event.SELECT,onFileSelect);
                          file.addEventListener(IOErrorEvent.IO_ERROR,onFileIOError);
                          file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadComplete);

          java:
           protected void processRequest(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException, IOException {
                  System.out.println("to upload picture !");
                  response.setContentType("text/html;charset=UTF-8");
                  PrintWriter out = response.getWriter();

                  // 保存文件到服務器中

                  DiskFileItemFactory factory = new DiskFileItemFactory();
                  factory.setSizeThreshold(4096);
                  ServletFileUpload upload = new ServletFileUpload(factory);
                  upload.setSizeMax(maxPostSize);
                  String filedir = request.getParameter("filedir");
                  try {
                      List fileItems = upload.parseRequest(request);
                      Iterator iter = fileItems.iterator();
                      while (iter.hasNext()) {
                          FileItem item = (FileItem) iter.next();
                          if (!item.isFormField()) {
                              String name = item.getName();
          //                    String filedir = item.get();//獲取文件名
                              System.out.println(name);
                              try {
                                  File file = new File("D:\\a\\"+filedir);//創建分級目錄
                                  file.mkdir();

                                  item.write(new File(uploadPath+filedir+"\\" + name));
                                  // SaveFile s = new SaveFile();
                                  // s.saveFile(name); "{\"path\": "[ {"name"}]}" 
                                  String path = "[path:{"+name+"}]";
                                  out.print(path);//用來返回flex的DataEvent.UPLOAD_COMPLETE_DATA請求
                                  
                                  out.close();

                              } catch (Exception e) {
                                  e.printStackTrace();
                                  out.print("{\"error\": "+name+"}");
                                  out.close();

                              }
                          }
                      }
                  } catch (FileUploadException e) {
                      out.print("{\"error\":"+e.getMessage()+"}");
                      out.close();
                      e.printStackTrace();
                      System.out.println(e.getMessage() + "結束");
                  }
              }
          uest);



          java接收

          posted @ 2012-09-12 14:16 youngturk 閱讀(980) | 評論 (0)編輯 收藏

          Flex 基于Http方式上傳圖片(轉)

               摘要: Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->首先下載 commons-fileupload-1.2.1.jar和commons-io-1.1.jar flex端代碼: <?xml version="1....  閱讀全文

          posted @ 2012-09-11 22:36 youngturk 閱讀(4113) | 評論 (0)編輯 收藏

          oracle 圖片存儲

          http://blog.csdn.net/qfs_v/article/details/2465276

          posted @ 2012-09-06 16:05 youngturk 閱讀(129) | 評論 (0)編輯 收藏

          java的反射應用 好文章

          http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html

          posted @ 2012-09-05 13:46 youngturk 閱讀(217) | 評論 (0)編輯 收藏

          oracle權限修改

          http://wenku.baidu.com/view/54431dc1bb4cf7ec4afed073.html###

          posted @ 2012-09-02 18:37 youngturk 閱讀(231) | 評論 (0)編輯 收藏

          僅列出標題
          共33頁: First 上一頁 8 9 10 11 12 13 14 15 16 下一頁 Last 
          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          導航

          統計

          公告

          this year :
          1 jQuery
          2 freemarker
          3 框架結構
          4 口語英語

          常用鏈接

          留言簿(6)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          相冊

          EJB學習

          Flex學習

          learn English

          oracle

          spring MVC web service

          SQL

          Struts

          生活保健

          解析文件

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 手游| 丰镇市| 濉溪县| 苗栗县| 广丰县| 曲周县| 民乐县| 华蓥市| 呼伦贝尔市| 鄱阳县| 秦皇岛市| 兴业县| 桃江县| 商河县| 尼勒克县| 平湖市| 凤庆县| 历史| 无锡市| 舟山市| 高青县| 临沭县| 宁远县| 内江市| 蓬溪县| 沁阳市| 伊川县| 乌兰察布市| 桃源县| 上饶市| 商南县| 江北区| 阿巴嘎旗| 静宁县| 五河县| 兴文县| 泽库县| 滕州市| 洛宁县| 柳江县| 宁强县|