Merhaba,
Bu yazımızda JSF'te PrimeFaces kullanarak veritabanına nasıl resim kaydedip ve veritabanından nasıl çağıralacağını anlatmaya çalışacağım.
Kullandıklarım
MySql
PrimeFaces 6.0
Netbeans 8.0.2
commons-fileupload 1.3
commons-io 2.2
omnifaces 2.4
Öncelikle veritabanına aşağıdaki şekilde name,extension,size ve image alanlarını ekliyoruz. Buradaki
name : Saklayacağımız dosyanın adını ifade eder.
extensions : Dosyanın uzantısını ifade eder.
size : Dosyanın boyutunu ifade eder.
image : Saklayacağımız dosyayı ifade eder.
CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(145) NOT NULL,
`extension` varchar(45) DEFAULT NULL,
`size` varchar(45) DEFAULT NULL,
`image` blob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Veritabanını oluşturduktan sonra sıra projemizi oluşturup framework tanımlamasına geliyor. Daha önce burada anlatmış olduğum gibi CRUD projesi oluşturabilirsiniz. Yine aynı yerde anlatmış olduğum Maven tanımlamasını yapabilirsiniz.
FileUpload için projemize Apache Foundation oluşturmuş olduğu commons-fileupload ve commons-io kütüphanelerimizi ekliyoruz. PrimeFaces'in Learn Sayfa 12'de açıklandığı üzere dosya yüklemeleri için gereklidir.
Burada ayrıca OmniFaces kütüphanesi'ni de ekliyoruz. OmniFaces JSF için üçüncü parti fonksiyon kütüphanesidir.
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.omnifaces</groupId>
<artifactId>omnifaces</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
web.xml dosyasında aşağıdaki gibi FileUpload Filter tanımlamasını yapıyoruz.
<?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>
<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>*.xhtml</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<!-- PrimeFaces Upload -->
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</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>
<!-- PrimeFaces Upload -->
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
</web-app>
Entity dosyamız aşağıdaki gibi olmalıdır.
Images.java
package com.kurtomerfaruk.primefacesimagetodb.models;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
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 Omer Faruk Kurt
* @Created on date 25/04/2017 16:29:02
* @blog http://kurtomerfaruk.com
* @mail kurtomerfaruk@gmail.com
*/
@Entity
@Table(name = "images")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Images.findAll", query = "SELECT i FROM Images i"),
@NamedQuery(name = "Images.findById", query = "SELECT i FROM Images i WHERE i.id = :id"),
@NamedQuery(name = "Images.findByName", query = "SELECT i FROM Images i WHERE i.name = :name"),
@NamedQuery(name = "Images.findByExtension", query = "SELECT i FROM Images i WHERE i.extension = :extension"),
@NamedQuery(name = "Images.findBySize", query = "SELECT i FROM Images i WHERE i.size = :size")})
public class Images implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 145)
@Column(name = "name")
private String name;
@Size(max = 45)
@Column(name = "extension")
private String extension;
@Size(max = 45)
@Column(name = "size")
private String size;
@Lob
@Column(name = "image")
private byte[] image;
public Images() {
}
public Images(Integer id) {
this.id = id;
}
public Images(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Images)) {
return false;
}
Images other = (Images) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.kurtomerfaruk.primefacesimagetodb.models.Images[ id=" + id + " ]";
}
}
ImagesFacade.java
package com.kurtomerfaruk.primefacesimagetodb.services;
import com.kurtomerfaruk.primefacesimagetodb.models.Images;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Omer Faruk Kurt
* @Created on date 25/04/2017 16:31:47
* @blog http://kurtomerfaruk.com
* @mail kurtomerfaruk@gmail.com
*/
@Stateless
public class ImagesFacade extends AbstractFacade<Images> {
@PersistenceContext(unitName = "com.kurtomerfaruk_PrimeFacesImageToDb_war_1.0PU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ImagesFacade() {
super(Images.class);
}
}
AbstractFacade.java
package com.kurtomerfaruk.primefacesimagetodb.services;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
/**
*
* @author Omer Faruk Kurt
* @Created on date 25/04/2017 16:31:47
* @blog http://kurtomerfaruk.com
* @mail kurtomerfaruk@gmail.com
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
public List<T> findRange(int first, int pageSize, String sortField, String sortOrder, Map<String, Object> filters) {
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
javax.persistence.criteria.Root<T> entityRoot = cq.from(entityClass);
cq.select(entityRoot);
List<javax.persistence.criteria.Predicate> predicates = getPredicates(cb, entityRoot, filters);
if (predicates.size() > 0) {
cq.where(predicates.toArray(new javax.persistence.criteria.Predicate[]{}));
}
if (sortField != null && sortField.length() > 0) {
if (entityRoot.get(sortField) != null) {
if (sortOrder.startsWith("ASC")) {
cq.orderBy(cb.asc(entityRoot.get(sortField)));
}
if (sortOrder.startsWith("DESC")) {
cq.orderBy(cb.desc(entityRoot.get(sortField)));
}
}
}
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(pageSize);
q.setFirstResult(first);
return q.getResultList();
}
public List<T> findRange(int first, int pageSize, Map<String, String> sortFields, Map<String, Object> filters) {
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
javax.persistence.criteria.Root<T> entityRoot = cq.from(entityClass);
cq.select(entityRoot);
List<javax.persistence.criteria.Predicate> predicates = getPredicates(cb, entityRoot, filters);
if (predicates.size() > 0) {
cq.where(predicates.toArray(new javax.persistence.criteria.Predicate[]{}));
}
if (sortFields != null && !sortFields.isEmpty()) {
for (String sortField : sortFields.keySet()) {
if (entityRoot.get(sortField) != null) {
String sortOrder = sortFields.get(sortField);
if (sortOrder.startsWith("ASC")) {
cq.orderBy(cb.asc(entityRoot.get(sortField)));
}
if (sortOrder.startsWith("DESC")) {
cq.orderBy(cb.desc(entityRoot.get(sortField)));
}
}
}
}
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(pageSize);
q.setFirstResult(first);
return q.getResultList();
}
public int count(Map<String, Object> filters) {
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
javax.persistence.criteria.Root<T> entityRoot = cq.from(entityClass);
cq.select(cb.count(entityRoot));
List<javax.persistence.criteria.Predicate> predicates = getPredicates(cb, entityRoot, filters);
if (predicates.size() > 0) {
cq.where(predicates.toArray(new javax.persistence.criteria.Predicate[]{}));
}
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
private List<Predicate> getPredicates(CriteriaBuilder cb, Root<T> entityRoot, Map<String, Object> filters) {
javax.persistence.metamodel.Metamodel entityModel = this.getEntityManager().getMetamodel();
javax.persistence.metamodel.ManagedType<T> entityType = entityModel.managedType(entityClass);
java.util.Set<javax.persistence.metamodel.EmbeddableType<?>> embeddables = entityModel.getEmbeddables();
String fieldTypeName = null;
// Add predicates (WHERE clauses) based on filters map
List<javax.persistence.criteria.Predicate> predicates = new java.util.ArrayList<>();
for (String s : filters.keySet()) {
javax.persistence.criteria.Path<Object> pkFieldPath = null;
if (s.contains(".")) {
String embeddedIdField = s.split("\\.")[0];
String embeddedIdMember = s.split("\\.")[1];
pkFieldPath = entityRoot.get(embeddedIdField).get(embeddedIdMember);
javax.persistence.metamodel.EmbeddableType<?> embeddableType = entityModel.embeddable(entityType.getAttribute(embeddedIdField).getJavaType());
fieldTypeName = embeddableType.getAttribute(embeddedIdMember).getJavaType().getName();
} else {
pkFieldPath = entityRoot.get(s);
fieldTypeName = entityType.getAttribute(s).getJavaType().getName();
}
if (pkFieldPath != null && fieldTypeName != null) {
if (fieldTypeName.contains("String")) {
predicates.add(cb.like((javax.persistence.criteria.Expression) pkFieldPath, filters.get(s) + "%"));
} else {
javax.persistence.criteria.Expression<?> filterExpression = getCastExpression((String) filters.get(s), fieldTypeName, cb);
if (filterExpression != null) {
predicates.add(cb.equal((javax.persistence.criteria.Expression<?>) pkFieldPath, filterExpression));
} else {
predicates.add(cb.equal((javax.persistence.criteria.Expression<?>) pkFieldPath, filters.get(s)));
}
}
}
}
return predicates;
}
private Expression<?> getCastExpression(String searchValue, String typeName, CriteriaBuilder cb) {
javax.persistence.criteria.Expression<?> expression = null;
switch (typeName) {
case "short":
expression = cb.literal(Short.parseShort(searchValue));
break;
case "byte":
expression = cb.literal(Byte.parseByte(searchValue));
break;
case "int":
expression = cb.literal(Integer.parseInt(searchValue));
break;
case "long":
expression = cb.literal(Long.parseLong(searchValue));
break;
case "float":
expression = cb.literal(Float.parseFloat(searchValue));
break;
case "double":
expression = cb.literal(Double.parseDouble(searchValue));
break;
case "boolean":
expression = cb.literal(Boolean.parseBoolean(searchValue));
break;
default:
break;
}
return expression;
}
}
ImagesController.java
package com.kurtomerfaruk.primefacesimagetodb.controllers;
import com.kurtomerfaruk.primefacesimagetodb.controllers.util.MobilePageController;
import com.kurtomerfaruk.primefacesimagetodb.models.Images;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
/**
*
* @author Omer Faruk Kurt
* @Created on date 25/04/2017 16:31:47
* @blog http://kurtomerfaruk.com
* @mail kurtomerfaruk@gmail.com
*/
@Named(value = "imagesController")
@ViewScoped
public class ImagesController extends AbstractController<Images> {
private static final long serialVersionUID = -4549216213990661616L;
@Inject
private MobilePageController mobilePageController;
public ImagesController() {
// Inform the Abstract parent controller of the concrete Images Entity
super(Images.class);
}
}
AbstractController.java
package com.kurtomerfaruk.primefacesimagetodb.controllers;
import com.kurtomerfaruk.primefacesimagetodb.services.AbstractFacade;
import com.kurtomerfaruk.primefacesimagetodb.services.LazyEntityDataModel;
import com.kurtomerfaruk.primefacesimagetodb.controllers.util.JsfUtil;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import java.util.ResourceBundle;
import javax.ejb.EJBException;
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
/**
* Represents an abstract shell of to be used as JSF Controller to be used in
* AJAX-enabled applications. No outcomes will be generated from its methods
* since handling is designed to be done inside one page.
*
* @param <T> the concrete Entity type of the Controller bean to be created
*/
/**
*
* @author Omer Faruk Kurt
* @Created on date 25/04/2017 16:31:47
* @blog http://kurtomerfaruk.com
* @mail kurtomerfaruk@gmail.com
*/
public abstract class AbstractController<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private AbstractFacade<T> ejbFacade;
private Class<T> itemClass;
private T selected;
private Collection<T> items;
private LazyEntityDataModel<T> lazyItems;
private enum PersistAction {
CREATE,
DELETE,
UPDATE
}
public AbstractController() {
}
public AbstractController(Class<T> itemClass) {
this.itemClass = itemClass;
}
/**
* Retrieve the currently selected item.
*
* @return the currently selected Entity
*/
public T getSelected() {
return selected;
}
/**
* Pass in the currently selected item.
*
* @param selected the Entity that should be set as selected
*/
public void setSelected(T selected) {
this.selected = selected;
}
/**
* Sets any embeddable key fields if an Entity uses composite keys. If the
* entity does not have composite keys, this method performs no actions and
* exists purely to be overridden inside a concrete controller class.
*/
protected void setEmbeddableKeys() {
// Nothing to do if entity does not have any embeddable key.
}
;
/**
* Sets the concrete embedded key of an Entity that uses composite keys.
* This method will be overriden inside concrete controller classes and does
* nothing if the specific entity has no composite keys.
*/
protected void initializeEmbeddableKey() {
// Nothing to do if entity does not have any embeddable key.
}
/**
* Returns all items as a Collection object.
*
* @return a collection of Entity items returned by the data layer
*/
public Collection<T> getItems() {
if (items == null) {
items = this.ejbFacade.findAll();
}
return items;
}
/**
* Pass in collection of items
*
* @param items a collection of Entity items
*/
public void setItems(Collection<T> items) {
this.items = items;
}
/**
*
* @return Entity-specific Lazy Data Model
*/
public LazyEntityDataModel<T> getLazyItems() {
if (lazyItems == null) {
lazyItems = new LazyEntityDataModel<>(this.ejbFacade);
}
return lazyItems;
}
public void setLazyItems(LazyEntityDataModel<T> lazyItems) {
this.lazyItems = lazyItems;
}
public void setLazyItems(Collection<T> items) {
if (items instanceof List) {
lazyItems = new LazyEntityDataModel<>((List<T>) items);
} else {
lazyItems = new LazyEntityDataModel<>(new ArrayList<>(items));
}
}
/**
* Apply changes to an existing item to the data layer.
*
* @param event an event from the widget that wants to save an Entity to the
* data layer
*/
public void save(ActionEvent event) {
String msg = ResourceBundle.getBundle("/messages").getString(itemClass.getSimpleName() + "Updated");
persist(PersistAction.UPDATE, msg);
}
/**
* Store a new item in the data layer.
*
* @param event an event from the widget that wants to save a new Entity to
* the data layer
*/
public void saveNew(ActionEvent event) {
String msg = ResourceBundle.getBundle("/messages").getString(itemClass.getSimpleName() + "Created");
persist(PersistAction.CREATE, msg);
if (!isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
lazyItems = null; // Invalidate list of lazy items to trigger re-query.
}
}
/**
* Remove an existing item from the data layer.
*
* @param event an event from the widget that wants to delete an Entity from
* the data layer
*/
public void delete(ActionEvent event) {
String msg = ResourceBundle.getBundle("/messages").getString(itemClass.getSimpleName() + "Deleted");
persist(PersistAction.DELETE, msg);
if (!isValidationFailed()) {
selected = null; // Remove selection
items = null; // Invalidate list of items to trigger re-query.
lazyItems = null; // Invalidate list of lazy items to trigger re-query.
}
}
/**
* Performs any data modification actions for an entity. The actions that
* can be performed by this method are controlled by the
* {@link PersistAction} enumeration and are either CREATE, EDIT or DELETE.
*
* @param persistAction a specific action that should be performed on the
* current item
* @param successMessage a message that should be displayed when persisting
* the item succeeds
*/
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
this.setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
this.ejbFacade.edit(selected);
} else {
this.ejbFacade.remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
Throwable cause = JsfUtil.getRootCause(ex.getCause());
if (cause != null) {
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException excp = (ConstraintViolationException) cause;
for (ConstraintViolation s : excp.getConstraintViolations()) {
JsfUtil.addErrorMessage(s.getMessage());
}
} else {
String msg = cause.getLocalizedMessage();
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/messages").getString("PersistenceErrorOccured"));
}
}
}
/**
* Creates a new instance of an underlying entity and assigns it to Selected
* property.
*
* @param event an event from the widget that wants to create a new,
* unmanaged Entity for the data layer
* @return a new, unmanaged Entity
*/
public T prepareCreate(ActionEvent event) {
T newItem;
try {
newItem = itemClass.newInstance();
this.selected = newItem;
initializeEmbeddableKey();
return newItem;
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Inform the user interface whether any validation error exist on a page.
*
* @return a logical value whether form validation has passed or failed
*/
public boolean isValidationFailed() {
return JsfUtil.isValidationFailed();
}
/**
* Retrieve all messages as a String to be displayed on the page.
*
* @param clientComponent the component for which the message applies
* @param defaultMessage a default message to be shown
* @return a concatenation of all messages
*/
public String getComponentMessages(String clientComponent, String defaultMessage) {
return JsfUtil.getComponentMessages(clientComponent, defaultMessage);
}
/**
* Retrieve a collection of Entity items for a specific Controller from
* another JSF page via Request parameters.
*/
@PostConstruct
public void initParams() {
Object paramItems = FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get(itemClass.getSimpleName() + "_items");
if (paramItems != null) {
setItems((Collection<T>) paramItems);
setLazyItems((Collection<T>) paramItems);
}
}
}
FileUploadController.java
package com.kurtomerfaruk.primefacesimagetodb.controllers;
import com.kurtomerfaruk.primefacesimagetodb.models.Images;
import com.kurtomerfaruk.primefacesimagetodb.services.ImagesFacade;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.ejb.EJB;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.inject.Inject;
import org.omnifaces.util.Utils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
/**
*
* @author Omer Faruk Kurt
* @Created on date 25/04/2017 16:37:27
* @blog http://kurtomerfaruk.com
* @mail kurtomerfaruk@gmail.com
*/
@ManagedBean
@ApplicationScoped
public class FileUploadController {
@Inject
private ImagesController imagesController;
@EJB
private ImagesFacade service;
private StreamedContent image=null;
public FileUploadController() {
}
public StreamedContent getImage() {
FacesContext context = FacesContext.getCurrentInstance();
if (image == null) {
InputStream is = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/resources/images/user2-160x160.jpg");
return new DefaultStreamedContent(is);
}
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
InputStream is = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/resources/images/user2-160x160.jpg");
return new DefaultStreamedContent(is);
}
return image;
}
public void setImage(StreamedContent image) {
this.image = image;
}
public void fileUpload(FileUploadEvent event){
try {
UploadedFile file = event.getFile();
image = new DefaultStreamedContent(file.getInputstream(), "image/jpeg");
Images images = imagesController.getSelected();
images.setImage(Utils.toByteArray(image.getStream()));
images.setName(file.getFileName());
images.setSize(String.valueOf(file.getSize()));
images.setExtension(file.getContentType());
imagesController.setSelected(images);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void imageClear(){
image=null;
}
public void findImage(Integer imageId) {
if (imageId != null) {
Images images = service.find(imageId);
if (images.getImage() != null) {
image = new DefaultStreamedContent(new ByteArrayInputStream(images.getImage()));
}
}
}
}
Create.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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:o="http://omnifaces.org/ui">
<ui:composition>
<p:dialog id="ImagesCreateDlg" widgetVar="ImagesCreateDialog" modal="true" resizable="false" appendTo="@(body)" header="#{messages.CreateImagesTitle}" closeOnEscape="true">
<h:form id="ImagesCreateForm">
<h:panelGroup id="display" rendered="#{imagesController.selected != null}">
<p:panelGrid columns="2" columnClasses="column">
<p:outputLabel value="#{messages.CreateImagesLabel_name}" for="name" />
<p:inputText id="name" value="#{imagesController.selected.name}" title="#{messages.CreateImagesTitle_name}" required="true" requiredMessage="#{messages.CreateImagesRequiredMessage_name}" size="145" maxlength="145"/>
<p:outputLabel value="#{messages.CreateImagesLabel_extension}" for="extension" />
<p:inputText id="extension" value="#{imagesController.selected.extension}" title="#{messages.CreateImagesTitle_extension}" size="45" maxlength="45"/>
<p:outputLabel value="#{messages.CreateImagesLabel_size}" for="size" />
<p:inputText id="size" value="#{imagesController.selected.size}" title="#{messages.CreateImagesTitle_size}" size="45" maxlength="45"/>
<p:outputLabel value="#{messages.CreateImagesLabel_image}" />
<h:panelGroup>
<o:graphicImage rendered="#{imagesController.selected.image!=null}" value="#{imagesController.selected.image}" width="150" height="150" dataURI="true"/>
<p:commandButton value="Clear" actionListener="#{fileUploadController.imageClear()}" update=":growl" process="@this"/>
</h:panelGroup>
<p:outputLabel value="File Upload"/>
<p:fileUpload fileUploadListener="#{fileUploadController.fileUpload}" update="display" auto="true" mode="advanced" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
</p:panelGrid>
<p:commandButton actionListener="#{imagesController.saveNew}" value="#{messages.Save}" update="display,:ImagesListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,PF('ImagesCreateDialog'));">
<p:confirm header="#{messages.ConfirmationHeader}" message="#{messages.ConfirmCreateMessage}" icon="ui-icon-alert"/>
</p:commandButton>
<p:commandButton value="#{messages.Cancel}" oncomplete="PF('ImagesCreateDialog').hide()" update="display" process="@this" immediate="true" resetValues="true"/>
</h:panelGroup>
</h:form>
</p:dialog>
</ui:composition>
</html>
Edit.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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:o="http://omnifaces.org/ui">
<ui:composition>
<p:dialog id="ImagesEditDlg" widgetVar="ImagesEditDialog" modal="true" resizable="false" appendTo="@(body)" header="#{messages.EditImagesTitle}" closeOnEscape="true">
<h:form id="ImagesEditForm">
<h:panelGroup id="display">
<p:panelGrid columns="2" columnClasses="column" rendered="#{imagesController.selected != null}">
<h:outputLabel value="#{messages.EditImagesLabel_id}" for="id" />
<h:outputText id="id" value="#{imagesController.selected.id}" />
<p:outputLabel value="#{messages.EditImagesLabel_name}" for="name" />
<p:inputText id="name" value="#{imagesController.selected.name}" title="#{messages.EditImagesTitle_name}" required="true" requiredMessage="#{messages.EditImagesRequiredMessage_name}" size="145" maxlength="145"/>
<p:outputLabel value="#{messages.EditImagesLabel_extension}" for="extension" />
<p:inputText id="extension" value="#{imagesController.selected.extension}" title="#{messages.EditImagesTitle_extension}" size="45" maxlength="45"/>
<p:outputLabel value="#{messages.EditImagesLabel_size}" for="size" />
<p:inputText id="size" value="#{imagesController.selected.size}" title="#{messages.EditImagesTitle_size}" size="45" maxlength="45"/>
<p:outputLabel value="#{messages.EditImagesLabel_image}" />
<o:graphicImage value="#{imagesController.selected.image}" width="150" height="150" dataURI="true"/>
</p:panelGrid>
<p:commandButton actionListener="#{imagesController.save}" value="#{messages.Save}" update="display,:ImagesListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,PF('ImagesEditDialog'));">
<p:confirm header="#{messages.ConfirmationHeader}" message="#{messages.ConfirmEditMessage}" icon="ui-icon-alert"/>
</p:commandButton>
<p:commandButton value="#{messages.Cancel}" oncomplete="PF('ImagesEditDialog').hide()" update="display" process="@this" immediate="true" resetValues="true"/>
</h:panelGroup>
</h:form>
</p:dialog>
</ui:composition>
</html>
List.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">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:form id="ImagesListForm">
<p:panel header="#{messages.ListImagesTitle}">
<p:contextMenu id="ImagesDataTableContextMenu" for="datalist">
<p:menuitem value="#{messages.Create}" onclick="document.getElementById('ImagesListForm:createButton').click();" icon="ui-icon-plus"/>
<p:menuitem value="#{messages.View}" onclick="document.getElementById('ImagesListForm:viewButton').click();" icon="ui-icon-search"/>
<p:menuitem value="#{messages.Edit}" onclick="document.getElementById('ImagesListForm:editButton').click();" icon="ui-icon-pencil"/>
<p:menuitem value="#{messages.Delete}" onclick="document.getElementById('ImagesListForm:deleteButton').click();" icon="ui-icon-trash"/>
</p:contextMenu>
<p:dataTable id="datalist"
value="#{imagesController.lazyItems}"
lazy="true"
var="item"
paginator="true"
rows="10"
rowsPerPageTemplate="10,20,30,40,50"
selectionMode="single"
selection="#{imagesController.selected}">
<!--
To disable Lazy Loading, please copy/replace the following lines above,
and be sure to replace the word HASH with the # symbol:
value="HASH{imagesController.items}"
lazy="false"
rowKey="HASH{item.id}"
-->
<p:ajax event="rowSelect" update="@form:createButton,@form:viewButton,@form:editButton,@form:deleteButton,@form:ImagesDataTableContextMenu"/>
<p:ajax event="rowUnselect" update="@form:createButton,@form:viewButton,@form:editButton,@form:deleteButton,@form:ImagesDataTableContextMenu"/>
<p:ajax event="contextMenu" update="@form:createButton @form:viewButton @form:editButton @form:deleteButton"/>
<p:ajax event="rowDblselect" onsuccess="document.getElementById('ImagesListForm:viewButton').click();"/>
<p:column sortBy="#{item.id}" filterBy="#{item.id}">
<f:facet name="header">
<h:outputText value="#{messages.ListImagesTitle_id}"/>
</f:facet>
<h:outputText value="#{item.id}"/>
</p:column>
<p:column sortBy="#{item.name}" filterBy="#{item.name}">
<f:facet name="header">
<h:outputText value="#{messages.ListImagesTitle_name}"/>
</f:facet>
<h:outputText value="#{item.name}"/>
</p:column>
<p:column sortBy="#{item.extension}" filterBy="#{item.extension}">
<f:facet name="header">
<h:outputText value="#{messages.ListImagesTitle_extension}"/>
</f:facet>
<h:outputText value="#{item.extension}"/>
</p:column>
<p:column sortBy="#{item.size}" filterBy="#{item.size}">
<f:facet name="header">
<h:outputText value="#{messages.ListImagesTitle_size}"/>
</f:facet>
<h:outputText value="#{item.size}"/>
</p:column>
<p:column sortBy="#{item.image}" filterBy="#{item.image}">
<f:facet name="header">
<h:outputText value="#{messages.ListImagesTitle_image}"/>
</f:facet>
<h:outputText value="#{item.image}"/>
</p:column>
</p:dataTable>
<p:commandButton id="createButton" icon="ui-icon-plus" value="#{messages.Create}" actionListener="#{imagesController.prepareCreate}" update=":ImagesCreateForm" oncomplete="PF('ImagesCreateDialog').show()"/>
<p:commandButton id="viewButton" style="visibility: hidden;" icon="ui-icon-search" value="#{messages.View}" update=":ImagesViewForm" oncomplete="PF('ImagesViewDialog').show()" disabled="#{empty imagesController.selected}"/>
<p:commandButton id="editButton" actionListener="#{fileUploadController.findImage(imagesController.selected.id)}" icon="ui-icon-pencil" value="#{messages.Edit}" update=":ImagesEditForm" oncomplete="PF('ImagesEditDialog').show()" disabled="#{empty imagesController.selected}"/>
<p:commandButton id="deleteButton" style="visibility: hidden;" icon="ui-icon-trash" value="#{messages.Delete}" actionListener="#{imagesController.delete}" update=":growl,datalist" disabled="#{empty imagesController.selected}">
<p:confirm header="#{messages.ConfirmationHeader}" message="#{messages.ConfirmDeleteMessage}" icon="ui-icon-alert"/>
</p:commandButton>
</p:panel>
<ui:include src="/confirmation.xhtml"/>
</h:form>
</ui:composition>
Projenin kodlarının burada bulabilirsiniz.
https://github.com/kurtomerfaruk/PrimeFacesImageDb
0 Yorumlar