使用JPA JSF MySql上载,插入,检索和显示图像

Coc*_*ter 18 java mysql jsf image jpa-2.0

我问这个问题,我打算回答其他人要学习的问题.它非常简单直接.我希望它有所帮助.

就是这个

使用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
Run Code Online (Sandbox Code Playgroud)

例如,创建会话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();
    }

}
Run Code Online (Sandbox Code Playgroud)

创建您的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
Run Code Online (Sandbox Code Playgroud)

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

@WebServlet(name = "ImageServlet", urlPatterns = {"/ImageServlet"})
Run Code Online (Sandbox Code Playgroud)

这是为了避免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();
Run Code Online (Sandbox Code Playgroud)

以上几行似乎是不言自明的.不要担心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>
}
Run Code Online (Sandbox Code Playgroud)

这是create xhtml,它将图像字节上传并保存到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>
Run Code Online (Sandbox Code Playgroud)

这是列出db中数据的列表页面.它附带一个命令链接,可以将您带到视图页面

<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>
Run Code Online (Sandbox Code Playgroud)

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