JEE Tutorial

Repository Pattern

PlaylistService.java

package com.welovecoding.services;
 
import com.welovecoding.entities.Playlist;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
 
@ManagedBean(name = "playlistService")
@RequestScoped
public class PlaylistService implements Serializable {
 
  @EJB
  private PlaylistRepository repository;
 
  public PlaylistService() {
  }
 
  public Playlist getPlaylistByUrlSlug(String slug) {
    return repository.getPlaylistByUrlSlug(slug);
  }
}

PlaylistRepository.java

package com.welovecoding.services;
 
import com.welovecoding.entities.Playlist;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
@Stateless
public class PlaylistRepository {
 
  @PersistenceContext(unitName = "welovecoding-PU")
  EntityManager em;
 
  public PlaylistRepository() {
  }
 
  public Playlist getPlaylistByUrlSlug(String slug) {
    return (Playlist) em.createNamedQuery("Playlist.findBySlug").setParameter("slug", slug).getSingleResult();
  }
}

Playlist.java

...
@Entity
@Table(name = "playlists")
@XmlRootElement
@NamedQueries({
  @NamedQuery(name = "Playlist.findAll", query = "SELECT p FROM Playlist p"),
  @NamedQuery(name = "Playlist.findBySlug", query = "SELECT p FROM Playlist p WHERE p.slug = :slug")})
public class Playlist implements Serializable {
...
}

playlist.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">
  <h:body>
    <f:metadata>
      <f:viewParam name="playlistSlug" value="#{playlistSlug}" />
    </f:metadata>
    <ui:param name="playlist" value="#{playlistService.getPlaylistByUrlSlug(playlistSlug)}" />
    <h:outputText value="#{playlist.title}" />
  </h:body>
</html>

JSF Snippets

User-Agent in JSF Page ausgeben:

<p><h:outputText value="#{request.getHeader('User-Agent')}" /></p>
<p>#{request.getHeader("User-Agent")}</p>
<p>${header["User-Agent"]}</p>

#{request.getLocale()} // de

Kommentar abgeben

Microsoft Certified Professional Logo
 

Werbung


+Benny Neugebauer