??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲国产欧美一区,国产精品免费在线,91九色视频在线http://www.aygfsteel.com/WshmAndLily/category/10974.htmlzh-cnSun, 30 Dec 2007 01:47:59 GMTSun, 30 Dec 2007 01:47:59 GMT60用组件beanutils,dbutils化JDBC操作 http://www.aygfsteel.com/WshmAndLily/articles/171183.htmlsemovysemovyFri, 28 Dec 2007 06:33:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/171183.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/171183.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/171183.html#Feedback0http://www.aygfsteel.com/WshmAndLily/comments/commentRss/171183.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/171183.html    虽然现在出现?jin)很多ORM框架Q可是还是有很多朋友也许q在使用JDBCQ就像我现在一P除了(jin)学习(fn)的时候在使用Hibernate、SpringcMq些优秀的框Ӟ工作时一直都在用JDBC。本文就单介l一下利用Jakarta Commons旗下beanutils、dbutils化JDBC数据库操作,以抛砖引玉,希望对像我一样在使用JDBC的朋友有所帮助?/p>

    下面分两部分简单介lbeanutils、dbutils在基于JDBC API数据库存取操作中的运用。第一部分显介lbeanutils在JDBC数据库存取操作中的运用,W二部分介绍dbutils在JDBC数据库存取操作中的运用,最后看看他们的优缺点,谈谈本h在项目运用过E中对他们的一点心(j)得体?x),仅供参考,其中有错误的地方希望大虾不吝赐教Q大家多多交共同进步?/p>

    一、Jakarta Commons beanutils

    Beanutils是操作Bean的锐利武器,其提q的BeanUtils工具cd以简单方便的d或设|Bean的属性,利用DynapdQ还可以在运行期创徏BeanQ符合懒人的?fn)惯Q正如LazyDynaBeanQLazyDynaClass一P呵呵。这些用法已l有很多文章提及(qing)Q也可以参考apache的官Ҏ(gu)档?/p>

    对于直接利用JDBC API讉K数据库时Q这里针对的是返回结果集ResultSet的查询selectQ,大多数都是采用两U方式,一U是取出q回的结果集的数据存?sh)Map中,另一U方式是Bean里。针对第二种方式QBeanutils里提供了(jin)ResultSetDynaClassl合DynaBean以及(qing)RowSetDynaClassl合DynaBean来简化操作。下面用以个单的例子展示一下beanutils的这两个cdJDBC数据库操作中的运用?/p>

    请在本机建立数据库publishQ我用的是MySQLQ在publish数据库中建立表book,脚本如下Q?/p>

CREATE TABLE book(

  id int(11) NOT NULL auto_increment,

  title varchar(50) character set latin1 NOT NULL,

  authors varchar(50) character set latin1 default NULL,

  PRIMARY KEY  (id)


)

    然后用你喜欢的编辑器建立一个类BeanutilsJDBCTestQ我们先用ResultSetDynaClass来处理,然后再用RowSetDynaClass来实现同L(fng)c,之后看看他们之间有什么不同,用ResultSetDynaClass处理的源代码如下所C?

    然后用你喜欢的编辑器建立一个类BeanutilsJDBCTestQ我们先用ResultSetDynaClass来处理,然后再用RowSetDynaClass来实现同L(fng)c,之后看看他们之间有什么不同,用ResultSetDynaClass处理的源代码如下所C?

package cn.qtone.test;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.Iterator;

import org.apache.commons.beanutils.DynaBean;

import org.apache.commons.beanutils.PropertyUtils;

import org.apache.commons.beanutils.ResultSetDynaClass;

public class BeanutilsJDBCTest{

       public static void main(String[] args) {

              Connection con = null;

              Statement st = null;

              ResultSet rs = null;

              try {

                     Class.forName("com.mysql.jdbc.Driver");

                     String url = "jdbc:mysql://127.0.0.1:3306/publish?useUnicode=true&characterEncoding=GBK";

                     con = DriverManager.getConnection(url, "root", "hyys");

                     st = con.createStatement();

                     rs = st.executeQuery("select * from book");

                     ResultSetDynaClass rsDynaClass = new ResultSetDynaClass(rs);

                     Iterator itr = rsDynaClass.iterator();

                     System.out.println("title-------------authors");

                     while (itr.hasNext()) {

                            DynaBean dBean = (DynaBean) itr.next();

                            System.out.println(PropertyUtils.getSimpleProperty(dBean,"title")

                                          + "-------------"+ PropertyUtils.getSimpleProperty(dBean, "authors"));

                     }


              } catch (Exception e) {

                     e.printStackTrace();


              } finally {

                     try {

                            if (rs != null) {

                                   rs.close();

                            }

                            if (st != null) {

                                   st.close();

                            }

                            if (con != null) {

                                   con.close();

                            }


                     } catch (Exception e) {

                            e.printStackTrace();

                     }

              }

       }

}

    用RowSetDynaClass处理的源代码如下所C?

package cn.qtone.test;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.Iterator;

import java.util.List;

import org.apache.commons.beanutils.DynaBean;

import org.apache.commons.beanutils.PropertyUtils;

import org.apache.commons.beanutils.RowSetDynaClass;

public class BeanutilsJDBCTest{

       public static void main(String[] args) {

              List rsDynaClass = rsTest();

              System.out.println("title ------------- authors ");

              Iterator itr = rsDynaClass.iterator();

              while (itr.hasNext()) {

                     DynaBean dBean = (DynaBean) itr.next();

                     try {

                            System.out.println(PropertyUtils.getSimpleProperty(dBean,"name")

                                          + "-------------"+ PropertyUtils.getSimpleProperty(dBean, "mobile"));

                     } catch (Exception e) {

                            // TODO 自动生成 catch ?/p>

                            e.printStackTrace();

                    }


              }


       }


       private static List rsTest() {

              Connection con = null;

              Statement st = null;

              ResultSet rs = null;

              try {

                     Class.forName("com.mysql.jdbc.Driver");

                     String url = "jdbc:mysql://127.0.0.1:3306/publish?useUnicode=true&characterEncoding=GBK";

                     con = DriverManager.getConnection(url, "root", "hyys");

                     st = con.createStatement();

                     rs = st.executeQuery("select * from book");

                     RowSetDynaClass rsdc = new RowSetDynaClass(rs);

                     return rsdc.getRows();

              } catch (Exception e) {

                     e.printStackTrace();

              } finally {

                     try {

                            if (rs != null) {

                                   rs.close();

                            }

                            if (st != null) {

                                   st.close();

                            }

                            if (con != null) {

                                   con.close();

                            }

                     } catch (Exception e) {

                            e.printStackTrace();

                     }

              }


              return null;

       }

}

    q两个方法输出的l果应该是一L(fng)。但是很昄W二U方式比W一U方式要好,它把数据讉K部分抽取出来攑ֈ一个方法中Q显得简单清晰?/p>

    其实在利用ResultSetDynaClassӞ必须在ResultSet{数据库资源关闭之前Q处理好那些数据Q你不能在资源关闭之后用DynaBeanQ否则就?x)抛出异常,异常是说不能在ResultSet之后存取数据Q具体的异常名我也忘?sh)(jin)?j)Q当然你也可以采用以前的方式一个一个的把数据放到Map里,如果你一定要那样做,q是别用BeanutilsQ因没带l你什么好处。M利用ResultSetDynaClass你的E序的扩展性非帔R好?/p>

    从第二中方式可以看出Q利用RowSetDynaClass可以很好的解决上qResultSetDynaClass遇到的问题,RowSetDynaClass的getRows()Ҏ(gu)Q把每一行封装在一个DynaBean对象里,然后Q把说有的行攑ֈ一个List里,之后你就可以对返回的List里的每一个DynaBeanq行处理Q此外对于DynaBean你还可以采用标准的get/set方式处理Q当然你也可以用PropertyUtils. getSimpleProperty(Object bean, String name)q行处理?/p>

    从上面的分析中,你应该可以决定你应该使用ResultSetDynaClassq是RowSetDynaClass?jin)?/p>

    虽然现在出现?jin)很多ORM框架Q可是还是有很多朋友也许q在使用JDBCQ就像我现在一P除了(jin)学习(fn)的时候在使用Hibernate、SpringcMq些优秀的框Ӟ工作时一直都在用JDBC。本文就单介l一下利用Jakarta Commons旗下beanutils、dbutils化JDBC数据库操作,以抛砖引玉,希望对像我一样在使用JDBC的朋友有所帮助?/p>

    下面分两部分简单介lbeanutils、dbutils在基于JDBC API数据库存取操作中的运用。第一部分显介lbeanutils在JDBC数据库存取操作中的运用,W二部分介绍dbutils在JDBC数据库存取操作中的运用,最后看看他们的优缺点,谈谈本h在项目运用过E中对他们的一点心(j)得体?x),仅供参考,其中有错误的地方希望大虾不吝赐教Q大家多多交共同进步?/p>

    一、Jakarta Commons beanutils

    Beanutils是操作Bean的锐利武器,其提q的BeanUtils工具cd以简单方便的d或设|Bean的属性,利用DynapdQ还可以在运行期创徏BeanQ符合懒人的?fn)惯Q正如LazyDynaBeanQLazyDynaClass一P呵呵。这些用法已l有很多文章提及(qing)Q也可以参考apache的官Ҏ(gu)档?/p>

    对于直接利用JDBC API讉K数据库时Q这里针对的是返回结果集ResultSet的查询selectQ,大多数都是采用两U方式,一U是取出q回的结果集的数据存?sh)Map中,另一U方式是Bean里。针对第二种方式QBeanutils里提供了(jin)ResultSetDynaClassl合DynaBean以及(qing)RowSetDynaClassl合DynaBean来简化操作。下面用以个单的例子展示一下beanutils的这两个cdJDBC数据库操作中的运用?/p>

    请在本机建立数据库publishQ我用的是MySQLQ在publish数据库中建立表book,脚本如下Q?/p>

CREATE TABLE book(
  id int(11) NOT NULL auto_increment,
  title varchar(50) character set latin1 NOT NULL,
  authors varchar(50) character set latin1 default NULL,
  PRIMARY KEY  (id)
)

    然后用你喜欢的编辑器建立一个类BeanutilsJDBCTestQ我们先用ResultSetDynaClass来处理,然后再用RowSetDynaClass来实现同L(fng)c,之后看看他们之间有什么不同,用ResultSetDynaClass处理的源代码如下所C?

    然后用你喜欢的编辑器建立一个类BeanutilsJDBCTestQ我们先用ResultSetDynaClass来处理,然后再用RowSetDynaClass来实现同L(fng)c,之后看看他们之间有什么不同,用ResultSetDynaClass处理的源代码如下所C?

package cn.qtone.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.ResultSetDynaClass;
public class BeanutilsJDBCTest{
       public static void main(String[] args) {
              Connection con = null;
              Statement st = null;
              ResultSet rs = null;
              try {
                     Class.forName("com.mysql.jdbc.Driver");
                     String url = "jdbc:mysql://127.0.0.1:3306/publish?useUnicode=true&characterEncoding=GBK";
                     con = DriverManager.getConnection(url, "root", "hyys");
                     st = con.createStatement();
                     rs = st.executeQuery("select * from book");
                     ResultSetDynaClass rsDynaClass = new ResultSetDynaClass(rs);
                     Iterator itr = rsDynaClass.iterator();
                     System.out.println("title-------------authors");
                     while (itr.hasNext()) {
                            DynaBean dBean = (DynaBean) itr.next();
                            System.out.println(PropertyUtils.getSimpleProperty(dBean,"title")
                                          + "-------------"+ PropertyUtils.getSimpleProperty(dBean, "authors"));
                     }
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     try {
                            if (rs != null) {
                                   rs.close();
                            }
                            if (st != null) {
                                   st.close();
                            }
                            if (con != null) {
                                   con.close();
                            }
                     } catch (Exception e) {
                            e.printStackTrace();
                     }
              }
       }
}

    用RowSetDynaClass处理的源代码如下所C?

package cn.qtone.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.RowSetDynaClass;
public class BeanutilsJDBCTest{
       public static void main(String[] args) {
              List rsDynaClass = rsTest();
              System.out.println("title ------------- authors ");
              Iterator itr = rsDynaClass.iterator();
              while (itr.hasNext()) {
                     DynaBean dBean = (DynaBean) itr.next();
                     try {
                            System.out.println(PropertyUtils.getSimpleProperty(dBean,"name")
                                          + "-------------"+ PropertyUtils.getSimpleProperty(dBean, "mobile"));
                     } catch (Exception e) {
                            // TODO 自动生成 catch ?br />                             e.printStackTrace();
                     }
              }
       }
       private static List rsTest() {
              Connection con = null;
              Statement st = null;
              ResultSet rs = null;
              try {
                     Class.forName("com.mysql.jdbc.Driver");
                     String url = "jdbc:mysql://127.0.0.1:3306/publish?useUnicode=true&characterEncoding=GBK";
                     con = DriverManager.getConnection(url, "root", "hyys");
                     st = con.createStatement();
                     rs = st.executeQuery("select * from book");
                     RowSetDynaClass rsdc = new RowSetDynaClass(rs);
                     return rsdc.getRows();
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     try {
                            if (rs != null) {
                                   rs.close();
                            }
                            if (st != null) {
                                   st.close();
                            }
                            if (con != null) {
                                   con.close();
                            }
                     } catch (Exception e) {
                            e.printStackTrace();
                     }
              }
              return null;
       }
}

    q两个方法输出的l果应该是一L(fng)。但是很昄W二U方式比W一U方式要好,它把数据讉K部分抽取出来攑ֈ一个方法中Q显得简单清晰?/p>

    其实在利用ResultSetDynaClassӞ必须在ResultSet{数据库资源关闭之前Q处理好那些数据Q你不能在资源关闭之后用DynaBeanQ否则就?x)抛出异常,异常是说不能在ResultSet之后存取数据Q具体的异常名我也忘?sh)(jin)?j)Q当然你也可以采用以前的方式一个一个的把数据放到Map里,如果你一定要那样做,q是别用BeanutilsQ因没带l你什么好处。M利用ResultSetDynaClass你的E序的扩展性非帔R好?/p>

    从第二中方式可以看出Q利用RowSetDynaClass可以很好的解决上qResultSetDynaClass遇到的问题,RowSetDynaClass的getRows()Ҏ(gu)Q把每一行封装在一个DynaBean对象里,然后Q把说有的行攑ֈ一个List里,之后你就可以对返回的List里的每一个DynaBeanq行处理Q此外对于DynaBean你还可以采用标准的get/set方式处理Q当然你也可以用PropertyUtils. getSimpleProperty(Object bean, String name)q行处理?/p>

    从上面的分析中,你应该可以决定你应该使用ResultSetDynaClassq是RowSetDynaClass?jin)?/p>

    未完待箋(hu)……



semovy 2007-12-28 14:33 发表评论
]]>
struts中实现文件下?/title><link>http://www.aygfsteel.com/WshmAndLily/articles/134531.html</link><dc:creator>semovy</dc:creator><author>semovy</author><pubDate>Sun, 05 Aug 2007 10:06:00 GMT</pubDate><guid>http://www.aygfsteel.com/WshmAndLily/articles/134531.html</guid><wfw:comment>http://www.aygfsteel.com/WshmAndLily/comments/134531.html</wfw:comment><comments>http://www.aygfsteel.com/WshmAndLily/articles/134531.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/WshmAndLily/comments/commentRss/134531.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/WshmAndLily/services/trackbacks/134531.html</trackback:ping><description><![CDATA[<font size=2>struts中实现文件下载的主要代码Q?/font> <p><font size=2>public ActionForward execute(ActionMapping mapping, ActionForm form,<br>   HttpServletRequest request, HttpServletResponse response) {<br>  String strFileName = "试文g.rar";<br>  File file = new File("具体路径" + strFileName);//<br>  if(file.exists()){<br>   try{<br>    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));<br>    byte[] buffer = new byte[1024];<br>    strFileName = java.net.URLEncoder.encode(strFileName, "UTF-8");//处理中文文g名的问题<br>    strFileName = new String(strFileName.getBytes("UTF-8"),"GBK");//处理中文文g名的问题<br>    response.reset();<br>    response.setCharacterEncoding("UTF-8");<br>    response.setContentType("application/x-rar-compressed");//不同cd的文件对应不同的MIMEcd<br>    response.setHeader("Content-Disposition","attachment; filename=" + strFileName);<br>    OutputStream os = response.getOutputStream();<br>    while(bis.read(buffer) > 0){<br>     os.write(buffer);<br>    }<br>    bis.close();<br>    os.close();<br>   }<br>   catch(Exception e){<br>    ......<br>   }<br>  }<br>  return mapping.getInputForward();<br> }</font></p> <p><font size=2>在Struts中的实现和在ASP.NET的实现类|q段代码是服务器上的文g以流的方式发送到客户端浏览器Q如果要是在U打开的方式的话还应将response.setHeader("Content-Disposition","attachment; filename=" + strFileName);改写为response.setHeader("Content-Disposition","inline; filename=" + strFileName);</font></p> <img src ="http://www.aygfsteel.com/WshmAndLily/aggbug/134531.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/WshmAndLily/" target="_blank">semovy</a> 2007-08-05 18:06 <a href="http://www.aygfsteel.com/WshmAndLily/articles/134531.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>commons fileuploadhttp://www.aygfsteel.com/WshmAndLily/articles/133866.htmlsemovysemovyWed, 01 Aug 2007 13:08:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/133866.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/133866.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/133866.html#Feedback0http://www.aygfsteel.com/WshmAndLily/comments/commentRss/133866.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/133866.html 

jsp文g上传大多采用采用开源项目来化处理,q里列出常用的两个jar包的实现Qƈq行比较Q说明他们的优缺点和应该注意的问题?/p>

Commons FileUploadQ可以在http://jakarta.apache.org/commons/fileupload/下蝲Q这个包需要Commons IO的支持,可以?a >http://jakarta.apache.org/commons/io/下蝲

com.oreilly.servletQ可以在http://www.servlets.com/cos/下蝲
Commons FileUpload提供三种文g上传处理方式QDiskFileUpload、ServletFileUpload和PortletFileUpload三种方式Q其中DiskFileUpload已经在javadoc下已l被标记期的Ҏ(gu)Q徏议用ServletFileUpload代替Q而PortletFileUpload需要配合portlet-api来用,所以这里我们只介绍ServletFileUploadQƈ且这个也是最常用的?/p>

com.oreilly.servlet也提供了(jin)三种文g上传的处理方式,MultipartWrapper、MultipartRequest和MultipartParser三种方式Q其中MultipartWrapper和MultipartRequest的用法基本相同,q且没有MultipartRequest提供的操作多Q所以这里介lMultipartRequestQMultipartParser和前两者有些不同,可以用来处理某些Ҏ(gu)情况Q例如表单中有两个同名的文g上传选择框?/p>

我们暂时UC面三U文件上传方式分别ؓ(f)QServletFileUpload方式QMultipartTestServletQ、MultipartRequest方式QMultipartTestServlet2Q、MultipartParser方式QMultipartTestServlet3Q?/p>

代码如下Q?br /> test.html

<%@ page language="java" import="java.util.*" contentType="text/html;charset=gbk" pageEncoding="gbk"%>
<html>
   <body>
     <form action="MultipartTestServlet" enctype="multipart/form-data" method="post">
      <input type="text" name="username" /><br />
      <input type="file" name="myfile" /><br/>
      <input type="file" name="myfile" /><br/>
      <input type="submit" />
     </form>
     <br/><br/><br/><br/>
     <form action="MultipartTestServlet2" enctype="multipart/form-data" method="post">
      <input type="text" name="username" /><br />
      <input type="file" name="myfile" /><br/>
      <input type="file" name="myfile" /><br/>
      <input type="submit" />
     </form>
     <br/><br/><br/><br/>
     <form action="MultipartTestServlet3" enctype="multipart/form-data" method="post">
      <input type="text" name="username" /><br />
      <input type="file" name="myfile" /><br/>
      <input type="file" name="myfile" /><br/>
      <input type="submit" />
     </form>
   </body>
</html>
MultipartTestServlet.java

package com.bug.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

public class MultipartTestServlet extends HttpServlet {

public MultipartTestServlet() {
   super();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

   request.setCharacterEncoding("gbk");
   RequestContext requestContext = new ServletRequestContext(request);
  
   if(FileUpload.isMultipartContent(requestContext)){
   
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File("c:/tmp/"));
    ServletFileUpload upload = new ServletFileUpload(factory);
    //upload.setHeaderEncoding("gbk");
    upload.setSizeMax(2000000);
    List items = new ArrayList();
     try {
      items = upload.parseRequest(request);
     } catch (FileUploadException e1) {
      System.out.println("文g上传发生错误" + e1.getMessage());
     }

    Iterator it = items.iterator();
    while(it.hasNext()){
     FileItem fileItem = (FileItem) it.next();
     if(fileItem.isFormField()){      
      System.out.println(fileItem.getFieldName() + "    " + fileItem.getName() + "    " + new String(fileItem.getString().getBytes("iso8859-1"), "gbk"));
     }else{
      System.out.println(fileItem.getFieldName() + "    " +
         fileItem.getName() + "    " +
         fileItem.isInMemory() + "     " +
         fileItem.getContentType() + "    " +
         fileItem.getSize());
     
      if(fileItem.getName()!=null && fileItem.getSize()!=0){
       File fullFile = new File(fileItem.getName());
       File newFile = new File("c:/temp/" + fullFile.getName());
       try {
        fileItem.write(newFile);
       } catch (Exception e) {
        e.printStackTrace();
       }
      }else{
       System.out.println("文g没有选择 ?文g内容为空");
      }
     }
     
    }
   }
}

}

MultipartTestServlet2.java

package com.bug.servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class MultipartTestServlet2 extends HttpServlet {

public MultipartTestServlet2() {
   super();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

   //request.setCharacterEncoding("gbk");   不v作用
   System.out.println("start ");
   MultipartRequest multi = new MultipartRequest(request, "c:/tmp/", 2*1024*1024, "gbk", new DefaultFileRenamePolicy());
   System.out.println("start ");
   Enumeration filesName = multi.getFileNames();
   Enumeration paramsName = multi.getParameterNames();
   while(paramsName.hasMoreElements()){
    String paramName = (String) paramsName.nextElement();
    System.out.println(multi.getParameter(paramName));
   }
   while(filesName.hasMoreElements()){
    String fileName = (String) filesName.nextElement();
    System.out.println(multi.getFilesystemName(fileName) + "   " +
           multi.getOriginalFileName(fileName) + "   " +
           multi.getContentType(fileName) + "   ");
    if(multi.getFilesystemName(fileName)!=null && !multi.getFilesystemName(fileName).equals(""))
     System.out.println(multi.getFile(fileName).toURI());
   }
}

}

MultipartTestServlet3.java

package com.bug.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.ParamPart;
import com.oreilly.servlet.multipart.Part;

public class MultipartTestServlet3 extends HttpServlet {

public MultipartTestServlet3() {
   super();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

       MultipartParser mp = new MultipartParser(request, 2*1024*1024, false, false, "gbk");
       Part part;
       while ((part = mp.readNextPart()) != null) {
         String name = part.getName();
         if (part.isParam()) {
           ParamPart paramPart = (ParamPart) part;
           String value = paramPart.getStringValue();
           System.out.println("param: name=" + name + "; value=" + value);
         }
         else if (part.isFile()) {
           // it's a file part
           FilePart filePart = (FilePart) part;
           String fileName = filePart.getFileName();
           if (fileName != null) {
             long size = filePart.writeTo(new File("c:/tmp/"));
             System.out.println("file: name=" + name + "; fileName=" + fileName +
               ", filePath=" + filePart.getFilePath() +
               ", contentType=" + filePart.getContentType() +
               ", size=" + size);
           }
           else {
            System.out.println("file: name=" + name + "; EMPTY");
           }
           System.out.flush();
         }
       }
     }

}

web.xml中加?/p>

<servlet>
     <servlet-name>MultipartTestServlet</servlet-name>
     <servlet-class>com.bug.servlet.MultipartTestServlet</servlet-class>
   </servlet>
   <servlet>
     <servlet-name>MultipartTestServlet2</servlet-name>
     <servlet-class>com.bug.servlet.MultipartTestServlet2</servlet-class>
   </servlet>
   <servlet>
     <servlet-name>MultipartTestServlet3</servlet-name>
     <servlet-class>com.bug.servlet.MultipartTestServlet3</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>MultipartTestServlet</servlet-name>
     <url-pattern>/MultipartTestServlet</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
     <servlet-name>MultipartTestServlet2</servlet-name>
     <url-pattern>/MultipartTestServlet2</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
     <servlet-name>MultipartTestServlet3</servlet-name>
     <url-pattern>/MultipartTestServlet3</url-pattern>
   </servlet-mapping>

我用q第一个例子的:

<!--注意:

1.当利用ServletUpload?lt;input type="radio" checked="checked">的元素会(x)被认为是文g元素<input type="file"> 
从而会(x)被解析出几个IFile出来

2.当用在struts的action?action的name不要讄,否则解析不出文g控g存在.因ؓ(f)actionform之前被解析掉?
-->

问题1、中文问题:(x)
三种凡是都可以通过自己的方法来讄encoding为gbk开处理和解决中文问题,包括初始化的时候传入gbk作ؓ(f)参数Q或是是初始化后通过setEncoding的方式来实现?br /> 另外ServletFileUpload方式也可以通过request.setCharacterEncoding("gbk");的方式来实现Q而其它两U方式不支持q种方式?/p>


问题2、文件大限?br /> ServletFileUpload方式可以讄文g大小限制Q也可以不用讄Q例子中的upload.setSizeMax(2000000)可以注释掉。如果设|upload.setSizeMax(-1)Q表明不限制上传的大。文档中没有指明默认的限制的多少Q我在不讄的情况下上传?jin)一?M的东西,可以上传Q估计默认是不限制大的?br /> 而MultipartRequest方式和MultipartParser方式是必设|文件的上传文g的大限制的Q如果不讄Q默认是1M的大限制?/p>


问题3、文件上传发生错?br /> 如果文g上传q程中发生Q何错误,或者是文g的大超Z(jin)范围Q系l都抛出错误?br /> ServletFileUpload方式在upload.parseRequest(request)时抛出错?br /> MultipartRequest方式在new MultipartRequest(。。?时抛出错?br /> MultipartParser方式在new MultipartParser(。。?时抛出错?/p>


问题4、上传同名文件时Q他们保存到临时目录是的冲突问题
ServletFileUpload方式Q不?x)有冲突Q系l会(x)把上传得文g按照一定的规则重新命名Q保证不?x)冲H?br /> MultipartParser方式Q会(x)产生冲突Q系l会(x)把文件按照上传时的文件名Q保存到临时目录下,如果两个用会(x)同时上传文g名相同的文gQ那么就可能?x)生冲H,一Ҏ(gu)另一方的临时文gl替换了(jin)?br /> MultipartRequest方式Q在初始化时如果提供?jin)一个名U{换策略,׃?x)有冲突Q如果不提桶Q就?x)有冲突。在上面的例子中我们提供?jin)一个new DefaultFileRenamePolicy()保证?jin)文件名不?x)有冲H发生?/p>


问题5Q表单中有两个同名的文g上传选择框,像我们例子中的myfile一P每个表单中有两个name=“myfile”的上传框
ServletFileUpload方式Q可以处理,可以分别得到他们各自的文Ӟ
MultipartRequest方式Q不可以处理Q会(x)发生冲突Q会(x)有一个上传框的文件覆盖了(jin)另外一个?br /> MultipartParser方式Q可以处理,可以分别得到他们各自的文Ӟ


备注Q?br /> 代码比较乱,主要是ؓ(f)?jin)说明他们间的区别。他们的详细C用说明还是要参考他的javadoc和domo?/p>

参考:(x)
1?a >http://www.servlets.com/cos/#classes
2?a >http://jakarta.apache.org/commons/fileupload/apidocs/index.html
3?a >http://jakarta.apache.org/commons/fileupload/using.html
4?a >http://www.onjava.com/pub/a/onjava/2003/06/25/commons.html?page=3



semovy 2007-08-01 21:08 发表评论
]]>
ajax struts 动态多文g上传http://www.aygfsteel.com/WshmAndLily/articles/133251.htmlsemovysemovyMon, 30 Jul 2007 02:01:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/133251.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/133251.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/133251.html#Feedback1http://www.aygfsteel.com/WshmAndLily/comments/commentRss/133251.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/133251.htmlindex.jsp:

<%@ page language="java" pageEncoding="gbk"%>

<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html>
<head>
<title>
multiUploadDemo
</title>
</head>
<script language="javascript">
   var num = 0;
 
 function upload(){
  document.getElementById("status").innerHTML = "文g上传?..";
     multiUploadForm.submit();
   }

function additem(id)
{
 var row,cell,str;
 row = eval("document.all["+'"'+id+'"'+"]").insertRow();
 if(row != null )
    {
       cell = row.insertCell();
       str="<input type="+'"'+"file"+'"'+" name=uploadFile["+ num +"].file><input type="+'"'+"button"+'"'+" value="+'"'+"删除"+'"'+" onclick='deleteitem(this,"+'"'+"tb"+'"'+");'>"
      cell.innerHTML=str;
    }
 num++;
}
function deleteitem(obj,id)
{
 var rowNum,curRow;
 curRow = obj.parentNode.parentNode;
 rowNum = eval("document.all."+id).rows.length - 1;
 eval("document.all["+'"'+id+'"'+"]").deleteRow(curRow.rowIndex);
}
function callback(msg)
{
 document.getElementById("status").innerHTML = "文g上传完成...<br>" + msg;
}
</script>
<body bgcolor="#ffffff">
<div id="status"></div>
<html:form method="post" action="/multiUpload.do" enctype="multipart/form-data" target="hidden_frame">

<table id="tb">
</table>

</html:form>
<iframe name='hidden_frame' id="hidden_frame" style="display:none"></iframe>
<input type="button" name="btnAddFile" value="Add File" onclick="additem('tb')"/>
<input type="button" name="btnUpload" value="upload" onclick="upload()"/>
</body>
</html:html>

Struts config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "

<struts-config>
  <data-sources />
  <form-beans >
    <form-bean name="multiUploadForm" type="com.yourcompany.struts.MultiUploadForm" />

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      attribute="multiUploadForm"
      name="multiUploadForm"
      path="/multiUpload"
      scope="request"
      type="com.yourcompany.struts.MultiUploadAction"
      validate="false" />

  </action-mappings>

  <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>

Form bean:  MultiUploadForm.java


package com.yourcompany.struts;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts.action.ActionForm;

public class MultiUploadForm extends ActionForm {
 private  List  myFiles; 
    public  MultiUploadForm(){ 
            myFiles  =  new  ArrayList(); 
            //Z(jin)能够在页面初始显CZ个file 
            myFiles.add(new  UploadFile()); 
    } 
    public  List  getMyFiles()  { 
            return  myFiles; 
    }         

//注意q个Ҏ(gu)的定?nbsp;

  public  UploadFile  getUploadFile(int  index){ 
            int  size  =  myFiles.size(); 
            if(index>size-1){ 
                    myFiles.add(new  UploadFile()); 
            } 
            return  (UploadFile)myFiles.get(index); 
    } 
    public  void  setMyFiles(List  myFiles)  { 
            this.myFiles  =  myFiles; 
    } 

}


ActionBean :MultiUploadAction.java

package com.yourcompany.struts;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class MultiUploadAction extends Action {
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  MultiUploadForm multiUploadForm = (MultiUploadForm) form;
  List myFiles = multiUploadForm.getMyFiles();
  String fileStr = "";
  for (int i = 0; i < myFiles.size(); i++) {
   UploadFile uploadFile = (UploadFile) myFiles.get(i);
   FormFile file = uploadFile.getFile();

   if (file == null) {
    System.out.println("file  is  null");
   } else {

    // 能运行到q里Q就可以使用单个文g上传的方法进行上传了(jin)。@环而已
    System.out.println("filename:::" + file.getFileName());
    System.out.println("file  size:::" + file.getFileSize());
    fileStr += "filename:::" + file.getFileName() + "file  size:::" + file.getFileSize() ;
     
   }
  }
  //q回文本
  try
  {
   response.setHeader("ContentType", "text/html;charset=gbk");
   PrintWriter out = response.getWriter();
   out.write("<script>parent.callback('upload file success" + fileStr + "')</script>");
  }catch(IOException e)
  {
   e.printStackTrace();
  }

  return null;
 }

}


Bean: UploadFile.java

package com.yourcompany.struts;

import java.io.Serializable;

import org.apache.struts.upload.FormFile;

public class UploadFile implements Serializable {
  private  FormFile  file; 
     public  FormFile  getFile()  { 
             System.out.println("run  in  uploadFile.getFile()"); 
             return  file; 
     } 
     public  void  setFile(FormFile  file)  { 
             this.file  =  file; 
     } 
}



semovy 2007-07-30 10:01 发表评论
]]>
ajax struts url streamhttp://www.aygfsteel.com/WshmAndLily/articles/128059.htmlsemovysemovyWed, 04 Jul 2007 03:54:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/128059.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/128059.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/128059.html#Feedback0http://www.aygfsteel.com/WshmAndLily/comments/commentRss/128059.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/128059.htmlpublic class Example7Action extends Action {


  public ActionForward execute(ActionMapping mapping, ActionForm inForm, HttpServletRequest request, HttpServletResponse response) throws Exception {

    String feedURL = (String)request.getParameter("feedURL");

    if (feedURL == null || feedURL.equalsIgnoreCase("")) {
      return null; // Trivial error handling... if no URL sent in, essentially do nothing
    }
    feedURL = new URLCodec().decode(feedURL);

    // Go get the feed
    StringBuffer xml = new StringBuffer(4096);
    try {
      URL               u   = new URL(feedURL);
      InputStream       in  = u.openStream();
      InputStreamReader isr = new InputStreamReader(in);
      BufferedReader    br  = new BufferedReader(isr);
      String theLine;
      while ((theLine = br.readLine()) != null) {
        xml.append(theLine);
      }
    } catch (Exception e) {
      System.err.println("Example7Action Exception: " + e);
    }

    // Write the XML to response
    response.setContentType("text/xml");
    PrintWriter out = response.getWriter();
    out.println(xml);
    out.flush();

    return null;

  } // End execute()


}



semovy 2007-07-04 11:54 发表评论
]]>
Struts实现动态(不定数量Q多个文件上传[转蝲]http://www.aygfsteel.com/WshmAndLily/articles/114083.htmlsemovysemovyFri, 27 Apr 2007 06:52:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/114083.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/114083.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/114083.html#Feedback0http://www.aygfsteel.com/WshmAndLily/comments/commentRss/114083.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/114083.html主要代码如下  
 
Form部分Q? 
 
public  class  MultiUploadForm  extends  ActionForm  {  
       private  List  myFiles;  
       public  MultiUploadForm(){  
               myFiles  =  new  ArrayList();  
               //Z(jin)能够在页面初始显CZ个file  
               myFiles.add(new  UploadFile());  
       }  
       public  List  getMyFiles()  {  
               return  myFiles;  
       }          
 
   //注意q个Ҏ(gu)的定? 
 
     public  UploadFile  getUploadFile(int  index){  
               int  size  =  myFiles.size();  
               if(index>size-1){  
                       myFiles.add(new  UploadFile());  
               }  
               return  (UploadFile)myFiles.get(index);  
       }  
       public  void  setMyFiles(List  myFiles)  {  
               this.myFiles  =  myFiles;  
       }  
}  
 
Dataset部分Q? 
public  class  UploadFile  implements  Serializable  {  
       private  FormFile  file;  
       public  FormFile  getFile()  {  
               System.out.println("run  in  uploadFile.getFile()");  
               return  file;  
       }  
       public  void  setFile(FormFile  file)  {  
               this.file  =  file;  
       }  
}  
Action部分Q? 
public  class  MultiUploadAction  extends  Action  {  
       public  ActionForward  execute(ActionMapping  mapping,  ActionForm  form,  
                                                                 HttpServletRequest  request,  
                                                                 HttpServletResponse  response)  {  
               MultiUploadForm  multiUploadForm  =  (MultiUploadForm)  form;  
               List  myFiles  =  multiUploadForm.getMyFiles();  
               for(int  i  =0;i<myFiles.size();i++){  
                       UploadFile  uploadFile  =  (UploadFile)myFiles.get(i);  
                       FormFile  file  =  uploadFile.getFile();  
 
                       if(file==null){  
                               System.out.println("file  is  null");  
                       }  
                       else{  
 
                               //能运行到q里Q就可以使用单个文g上传的方法进行上传了(jin)。@环而已  
                               System.out.println("filename:::"  +  file.getFileName());  
                               System.out.println("file  size:::"  +  file.getFileSize());  
                       }  
               }  
 
               return  null;  
       }  
}  
 
JSP部分Q? 
 
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-nested.tld" prefix="nested" %>

<html:html>
<head>
<title>
multiUploadDemo
</title>
</head>
<script language="javascript" type="">
   var num = 0;
 
 function upload(){
     multiUploadForm.submit();
   }

function additem(id)
{
 var row,cell,str;
 row = eval("document.all["+'"'+id+'"'+"]").insertRow();
 if(row != null )
    {
       cell = row.insertCell();
       str="<input type="+'"'+"file"+'"'+" name=uploadFile["+ num +"].file><input type="+'"'+"button"+'"'+" value="+'"'+"删除"+'"'+" onclick='deleteitem(this,"+'"'+"tb"+'"'+");'>"
      cell.innerHTML=str;
    }
 num++;
}
function deleteitem(obj,id)
{
 var rowNum,curRow;
 curRow = obj.parentNode.parentNode;
 rowNum = eval("document.all."+id).rows.length - 1;
 eval("document.all["+'"'+id+'"'+"]").deleteRow(curRow.rowIndex);
}

</script>
<body bgcolor="#ffffff">
<html:form method="post" action="/multiUploadAction.do" enctype="multipart/form-data">

<table id="tb">
</table>

</html:form>
<input type="button" name="btnAddFile" value="Add File" onclick="additem('tb')"/>
<input type="button" name="btnUpload" value="upload" onclick="upload()"/>
</body>
</html:html> 
 struts-config.xml部分Q? 
 
   <form-beans>  
       <form-bean  name="multiUploadForm"  type="MultiUploadForm"  />  
   </form-beans>  
 
<action  name="multiUploadForm"  path="/multiUploadAction"  type="MultiUploadAction"  />  
 
以上只是对动态多文g上传部分q行?jin)描qͼ只是一个Demo。大家可以根据自q需求变通的调整一下?nbsp; 



semovy 2007-04-27 14:52 发表评论
]]>
logic:equal,logic:present用法http://www.aygfsteel.com/WshmAndLily/articles/96727.htmlsemovysemovyTue, 30 Jan 2007 06:23:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/96727.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/96727.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/96727.html#Feedback0http://www.aygfsteel.com/WshmAndLily/comments/commentRss/96727.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/96727.html<logic:equal (tng)name="DeliverProveForm" (tng)property="userAction" (tng)value="create">
如果DeliverProveForm里的属性userAction的值等于create执行这ѝ?br /></logic:equal>

2.
<logic:present (tng)name="tipmsg">
如果在你的action中设|了(jin)tipmsg执行到q儿。如Qrequest.setAttribute("tipmsg","提示信息")或session.setAttribute("tipmsg","提示信息")
<bean:write (tng)name="tipmsg"/>
</logic:present> (tng)

semovy 2007-01-30 14:23 发表评论
]]>
StrutsFileDownload-----DownloadActionhttp://www.aygfsteel.com/WshmAndLily/articles/91528.htmlsemovysemovyWed, 03 Jan 2007 06:05:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/91528.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/91528.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/91528.html#Feedback0http://www.aygfsteel.com/WshmAndLily/comments/commentRss/91528.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/91528.html StrutsFileDownload

A new DownloadAction was added in Struts 1.2.6 (see the [WWW] JavaDoc). This page is to show how to use it and has the following structure:

  1. Implementing a DownloadAction
    1. Implement the getStreamInfo() Method
    2. Implement the getBufferSize() Method
  2. Examples
    1. FileStreamInfo Example
    2. ResourceStreamInfo Example
    3. Byte Array Example
  3. Using the DownloadAction in your Web Pages
  4. Content Disposition
    1. Setting the Content Disposition
    2. Content Disposition Values

(!) FrankZ: Here is the sample webapp... downloadapp.zip Please note that this is my first ever attempt at editing a Wiki entry, so if I screwed anything up, I apologize in advance! Lastly, I skimmed through the content of this entry and didn't see anything blatantly wrong. I will try and proof it more thoroughly as time allows, but for now, in addition to the sample app, it should get anyone going in the right direction.

<!> niallp: Since I haven't actually used this class myself, I'm hoping that Martin, Frank or anyone else involved in the discussion/creation of this would take a look here to see if its OK.

(!) Details from this thread: [WWW] Mail Archive - Note that the link to the sample app at omnytex.com referenced in this thread is no longer valid. The sample app is attached to this Wiki page only, so download it from here downloadapp.zip

Implementing a DownloadAction

You need to extend org.apache.struts.actions.DownloadAction and implement the getStreamInfo() method. Optionally you can also override the getBufferSize() method if you require a different buffer size from the default.

Implement the getStreamInfo() Method

The getStreamInfo() method returns a StreamInfo object - which is an inner interface of the DownloadAction. The DownloadAction provides two concrete implementations (static inner classes) of the StreamInfo interface:

  • FileStreamInfo - Simplifies downloading of a file from disk - need to pass a java.io.File object to the constructor along with the content type.

  • ResourceStreamInfo - simplifies downloading of a web application resource - need to pass the ServletContext, path and content type to its constructor.

In the examples below, I have also provided a Byte array implementation of the StreamInfo interface.

Implement the getBufferSize() Method

The DownloadAction, by default, returns a buffer size of 4096. Optionally, this may be overriden to customize the size of the buffer used to transfer the file.

Examples

Below are three examples:

  • using a File

  • using a web application resource

  • using a byte array.

FileStreamInfo Example

Example of using the DownloadAction with a file. This example picks up the file name from the parameter attribute in the strust-config.xml action mapping.

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;

public class ExampleFileDownload extends DownloadAction{

    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {
        
        // Download a "pdf" file - gets the file name from the
        // Action Mapping's parameter
        String contentType = "application/pdf";
        File file          = new File(mapping.getParameter());

        return new FileStreamInfo(contentType, file);
        
    }

}

ResourceStreamInfo Example

Example of using the DownloadAction with a web application resource. This example picks up the web application resource path from the parameter attribute in the strust-config.xml action mapping.

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;

public class ExampleResourceDownload extends DownloadAction {

    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {
        
        // Download a "jpeg" file - gets the file name from the
        // Action Mapping's parameter
        String contentType         = "image/jpeg";
        String path                = mapping.getParameter();
        ServletContext application = servlet.getServletContext();
        
        
        return new ResourceStreamInfo(contentType, application, path);
        
    }

}


Byte Array Example

Example of using the DownloadAction with a Byte Array.

This example creates a ByteArrayStreamInfo inner class which implements the StreamInfo interface.

(niallp: IMO we should include this ByteArrayStreamInfo in the implementation)

import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;

public class ExampleByteArrayDownload extends DownloadAction {

    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {
        
        // Download a "pdf" file
        String contentType = "application/pdf";
        byte[] myPdfBytes  = null;              // Get the bytes from somewhere

        return new ByteArrayStreamInfo(contentType, myPdfBytes);
        
    }

    protected class ByteArrayStreamInfo implements StreamInfo {
        
        protected String contentType;
        protected byte[] bytes;
        
        public ByteArrayStreamInfo(String contentType, byte[] bytes) {
            this.contentType = contentType;
            this.bytes = bytes;
        }
        
        public String getContentType() {
            return contentType;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(bytes);
        }
    }
}

Using the DownloadAction in your Web Pages

The last bit of the puzzle is how do I use this action?

You need to do two things:

  • As with any Struts action, you need to configure it in the struts-config.xml

  • Use it on your web page like any other link to a file

So for example you might have something like the following in your struts-config.xml:

    <action path="/downloadMyPdfFile" type="myPackage.ExampleFileDownload" parameter="/foo/bar.pdf">
    <action path="/downloadMyImage"   type="myPackage.ExampleResourceDownload" parameter="/images/myImage.jpeg">

The on your jsp page, you might use these in the following way:

    <html:img action="downloadMyImage" alt="My Image" height="400" width="400"/>

    <html:link action="downloadMyPdfFile">Click Here to See the PDF</html:link>

Note you may need to set the nocache value to false in the controller section of your struts config file. Nocache set to true prevented me from being able to use Internet Explorer to download the file succesfully; Firefox and Safari worked fine.

    <controller contentType="text/html;charset=UTF-8" locale="true" nocache="false" />

Content Disposition

Setting the Content Disposition

DownloadAction doesn't cater for setting the content dispositon header. The easiest way is set it in the getStreamInfo() method, for example...

public class ExampleFileDownload extends DownloadAction{


    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {

        // File Name
        String fileName = mapping.getParameter();

        // Set the content disposition
        response.setHeader("Content-disposition", 
                           "attachment; filename=" + fileName);
        
        // Download a "pdf" file - gets the file name from the
        // Action Mapping's parameter
        String contentType = "application/pdf";
        File file          = new File(fileName);

        return new FileStreamInfo(contentType, file);
        
    }
}

Probably would want to play with the file name, to remove any path info first.

Content Disposition Values

You can set the content disposition to either download the file or open up in the browser:

  • To open up in the browser: "inline; filename=myFile.pdf"

  • To download: "attachment; filename=myFile.pdf"

Displaying images I always set the content disposition to the "inline" option.

NOTE: I'm not expert at this, just got it working by trial and error. I had problems and I'm seem to remember I had to play with setting the response headers to get it to work properly. There may also be browser issues - my app only has to work with IE. Anyone who knows more about this, feel free to amend this page.

FIX for IE: Content-Disposition Attachment Header Does Not Save File [WWW] link

last edited 2006-01-25 18:40:18 by WendySmoak



semovy 2007-01-03 14:05 发表评论
]]>
struts+MySQL实现囄的存储与昄http://www.aygfsteel.com/WshmAndLily/articles/88347.htmlsemovysemovySun, 17 Dec 2006 08:30:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/88347.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/88347.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/88347.html#Feedback0http://www.aygfsteel.com/WshmAndLily/comments/commentRss/88347.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/88347.html K K 功能设计Q?/span> <img> 实现步骤Q?/span>

struts struts-1.2.8-src web/examples/ upload JSP ActionForm Action upload.jsp <html:form action="/UploadSubmit" enctype="multipart/form-data"> (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) 请选择需要上传的照片 :

 (tng) (tng) (tng) (tng) <html:file property="theFile"/>

 (tng) (tng) (tng) (tng) <html:submit value=" 上传 "/> (tng) (tng) (tng) (tng) (tng)

</html:form>

ActionForm getter setter public class UploadForm extends ActionForm {

 (tng) (tng) (tng) protected FormFile theFile;

 (tng) (tng) (tng) public FormFile getTheFile() {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) return theFile;

 (tng) (tng) (tng) }

 (tng) (tng) (tng) public void setTheFile(FormFile theFile) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) this.theFile = theFile;

 (tng) (tng) (tng) }

}

theFile String boolean org.apache.struts.upload.FormFile HTTP FormFile FormFile J Action Action public ActionForward execute(ActionMapping mapping,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) ActionForm form,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) HttpServletRequest request,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) HttpServletResponse response)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) throws Exception {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) if (form instanceof UploadForm) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) UploadForm theForm = (UploadForm) form;

 (tng) (tng) (tng) (tng) (tng)  (tng) (tng) (tng) (tng) (tng) (tng) //

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) FormFile file = theForm.getTheFile();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) String filename= file.getFileName();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) HttpSession session = request.getSession();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) String path = session.getServletContext().getRealPath("/") + "temp\\" + filename;

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) try {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) InputStream stream = file.getInputStream();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) OutputStream bos = new FileOutputStream(path);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) int bytesRead = 0;

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) byte[] buffer = new byte[8192];

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) bos.write(buffer, 0, bytesRead);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) bos.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.info("The file has been written to \""

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)  (tng) + path + "\"");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //  (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) session.setAttribute("imageuploaded","true");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) session.setAttribute("filename",filename);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) // close the stream

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) stream.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) bos.flush();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) bos.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }catch (FileNotFoundException fnfe) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) return null;

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }catch (IOException ioe) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) return null;

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //destroy the temporary file created

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) file.destroy();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) return mapping.findForward("next");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) (tng)  (tng) (tng)//this shouldn't happen in this example

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) return null;

 (tng) (tng) (tng) }

temp <img src=”?gt; struts upload struts-config.xml ActionForm Action <form-bean name="uploadForm"

 (tng)type="org.apache.struts.webapp.upload.UploadForm"/>

<action input="/pages/hr/error.jsp" name="uploadForm"

 (tng)  (tng) (tng) (tng) (tng) (tng) (tng) (tng) path="/UploadSubmit" scope="request"

type="org.apache.struts.webapp.upload.UploadAction" validate="true">

 (tng) (tng) <forward name="next" path="/pages/hr/input.jsp"/>

</action>

<controller maxFileSize="2M" inputForward="true" />

<action> validate true theFile controller ?st1:chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="2" unitname="m">2M?/span> ActionForm validate /**

 (tng) (tng) (tng) (tng) * Check to make sure the client hasn't exceeded the maximum allowed upload size inside of this validate method.

**/

 (tng) (tng) (tng) public ActionErrors validate(ActionMapping mapping,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) HttpServletRequest request) { (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) ActionErrors errors = null;

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) //has the maximum length been exceeded?

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) Boolean maxLengthExceeded =

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (Boolean) request.getAttribute(

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED); (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) errors = new ActionErrors();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) errors.add(

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) ActionMessages.GLOBAL_MESSAGE ,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) new ActionMessage("maxLengthExceeded"));

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) errors.add(

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) ActionMessages.GLOBAL_MESSAGE ,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) new ActionMessage("maxLengthExplanation"));

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) return errors;

 (tng) (tng) (tng) }

hook controller theFile request scope Validate Action MySQL MEDIUMBLOB BLOB 216-1 64K MEDIUMBLOB 224-1 16M /**

 (tng)*  (tng)* @param id  (tng)* @param path  (tng)* @return

 (tng)*/

public static void saveImage(int id, String path) throws SQLException{

 (tng) (tng) (tng) (tng) String time = new java.util.Date().toString();

 (tng) (tng) (tng) (tng) Connection conn = null;

 (tng) (tng) (tng) (tng) PreparedStatement pstmt = null;

 (tng) (tng) (tng) (tng) boolean flag = false;

 (tng) (tng) (tng) (tng) //  (tng) (tng) (tng) (tng) try {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) conn = DbManager.getConnection();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.info(time + ":saveImage() DbManager ");

 (tng) (tng) (tng) (tng) } catch (SQLException e) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) // DbManager  (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.error(time + ": saveImage() ");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) throw new SQLException(":saveImage() ");

 (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //  (tng) (tng) (tng) (tng) try {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) pstmt = conn.prepareStatement("UPDATE hr01 SET hr01_photo=? where hr01_id=?");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) FileInputStream in = new FileInputStream(path);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) pstmt.setBinaryStream(1,in,in.available());

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) pstmt.setInt(2,id); (tng) (tng) (tng) (tng)  (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) pstmt.executeUpdate();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) pstmt.executeUpdate("COMMIT");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.info(" " + path + " ");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) flag = true; (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) }catch(IOException e){

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.error(" " + path + " ");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) throw new SQLException(" ");

 (tng) (tng) (tng) (tng) }catch (SQLException ex) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.error(new java.util.Date() + "Error:Insert into table."

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) + ex.getMessage()); (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.error(" " + path +" .");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) throw new SQLException(" " + path +" .");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) } finally {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) try {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) pstmt.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) conn.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.info("DbHrinfo saveImage() closed the connection created at " + time);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) } catch (SQLException e) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) }
> (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) //  (tng) (tng) (tng) (tng) if(flag == true){

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) File file = new File(path);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) if(file.exists()){

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) file.delete();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) }

}

pstmt.executeUpdate("COMMIT"); SQL SQL textpad COMMIT SQL <img src=”?gt; AlterImageAction session public ActionForward execute(ActionMapping mapping,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) ActionForm form,HttpServletRequest request,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) HttpServletResponse response)

throws IOException,ServletException{

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) HttpSession session = request.getSession();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) //1.  (tng) (tng) (tng) (tng) String filename = (String)session.getAttribute("filename");

 (tng) (tng) (tng) (tng) String path = session.getServletContext().getRealPath("/")

+ "temp\\" + filename;

 (tng) (tng) (tng) (tng) File file = new File(path);

 (tng) (tng) (tng) (tng) if(file.exists()){

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) file.delete();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.info(" " + path + " ");

 (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) //2. session  (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) session.removeAttribute("imageuploaded");

 (tng) (tng) (tng) (tng) session.removeAttribute("filename"); (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) return mapping.findForward("next"); (tng) (tng) (tng) (tng)

}

ShowImageAction public ActionForward execute(ActionMapping mapping,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) ActionForm form, HttpServletRequest request,

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) HttpServletResponse response)

throws IOException,ServletException{

 (tng) (tng) (tng) (tng) //  (tng) (tng) (tng) (tng) if (!DbManager.hasSetDataSource()) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) javax.sql.DataSource dataSource;

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) try {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) dataSource = getDataSource(request);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) DbManager.setDataSource(dataSource);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) } catch (Exception e) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.error(e.getMessage());

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) mapping.findForward("error");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) String photo_no = request.getParameter("photo_no");

 (tng) (tng) (tng) (tng) Connection conn = null;

 (tng) (tng) (tng) (tng) Statement stmt = null;

 (tng) (tng) (tng) (tng) //  (tng) (tng) (tng) (tng) try {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) conn = DbManager.getConnection();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.info("showimage.jsp DbManager ");

 (tng) (tng) (tng) (tng) } catch (SQLException e) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) // DbManager  (tng) (tng) (tng) (tng) (tng) (tng) (tng) logger.error(" showimage.jsp ");

 (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) try {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) //  (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) stmt = conn.createStatement();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) String sql = " SELECT hr01_photo FROM hr01 WHERE hr01_id='" + photo_no + "'";

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) ResultSet rs = stmt.executeQuery(sql);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) if (rs.next()) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) InputStream in = rs.getBinaryStream("hr01_photo");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) int bytesRead = 0;

byte[] buffer = new byte[8192];

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) response.setContentType("image/jpeg");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) response.setContentLength(in.available());

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) OutputStream outs = response.getOutputStream();

 (tng) (tng) (tng) (tng)  (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) outs.write(buffer, 0, bytesRead);

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) outs.flush();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) in.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) rs.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) } else {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) rs.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) response.sendRedirect("error.jsp");

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) }catch(SQLException e){

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) }finally {

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) try{

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) stmt.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) conn.close();

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }catch(SQLException ex){

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng)

 (tng) (tng) (tng) (tng) (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) }

 (tng) (tng) (tng) (tng) return null;

}

execute response redirect session response image/jpeg null JSP <image> Action struts-config.xml Action <action path="/ShowImage"

 (tng)type="software.action.ShowImageAction"></action>

JSP Action :

<img src="/tibet/ShowImage.do?photo_no=666542">


< p>

semovy 2006-12-17 16:30 发表评论
]]>
html:messages与html:errorshttp://www.aygfsteel.com/WshmAndLily/articles/82531.htmlsemovysemovyTue, 21 Nov 2006 06:33:00 GMThttp://www.aygfsteel.com/WshmAndLily/articles/82531.htmlhttp://www.aygfsteel.com/WshmAndLily/comments/82531.htmlhttp://www.aygfsteel.com/WshmAndLily/articles/82531.html#Feedback0http://www.aygfsteel.com/WshmAndLily/comments/commentRss/82531.htmlhttp://www.aygfsteel.com/WshmAndLily/services/trackbacks/82531.html 1. ?/strong>  (tng) (tng) (tng) (tng)
 (tng) (tng) (tng) <html:messages> 标签?<html:errors> 标签有些怼之处, 也能够在|页上输出消? 不过两者的使用Ҏ(gu)有些差别.
2. 实例
 (tng) (tng) (tng) <html:messages id="message" message="true">
 (tng) (tng) (tng) (tng) (tng) (tng) (tng) <bean:write name="message"/>
 (tng) (tng) (tng) </html:messages>

3. 属?/font>
(1) name: 指定ActionMessages 对象存放?request ?session 范围内的属?key(即上面实例中的message). 标签处理cdҎ(gu)q一属性key 来检索request ?session 范围?ActionMessages 对象.

(2) message: 指定消息的来? 如果为true , 则从request ?session 范围内检索出属?key?Globals.MESSAGE_KEY ?ActionMessages 对象, 此时 name 属性无? 如果为false ,则根据name 属性来(g)索ActionMessages 对象, 如果此时没有讄name 属? 采用默认值Globals.ERROR_KEY. message 属性的默认gؓ(f)false.
(3) id: 用来命名从消息集合中(g)索出的每?ActionMessage 对象, 它和<bean:write>标签的name 属性匹? 在上例中, <html:messages> 标签的处理类每次从消息集合中取出一?ActionMessages 对象, 把它命名ؓ(f) "message", <bean:write> 标签接着把这个名?message" 的ActionMessage 对象的消息输出到|页?
4. 创徏ActionMessages 集合, 存入request ?/strong>
 (tng) (tng) (tng) ActionMessages actionMessages = new ActionMessages();
 (tng) (tng) (tng) actionMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("record.inserted"));
 (tng) (tng) (tng) saveMessages(request, actionMessages);



semovy 2006-11-21 14:33 发表评论
]]>
վ֩ģ壺 ˮ| | ɽ| | | | | | | | ֲ| Զ| | | ˳| | ƶ| ƽ| | | | | IJ| ƽ| ˮ| Ϫ| ƽ| | Ȫ| ƽ| ͩ| | | | | | ¹| | Ϫ| | |