Upload, Insert, Retrieve and Display Image using JPA JSF MySql [closed]

空扰寡人 提交于 2019-11-29 00:57:38

问题


I am asking this question and I intend to answer the question for others to learn. Its pretty simple and straight forward. I Hope it helps.

This is it

Create your entity for example customer with your blob field

@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

Create a session Bean to help communicate with the entity for example

@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();
    }

}

Create your managedBean. Take note of the private UploadedFile uploadedFile; its from the

org.apache.myfaces.custom.fileupload.UploadedFile; which i will explain later.

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

Create the servlet class. Its the most important to display your image. Take note of the following, they are the most important

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

this is to avoid web.xml editing, it easier if you ask me. just get the url of the file.

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();

The above line seems to be self explanatory. Dont worry much about the id it will be use to reference the image in the xhtml later.

so the full servlet look more like this

@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>
}

This is the create xhtml that uploads and save image bytes to the db

<?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>

This is the list page to list your data in the db. it is attached with a commandlink that takes you to the the view page

<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>

In conclusion, I wish this helps someone someday. And I wish someone takes time to solve problems in the most simple way because I still have plenty unanswered questions, but will keep on reading when i'll get it right I will share it in the most simple way for people like me. For the upload earlier mention please your will need to download to tomahawk library. I think people like balusc blog about it. He just made it look complex than it should be. just pick things you need from the blog and use it. He is a good guy no dispute about that. cheers

来源:https://stackoverflow.com/questions/11954181/upload-insert-retrieve-and-display-image-using-jpa-jsf-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!