18

我在问这个问题,我打算回答这个问题供其他人学习。它非常简单直接。我希望它有帮助。

就是这个

使用您的 blob 字段创建您的实体,例如客户

@Entity
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Lob
    private byte[] logo;


//setter and getter required

例如,创建一个会话 Bean 以帮助与实体进行通信

@Stateless
public class CustomerService {
    @PersistenceContext(unitName = "ImageTestPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }


    public List<Customer> customerList(){
       return em.createNamedQuery(stat).getResultList();
    }

    public byte[] loadImage(int id){
        return em.find(Customer.class, id).getLogo();
    }

}

创建你的 managedBean。记下 private UploadedFile uploadedFile;它的

org.apache.myfaces.custom.fileupload.UploadedFile;我稍后会解释。

public class CustomerManager {
    @EJB
    private CustomerService customerService;
    private Customer customer = new Customer();
    private List<Customer> list;
    private DataModel<Customer> dataModel;
    private UploadedFile uploadedFile;

    public CustomerManager() {
    }
    public void createCustomer() throws IOException{
        customer.setId(0);
         byte[] file = uploadedFile.getBytes();
         customer.setLogo(file);
         customerService.persist(customer);
    }

    public void loadTable(){
         dataModel = new ListDataModel<Customer>();
        dataModel.setWrappedData(customerService.findStatus(customer));
    } 

    public String view(){
        customer = dataModel.getRowData();
        return "view.xhtml";
    }
//setter and getter for all
//use the loadTable method to load your model table

创建 servlet 类。显示您的图像最重要。请注意以下几点,它们是最重要的

@WebServlet(name = "ImageServlet", urlPatterns = {"/ImageServlet"})

这是为了避免 web.xml 编辑,如果你问我会更容易。只需获取文件的url。

int id =Integer.parseInt(request.getParameter("id"));
        byte[] image = customerService.loadImage(id);

        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(image);
        outputStream.close();

上面的行似乎是不言自明的。不要太担心id它会被用来引用 xhtml 中的图像。

所以完整的 servlet 看起来更像这样

@WebServlet(name = "ImageServlet", urlPatterns = {"/ImageServlet"})
public class ImageServlet extends HttpServlet {
    @EJB
    private CustomerService customerService;


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        int id =Integer.parseInt(request.getParameter("id"));
        byte[] image = customerService.loadImage(id);

        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(image);
        outputStream.close();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

这是将图像字节上传并保存到数据库的创建 xhtml

<?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:h="http://java.sun.com/jsf/html"
      xmlns:t="http://myfaces.apache.org/tomahawk">
    <h:head>
        <title> Title</title>
    </h:head>
    <h:body>
        <h:form id="uploadForm" enctype="multipart/form-data">
            <h:panelGrid columns="2">
                username :<h:inputText value="#{customerManager.customer.username}"/>
                Status :<h:inputText value="#{customerManager.customer.status}"/>
                <h:outputLabel for="file" value="Select file" />
                <t:inputFileUpload id="file" value="#{customerManager.uploadedFile}" required="true" />
                    <h:message for="file" style="color: red;" />

                    <h:commandButton value="Create" action="#{customerManager.createCustomer()}"/>
            </h:panelGrid>
        </h:form>
    </h:body>
</html>

这是列出数据库中数据的列表页面。它附有一个命令链接,可将您带到查看页面

<h:dataTable value="#{customerManager.dataModel}" var="list">
            <h:column>
                #{list.id}
            </h:column>

            <h:column>
                <h:commandLink value="#{list.username}" action="#{customerManager.view}"  />

            </h:column>
        </h:dataTable>

总之,我希望有一天这对某人有所帮助。我希望有人花时间以最简单的方式解决问题,因为我还有很多未解决的问题,但当我做对时会继续阅读我会以最简单的方式分享给像我这样的人。对于upload前面提到的,请您将需要下载到 tomahawk 库。我认为人们喜欢关于它的 balusc 博客。他只是让它看起来比它应该的复杂。只需从博客中挑选您需要的东西并使用它。他是个好人,这一点没有争议。干杯

4

0 回答 0