页面无法上传文件

时间:2016-09-17 15:59:56

标签: java jpa

我是JEE的新手。我在使用JSF 2.2,netbeans 8.0.2和glassfish 4.1上的Primefaces 5.0将文件上传到mysql数据库时遇到问题。我还使用** commons-io-2.4 commons-fileupload-1.3 进行上传。我之前在这个网站上看到过类似的问题但是没有一个问题似乎能解决我的问题。**

以下是抛出异常

     javax.faces.el.EvaluationException: java.lang.RuntimeException: javax.transaction.RollbackException: Transaction marked for rollback.
            at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
            at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
            at javax.faces.component.UICommand.broadcast(UICommand.java:315)
            at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
            at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
            at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
            at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
            at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
            at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
            at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
            at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:95)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
            at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
            at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
            at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
            at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
            at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
            at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
            at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
            at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
            at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
            at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
            at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
            at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
            at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
            at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
            at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
            at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
            at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
            at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
            at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
            at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
            at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
            at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
            at java.lang.Thread.run(Thread.java:745)
        Caused by: java.lang.RuntimeException: javax.transaction.RollbackException: Transaction marked for rollback.
            at managed.ClientController.persist(ClientController.java:194)
            at managed.ClientController.createClient(ClientController.java:58)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
            at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
            at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
            at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
            at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
            at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
            ... 41 more
        Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
            at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:490)
            at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:854)
            at com.sun.enterprise.transaction.UserTransactionImpl.commit(UserTransactionImpl.java:212)
            at managed.ClientController.persist(ClientController.java:191)
            ... 52 more

这是我的实体类

    package entity;

    import java.io.Serializable;
    import javax.persistence.Basic;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Lob;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    import javax.xml.bind.annotation.XmlRootElement;

    /**
     *
     * @author rue
     */
    @Entity
    @Table(name = "client")
    @XmlRootElement
    @NamedQueries({
        @NamedQuery(name = "Client.findAll", query = "SELECT c FROM Client c"),
        @NamedQuery(name = "Client.findByEmailAddress", query = "SELECT c FROM Client c WHERE c.emailAddress = :emailAddress"),
        @NamedQuery(name = "Client.findByPhoneNumber", query = "SELECT c FROM Client c WHERE c.phoneNumber = :phoneNumber"),
        @NamedQuery(name = "Client.findByPhysicalAddress", query = "SELECT c FROM Client c WHERE c.physicalAddress = :physicalAddress"),
        @NamedQuery(name = "Client.findByCompanyName", query = "SELECT c FROM Client c WHERE c.companyName = :companyName"),
        @NamedQuery(name = "Client.findByServiceOffered", query = "SELECT c FROM Client c WHERE c.serviceOffered = :serviceOffered"),
        @NamedQuery(name = "Client.findByLicenseStatus", query = "SELECT c FROM Client c WHERE c.licenseStatus = :licenseStatus")})
    public class Client implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @Basic(optional = false)
        @NotNull
        @Size(min = 1, max = 50)
        @Column(name = "email_address")
        private String emailAddress;
        @NotNull
        @Column(name = "phone_number")
        private Integer phoneNumber;
        @NotNull
        @Size(min = 1, max = 400)
        @Column(name = "physical_address")
        private String physicalAddress;
        @NotNull
        @Size(min = 1, max = 30)
        @Column(name = "company_name")
        private String companyName;
        @NotNull
        @Size(min = 1, max = 30)
        @Column(name = "service_offered")
        private String serviceOffered;
        @Basic(optional = false)
        @NotNull
        @Size(min = 1, max = 20)
        @Column(name = "license_status")
        private String licenseStatus;
        @Basic(optional = false)   
        @Lob
        @Column(name = "memorandum_of_association")
        private byte[] memorandumOfAssociation;
        @Basic(optional = false)

        @Lob
        @Column(name = "articles_of_association")
        private byte[] articlesOfAssociation;
        @Basic(optional = false)
        @Lob
        @Column(name = "certificate_of_incorporation")
        private byte[] certificateOfIncorporation;
        @Basic(optional = false)

        @Lob
        @Column(name = "financial_statement")
        private byte[] financialStatement;

        public Client() {
        }

        public Client(String emailAddress) {
            this.emailAddress = emailAddress;
        }

        public Client(String emailAddress, String licenseStatus, byte[] memorandumOfAssociation, byte[] certificateOfIncorporation) {
            this.emailAddress = emailAddress;
            this.licenseStatus = licenseStatus;
            this.memorandumOfAssociation = memorandumOfAssociation;
            this.certificateOfIncorporation = certificateOfIncorporation;
        }

        public Client(String emailAddress, Integer phoneNumber, String physicalAddress, String companyName, String serviceOffered, String licenseStatus, byte[] memorandumOfAssociation, byte[] articlesOfAssociation, byte[] certificateOfIncorporation, byte[] financialStatement) {
            this.emailAddress = emailAddress;
            this.phoneNumber = phoneNumber;
            this.physicalAddress = physicalAddress;
            this.companyName = companyName;
            this.serviceOffered = serviceOffered;
            this.licenseStatus = licenseStatus;
            this.memorandumOfAssociation = memorandumOfAssociation;
            this.articlesOfAssociation = articlesOfAssociation;
            this.certificateOfIncorporation = certificateOfIncorporation;
            this.financialStatement = financialStatement;
        }



        public String getEmailAddress() {
            return emailAddress;
        }

        public void setEmailAddress(String emailAddress) {
            this.emailAddress = emailAddress;
        }

        public Integer getPhoneNumber() {
            return phoneNumber;
        }

        public void setPhoneNumber(Integer phoneNumber) {
            this.phoneNumber = phoneNumber;
        }

        public String getPhysicalAddress() {
            return physicalAddress;
        }

        public void setPhysicalAddress(String physicalAddress) {
            this.physicalAddress = physicalAddress;
        }

        public String getCompanyName() {
            return companyName;
        }

        public void setCompanyName(String companyName) {
            this.companyName = companyName;
        }

        public String getServiceOffered() {
            return serviceOffered;
        }

        public void setServiceOffered(String serviceOffered) {
            this.serviceOffered = serviceOffered;
        }

        public String getLicenseStatus() {
            return licenseStatus;
        }

        public void setLicenseStatus(String licenseStatus) {
            this.licenseStatus = licenseStatus;
        }

        public byte[] getMemorandumOfAssociation() {

            return memorandumOfAssociation;
        }

        public void setMemorandumOfAssociation(byte[] memorandumOfAssociation) {
            this.memorandumOfAssociation = memorandumOfAssociation;
        }

        public byte[] getArticlesOfAssociation() {
            return articlesOfAssociation;
        }

        public void setArticlesOfAssociation(byte[] articlesOfAssociation) {
            this.articlesOfAssociation = articlesOfAssociation;
        }

        public byte[] getCertificateOfIncorporation() {
            return certificateOfIncorporation;
        }

        public void setCertificateOfIncorporation(byte[] certificateOfIncorporation)     {
            this.certificateOfIncorporation = certificateOfIncorporation;
        }

        public byte[] getFinancialStatement() {
            return financialStatement;
        }

        public void setFinancialStatement(byte[] financialStatement) {
            this.financialStatement = financialStatement;
        }

        @Override
        public int hashCode() {
            int hash = 0;
            hash += (emailAddress != null ? emailAddress.hashCode() : 0);
            return hash;
        }

        @Override
        public boolean equals(Object object) {

            if (!(object instanceof Client)) {
                return false;
            }
            Client other = (Client) object;
            return !((this.emailAddress == null && other.emailAddress != null) || (this.emailAddress != null && !this.emailAddress.equals(other.emailAddress)));
        }

        @Override
        public String toString() {
            return "entity.Client[ emailAddress=" + emailAddress + " ]";
        }

    }

这是Managed Bean

    package managed;

    import entity.Client;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.annotation.Resource;
    import javax.ejb.EJB;
    import javax.faces.application.FacesMessage;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.RequestScoped;
    import javax.faces.context.FacesContext;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import session.ClientFacade;
    import org.primefaces.model.UploadedFile;

    /**
     *
     * @author rue
     */
    @ManagedBean
    @RequestScoped
    public class ClientController {

        @EJB
        private ClientFacade clientFacade;
        @PersistenceContext(unitName = "potronlinePU")
        private EntityManager em;
        @Resource
        private javax.transaction.UserTransaction utx;

        private Client c;   
        private Client c1;  
        private UploadedFile financialStatementFile;
        private UploadedFile certificateOfIncorporationFile;
        private UploadedFile memorandumOfAssociationFile;
        private UploadedFile articlesOfAssociationFile;

        public ClientController() {
            c = new Client();
            c1 = new Client();
        }

        public void createClient() {
            Client client = new Client(c.getEmailAddress(), c.getPhoneNumber(), c.getPhysicalAddress(), c.getCompanyName(),
                    c.getServiceOffered(), c.getLicenseStatus(), c.getMemorandumOfAssociation(), c.getArticlesOfAssociation(),
                    c.getCertificateOfIncorporation(), c.getFinancialStatement());
            //clientFacade.create(client);

            this.persist(client);
        }

        public UploadedFile getFinancialStatementFile() {
            return financialStatementFile;
        }

        public void setFinancialStatementFile(UploadedFile financialStatementFile) {
            this.financialStatementFile = financialStatementFile;

    //        this.file = file;
            FileInputStream fin;
            if (financialStatementFile != null) {
                try {
                    fin = new FileInputStream(this.financialStatementFile.getContentType());
                    int bytesAvailable = fin.available();
                    byte[] fileBytes = new byte[bytesAvailable];
                    fin.read(fileBytes);
                    //acReq.setAcquitedFile(fileBytes);
                    c1.setFinancialStatement(fileBytes);
                } catch (IOException ex) {
                    Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
                    FacesMessage msg = new FacesMessage("Failed!", financialStatementFile.getFileName() + " is not uploaded.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                }
            } else {
                FacesMessage msg = new FacesMessage("Please select image!!");
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        }

        public UploadedFile getCertificateOfIncorporationFile() {
            return certificateOfIncorporationFile;
        }

        public void setCertificateOfIncorporationFile(UploadedFile certificateOfIncorporationFile) {
            this.certificateOfIncorporationFile = certificateOfIncorporationFile;

            FileInputStream fin;
            if (certificateOfIncorporationFile != null) {
                try {

                    fin = new FileInputStream(this.certificateOfIncorporationFile.getContentType());
                    int bytesAvailable = fin.available();
                    byte[] fileBytes = new byte[bytesAvailable];
                    fin.read(fileBytes);
                    c1.setCertificateOfIncorporation(fileBytes);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                FacesMessage msg = new FacesMessage("Please select image!!");
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        }

        public UploadedFile getMemorandumOfAssociationFile() {
            return memorandumOfAssociationFile;
        }

        public void setMemorandumOfAssociationFile(UploadedFile memorandumOfAssociationFile) {
            this.memorandumOfAssociationFile = memorandumOfAssociationFile;

            FileInputStream fin;
            if (memorandumOfAssociationFile != null) {
                try {
                    fin = new FileInputStream(this.memorandumOfAssociationFile.getContentType());
                    int bytesAvailable = fin.available();
                    byte[] fileBytes = new byte[bytesAvailable];
                    fin.read(fileBytes);                
                    c1.setMemorandumOfAssociation(fileBytes);
                } catch (IOException ex) {
                    Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
                    FacesMessage msg = new FacesMessage("Failed!", memorandumOfAssociationFile.getFileName() + " is not uploaded.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                }
            } else {
                FacesMessage msg = new FacesMessage("Please select image!!");
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        }

        public UploadedFile getArticlesOfAssociationFile() {
            return articlesOfAssociationFile;
        }

        public void setArticlesOfAssociationFile(UploadedFile articlesOfAssociationFile) {
            this.articlesOfAssociationFile = articlesOfAssociationFile;

            FileInputStream fin;
            if (articlesOfAssociationFile != null) {
                try {
                    fin = new FileInputStream(this.articlesOfAssociationFile.getContentType());
                    int bytesAvailable = fin.available();
                    byte[] fileBytes = new byte[bytesAvailable];
                    fin.read(fileBytes);                
                    c1.setArticlesOfAssociation(fileBytes);

                } catch (IOException ex) {

                    Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
                    FacesMessage msg = new FacesMessage("Failed!", articlesOfAssociationFile.getFileName() + " is not uploaded.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                }
            } else {
                FacesMessage msg = new FacesMessage("Please select image!!");
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        }

        public Client getC() {
            return c;
        }

        public void setC(Client c) {
            this.c = c;
        }

        public Client getC1() {
            return c1;
        }

        public void setC1(Client c1) {
            this.c1 = c1;
        }

        public void persist(Object object) {
            try {

                utx.begin();
                em.persist(object);
                utx.commit();
            } catch (Exception e) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
                throw new RuntimeException(e);

            }
        }

    }

这是提交页面

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:p="http://primefaces.org/ui">

    <body>

        <ui:composition template="./../WEB-INF/clienttemplate.xhtml">

            <ui:define name="top">

            </ui:define>

            <ui:define name="content">
                <h:form enctype="multipart/form-data">
                    <h:panelGrid columns="2" bgcolor="yellow">
                        <p:outputLabel for="compName" value="Compay Name"/>
                        <p:inputText id="compName" value="#{clientController.c.companyName}" />
                        <p:outputLabel for="email" value="Email Address"/>
                        <p:inputText id="email" value="#{clientController.c.emailAddress}" /> 
                        <p:outputLabel for="phone" value="Phone Number"/>
                        <p:inputText id="phone" value="#{clientController.c.phoneNumber}" />
                        <p:outputLabel for="physicalAdd" value="Physical   Address"/>
                        <p:inputText id="physicalAdd" value="#    {clientController.c.physicalAddress}" />
                        <p:outputLabel for="service" value="Service Offered"/>
                        <p:inputText id="service" value="#{clientController.c.serviceOffered}" />
                        <p:outputLabel for="licenseStatus" value="License Status"/>
                        <p:inputText id="licenseStatus" value="#{clientController.c.licenseStatus}" />
                        <p:outputLabel for="memAss" value="Memorandum of Association"/>
                        <p:fileUpload id="memAss" value="#{clientController.memorandumOfAssociationFile}" mode="simple" />
                        <p:outputLabel for="artAss" value="Articles of Association"/>
                        <p:fileUpload id="artAss" value="#{clientController.articlesOfAssociationFile}" mode="simple" />
                        <p:outputLabel for="certInc" value="Certificate of Incorporation"/>
                        <p:fileUpload id="certInc" value="#{clientController.certificateOfIncorporationFile}" mode="simple" />
                        <p:outputLabel for="finSt" value="Financial Statement"/>
                        <p:fileUpload id="finSt" value="#{clientController.financialStatementFile}" mode="simple" />
                        <p:commandButton type="submit" value="Submit" action="#      {clientController.createClient}"  ajax="false" />
                    </h:panelGrid>
                </h:form>
            </ui:define>

            <ui:define name="bottom">

            </ui:define>

        </ui:composition>

    </body>
</html>





**Here is the web.xml file**

<?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
        <context-param>
            <param-name>javax.faces.PROJECT_STAGE</param-name>
            <param-value>Development</param-value>
        </context-param>
        <context-param>
            <param-name>primefaces.UPLOADER</param-name>
            <param-value>auto|native|commons</param-value>
        </context-param>
        <context-param>
            <param-name>primefaces.THEME</param-name>
            <param-value>aristo</param-value>
        </context-param>
        <filter>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <filter-class>
                org.primefaces.webapp.filter.FileUploadFilter
            </filter-class>
        </filter>
        <filter-mapping>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <servlet-name>Faces Servlet</servlet-name>
        </filter-mapping>
        <servlet>
            <servlet-name>Faces Servlet</servlet-name>
            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Faces Servlet</servlet-name>
            <url-pattern>/faces/*</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>faces/index.xhtml</welcome-file>
        </welcome-file-list>
    </web-app>

我正在使用 commons-io-2.4 commons-fileupload-1.3 进行上传

任何人都可以提供帮助,我已经被困了几天

0 个答案:

没有答案