Hiscoder

HisCoder

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::

      首先得说这是一件非常细致的工作。造成耽误这么长时间都是因为一些细节的问题。废话少说,切入正题。

      主要遇见了一下几个问题。

      第一,在使用spring对Struts2Action进行管理的时候,怎么也访问不到Action类,最后发现在application.xml中配置包路径的时候多了用一个字符。

  applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
           <context:annotation-config></context:annotation-config>
           <context:component-scan base-package="com.medvision"></context:component-scan>
           
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
       <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" value="jdbc:oracle:thin:@10.10.9.204:1521:oracle"/>
    <property name="username" value="qustion"/>
    <property name="password" value="tianjian"/>
     <!-- 连接池启动时的初始值 -->
     <property name="initialSize" value="1"/>
     <!-- 连接池的最大值 -->
     <property name="maxActive" value="500"/>
     <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
     <property name="maxIdle" value="2"/>
     <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
     <property name="minIdle" value="1"/>
        
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation"
            value="classpath:hibernate.cfg.xml">
        </property>
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
          <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction-manager="txManager"/>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
    
    

第二个问题,在Struts的Acton中获取的uploadFileName总是为空。因为项目的文件太多,每次启动tomcat都会花费很长的时间,于是我就又新建了一个一个项目,使用原来的类库,很郁闷的是,如果加上spring框架,就会出现错。如果,不加上Spring框架,然后就不会这个问题。曾经一度认为,是Spring接管Struts的Action的时候出现了问题。所以,就一直在查找这方面的原因,后来发现是第一个错误导致了这种原因。解决后,例子程序能够正常运行,但是,项目还是不能够达到预期的效果。换了类库 ,重新 建了Acton尝试了很多方法都不行。最后发现时Extjs的错误。在form中必须fileUpload 属性和uploadfile属性设为true.这样问题 解决了。

 

下面就总结一下吧,需要注意的几个地方:

在Action中必须有三个属性 File  *filename,*contentType

在Struts中必须配置相应的拦截器。

第三前台一定要有两个属性。

 

upload.js

Ext.onReady(function() {

    var fileForm = new Ext.form.FormPanel({
        title : "",
        renderTo : "fileUpload",
        fileUpload : true,
        layout : "table",
        id : "fileUploadForm",
        uploadfile:true,

        items:[
            {
            xtype:'panel',
            frame:true,
            width:700,
            height:500,
            layout:'form',
            items:[{
            name:'id',
            hidden:true
                },{
                    xtype:'textfield',
                    name:'deptName',
                    fieldLabel:'科室名称'
                },{
                    xtype:'textfield',
                    name:'deptCode',
                    fieldLabel:'科室编码'
                }]
        },{
            xtype:'panel',
            layout:'form',
            width:450,
            height:500,
            frame:true,
            items:[{
                    id : 'upload',
                    name : 'upload',
                    inputType : "file",
                    fieldLabel : '上传图片',
                    xtype : 'textfield',
                    anchor : '40%'

                }, {

                    xtype : 'box',
                    id : 'browseImage',
                    fieldLabel : "预览图片",
                    autoEl : {
                        width : 300,
                        height : 350,
                        tag : 'img',
                        // type : 'image',
                        src : Ext.BLANK_IMAGE_URL,
                        style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);',
                        complete : 'off',
                        id : 'imageBrowse'
                    }

                }]
        }],
                listeners : {
            'render' : function(f) {
                //
                this.form.findField('upload').on('render', function() {
                    //通過change事件
                    Ext.get('upload').on('change',
                            function(field, newValue, oldValue) {

                                var url = getPath(Ext.get('upload').dom);
                                // alert("url = " + url);
                                if (img_reg.test(url)) {

                                    if (Ext.isIE) {
                                        
                                        var image = Ext.get('imageBrowse').dom;
                                        image.src = Ext.BLANK_IMAGE_URL;// 覆盖原来的图片
                                        image.filters
                                                .item("DXImageTransform.Microsoft.AlphaImageLoader").src = url;

                                    }// 支持FF
                                    else {
                                        Ext.get('imageBrowse').dom.src = Ext
                                                .get('upload').dom.files
                                                .item(0).getAsDataURL()
                                    }
                                }
                            }, this);
                }, this);
            }
        }
,        buttons : [{
                    text : "提交",
                    name : "submit",
                    handler : submit
                }]
    });

    var img_reg = /\.([jJ][pP][gG]){1}$|\.([jJ][pP][eE][gG]){1}$|\.([gG][iI][fF]){1}$|\.([pP][nN][gG]){1}$|\.([bB][mM][pP]){1}$/

});


function submit() {
    Ext.getCmp("fileUploadForm").getForm().submit({

                url : "uploadAction.action",
                method : "POST",
                success : function(form, action) {
                    alert("success");
                },
                failure : function(form, action) {
                    alert("failure");
                }
            });
}



   function getPath(obj)  
    {  
     if(obj)  
    {  
        if (window.navigator.userAgent.indexOf("MSIE")>=1)  
        {  
          obj.select();  
      return document.selection.createRange().text;  
          }  
        else if(window.navigator.userAgent.indexOf("Firefox")>=1)  
          {  
         if(obj.files)  
           {  
           return obj.files.item(0).getAsDataURL();  
     }  
       return obj.value;  
    }  
  return obj.value;  
     }  
    }  

upload.action

package com.medvision;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;

@Component("upload")
@Scope("prototype")
public class UploadAction extends ActionSupport {

    /**  
   *   
   */
    private UploadAction(){
        System.out.println("I was created !");
    }
    private static final long serialVersionUID = 1L;
    private File upload;
    private String uploadContentType;

    private String uploadFileName; // fileName 前面必須和uplaod一致,不然找不到文件
    private String comon;
    private String deptName ;
    private String deptCode ;
    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public String getDeptCode() {
        return deptCode;
    }

    public void setDeptCode(String deptCode) {
        this.deptCode = deptCode;
    }

    public String getComon() {
        return comon;
    }

    public void setComon(String comon) {
        this.comon = comon;
    }
    @Resource
    private test t ;

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    // 上传文件的文件名

    private String getFileExp(String name) {
        int pos = name.lastIndexOf(".");

        return name.substring(pos);
    }

    private static final int BUFFER_SIZE = 16 * 1024;

    public String execute() throws Exception {
        System.out.println("excute was called ");
        try{
            t.sayHello();
        }catch(Exception e){
            e.printStackTrace();
        }
        Date d = new Date();
        System.out.println(this.getComon()+"deptName:"+this.getDeptCode()+"deptCode:"+this.getDeptCode());

        System.out.println("uploadFileName = " + this.uploadFileName);

        // upload -- wapps 下面的文件夹,用来存放图片
        String toSrc = ServletActionContext.getServletContext().getRealPath(
                "upload")
                + "/" + d.getTime() + getFileExp(this.uploadFileName); // 使用時間戳作為文件名

        System.out.println("toFile= " + toSrc);

        File toFile = new File(toSrc);
        writeFile(this.upload, toFile);

        return SUCCESS;
    }

    private static void writeFile(File src, File dst) {

        System.out.println(" == 文件寫入 == ");
        try {
            InputStream in = null;
            OutputStream out = null;
            try {

                in = new BufferedInputStream(new FileInputStream(src),
                        BUFFER_SIZE);
                out = new BufferedOutputStream(new FileOutputStream(dst),
                        BUFFER_SIZE);
                byte[] buffer = new byte[BUFFER_SIZE];
                while (in.read(buffer) > 0) {
                    out.write(buffer);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<include file="struts-default.xml" />
<constant name="struts.objectFactory.spring.autoWire" value="type" />
<constant name="struts.multipart.saveDir" value="/tmp"></constant>
    <package name="default" namespace="/" extends="json-default">
        <interceptors>
        <interceptor name="uploadInter" class="uploadInterceptor"></interceptor>
        </interceptors>
        <action name="uploadAction" class="upload">
            <interceptor-ref name="fileUploadStack">
                <!--拦截器strut2自带的, 指定上传文件的格式,如果不符合规定,将会自动拦截下来 -->
                <!-- <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg</param> -->
                <param name="maximumSize">20000000000</param>
            </interceptor-ref>
            <interceptor-ref name="uploadInter" />
            <result name="success"></result>
        </action>
        <action name="getupload" class="index">
            <result name="success">
             /index.jsp
            </result>
        </action>
    </package>
</struts>    

 

就这样了。学习愉快。

posted on 2012-05-23 10:59  HisCoder  阅读(2320)  评论(0编辑  收藏  举报