PrimeFaces + Spring Data + Redis-Integration

Dieses Tutorial führt Sie durch die Integration zwischen verschiedenen Frameworks, Primefaces, Spring Data und Redis Key/Value-Datenbank. Wir haben bereits früher Tutorials zu diesen Themen veröffentlicht, auf die Sie für eine ausführliche Diskussion zu jedem Thema verweisen können. In diesem Tutorial wird davon ausgegangen, dass der Leser über ausreichende Kenntnisse zu diesen Themen verfügt und in der Lage ist, diese Frameworks zu integrieren. Wenn Sie Fragen haben, schreiben Sie diese bitte in den Kommentarbereich. Am Ende dieses Tutorials können Sie den Quellcode für dieses Beispiel herunterladen.

Lesen Sie auch:

  • Spring Roo + Spring Data JPA-Repositories + Eclipse-Integration
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB

1. Java Bean

In diesem Beispiel würden wir die Entitäten „Adresse“ und „Mitarbeiter“ verwenden.

Adresse.java

package net.javabeat.springdata.jpa.data;

import java.io.Serializable;
import java.math.BigInteger;

public class Address implements Serializable {

	private static final long serialVersionUID = 1L;

	private BigInteger id;

	private String addressCountry;

	private String addressCity;

	public BigInteger getId() {
		return id;
	}

	public void setId(BigInteger id) {
		this.id = id;
	}

	public String getAddressCountry() {
		return addressCountry;
	}

	public void setAddressCountry(String addressCountry) {
		this.addressCountry = addressCountry;
	}

	public String getAddressCity() {
		return addressCity;
	}

	public void setAddressCity(String addressCity) {
		this.addressCity = addressCity;
	}
}

Employee.java

package net.javabeat.springdata.jpa.data;

import java.io.Serializable;

public class Employee implements Serializable{

	private static final long serialVersionUID = 1L;

	private int id;

	private String employeeName;

	private Address address = new Address();

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getEmployeeName() {
		return employeeName;
	}

	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public boolean equals(Object obj){
		if(obj instanceof Employee){
			Employee emp = (Employee)obj;
			if(emp.getId() == (this.id)){
				return true;
			}
		}
		return false;
	}

	public int hashCode(){
		return this.id;
	}
}

2. Federkonfigurationen

Hier sind die Federkonfigurationen für dieses Tutorial. Der entscheidende Punkt hierbei ist das Hinzufügen der Redis-Datenbankvorlagenklasse und der Verbindungsfactory. Außerdem das Bean-Paket für den automatischen Scan der Java-Klassen.

SpringContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!--  Scanning the Spring Beans -->
	<context:component-scan base-package="net.javabeat.springdata.beans"></context:component-scan>
	<!-- Redis Connection Factory -->
	<bean id="jedisConnFactory"  
			p:use-pool="true" />
	<!-- Redis Template -->
	<bean id="redisTemplate"  
			p:connection-factory-ref="jedisConnFactory" />

</beans>

3. Spring Bean Service

RegistrationService ist der Einstiegspunkt, der für den Zugriff auf die RedisTemplate verwendet wird, die für die Ausführung der verschiedenen Vorgänge mithilfe der Redis-Datenbank verantwortlich ist.

RegistrationService.java

package net.javabeat.springdata.beans;

import net.javabeat.springdata.jpa.data.Employee;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RegistrationService {
	@Autowired
	private RedisTemplate<String,Employee> redisTemplate;

	public RedisTemplate<String, Employee> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<String, Employee> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
}

4. PrimeFaces / JSF-Konfigurationen

Eine nicht triviale Konfiguration ist erforderlich, wenn es darum geht, eine Spring Bean in die von Faces verwaltete Bean einzufügen. Dazu wird ein Spring Expression Language Resolver hinzugefügt faces-config.xml.

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config 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-facesconfig_2_2.xsd"
	version="2.2">
<application>
	<resource-bundle>
		<base-name>net.javabeat.jsf.application</base-name>
		<var>msg</var>
	</resource-bundle>
	<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>

5. Von PrimeFaces verwaltete Bean

RegistrationManagedBean.java

package net.javabeat.primefaces.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import net.javabeat.springdata.beans.RegistrationService;
import net.javabeat.springdata.jpa.data.Employee;

@ManagedBean
@SessionScoped
public class RegistrationManagedBean {

	public static final String EMP_TYPE = "EMP";

	private Employee employee = new Employee();

	private List<Employee> employees = new ArrayList<Employee>();

	private String searchIdentifier;

	private List<Employee> searchedEmployees = new ArrayList<Employee>();

	@ManagedProperty(value="#{registrationService}")
	private RegistrationService service;

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public List<Employee> getEmployees() {
		List<Object> os = this.service.getRedisTemplate().opsForHash().values(EMP_TYPE);
		employees = new ArrayList<Employee>();
		for(Object o : os){
			Employee e = (Employee)o;
			employees.add(e);
		}
		return employees;
	}

	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}

	public RegistrationService getService() {
		return service;
	}

	public void setService(RegistrationService service) {
		this.service = service;
	}

	public String getSearchIdentifier() {
		return searchIdentifier;
	}

	public void setSearchIdentifier(String searchIdentifier) {
		this.searchIdentifier = searchIdentifier;
	}

	public List<Employee> getSearchedEmployees() {
		return searchedEmployees;
	}

	public void setSearchedEmployees(List<Employee> searchedEmployees) {
		this.searchedEmployees = searchedEmployees;
	}

	public String register(){
		// Supposed employee identifier mechanism
		int employeeId = this.service.getRedisTemplate().opsForHash().values(EMP_TYPE).size() + 1;
		this.employee.setId(employeeId);
		// Save
		this.service.getRedisTemplate().
			opsForHash().put("EMP", this.employee.hashCode(), employee);
		this.employee = new Employee();
		return "";
	}

	public String searchById(){
		// Reset the searched list
		this.searchedEmployees = new ArrayList<Employee>();
		// Create dummy employee
		Employee emp = new Employee();
		if(this.searchIdentifier != null && !this.searchIdentifier.equals(""))
			// Set employee identifier for that value entered by the end user
			emp.setId(Integer.parseInt(this.searchIdentifier));
		// Rely on the hash code generated by the employee hashCode()
		this.searchedEmployees.add((Employee)this.service.getRedisTemplate().opsForHash().get(EMP_TYPE, emp.hashCode()));
		return "";
	}
}

6. Web-Bereitstellungsdeskriptor

Es handelt sich um den Bereitstellungsdeskriptor, der die Definition der Webanwendung enthält, die vom Java EE-Container verwendet wird. Für diesen Abschnitt ist keine große Erklärung erforderlich. Wir müssen die JSF- und Spring-Konfigurationen in der Datei web.xml definieren.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" metadata-complete="true" version="2.5">
  <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>
  <context-param>
    <param-name>javax.faces.application.CONFIG_FILES</param-name>
    <param-value>/WEB-INF/faces-config.xml</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-config/*.xml</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>/faces/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
</web-app>

7. Die Aussicht

Hier ist die PrimeFaces-Ansicht, die in diesem Beispiel verwendet wird.

index.xhtml

<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">
	<h:head>
		<script name="jquery/jquery.js" library="primefaces"></script>
	</h:head>
	<f:view>
		<h:form prependId="false">
			<h3>JavaBeat - Tutorials</h3>
			<h2>Primefaces + Spring Data + Redis</h2>
			<h:panelGrid columns="2">
				<h:outputText value="Enter Employee Name:"/>
				<p:inputText value="#{registrationManagedBean.employee.employeeName}"></p:inputText>
				<h:outputText value="Enter Employee Address Country:"/>
				<p:inputText value="#{registrationManagedBean.employee.address.addressCountry}"></p:inputText>
				<h:outputText value="Enter Employee Address City:"/>
				<p:inputText value="#{registrationManagedBean.employee.address.addressCity}"></p:inputText>
			</h:panelGrid>
			<p:commandButton value="Register" action="#{registrationManagedBean.register}" ajax="false"/>
			<p:separator/>
			<h:panelGrid columns="1">
				<p:dataTable value="#{registrationManagedBean.employees}" var="employee">
					<p:column headerText="Employee's Name">
						<h:outputText value="#{employee.employeeName}"/>
					</p:column>
					<p:column headerText="Employee's Country">
						<h:outputText value="#{employee.address.addressCountry}"/>
					</p:column>
					<p:column headerText="Employee's City">
						<h:outputText value="#{employee.address.addressCity}"/>
					</p:column>
				</p:dataTable>
			</h:panelGrid>
			<p:separator/>
			<h:panelGrid columns="2">
				<f:facet name="header">
					<h2>
						<h:outputText value="Search"/>
					</h2>
				</f:facet>
				<h:outputText value="Enter Employee Id"/>
				<p:inputText value="#{registrationManagedBean.searchIdentifier}"></p:inputText>
			</h:panelGrid>
			<p:commandButton value="Search" action="#{registrationManagedBean.searchById}" ajax="false"/>
			<p:separator/>
			<h:panelGrid columns="1">
				<p:dataTable value="#{registrationManagedBean.searchedEmployees}"
						var="employee" emptyMessage="No Result">
					<p:column headerText="Employee's Name">
						<h:outputText value="#{employee.employeeName}"/>
					</p:column>
					<p:column headerText="Employee's Country">
						<h:outputText value="#{employee.address.addressCountry}"/>
					</p:column>
					<p:column headerText="Employee's City">
						<h:outputText value="#{employee.address.addressCity}"/>
					</p:column>
				</p:dataTable>
			</h:panelGrid>
		</h:form>
	</f:view>
</html>

8. Maven-Abhängigkeiten

Hier ist die Maven-Build-Datei (pom.xml), die zum Verwalten der Abhängigkeiten der Webanwendung verwendet wird. In dieser pom.xml-Datei sind alle für dieses Tutorial verwendeten Abhängigkeiten aufgeführt.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>next.javabeat.jsf</groupId>
	<artifactId>JavaBeat-Primefaces-SpringData-Redis</artifactId>
	<packaging>war</packaging>
	<version>1.0</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.6</java.version>
		<junit.version>4.9</junit.version>
		<slf4j.version>1.6.4</slf4j.version>
		<logback.version>1.0.1</logback.version>
		<log4j.version>1.2.14</log4j.version>

		<servlet.version>2.5</servlet.version>
		<jsp.version>2.1</jsp.version>
		<jstl.version>1.2</jstl.version>
		<taglibs-standard.version>1.1.2</taglibs-standard.version>

		<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
		<maven.failsafe.plugin>2.4.3-alpha-1</maven.failsafe.plugin>

	</properties>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${maven.compiler.plugin}</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>

		</plugins>
	</build>
	<dependencies>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.2.4</version>
		</dependency>

		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.2.4</version>
		</dependency>

		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>4.0</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.1.2</version>
		</dependency>

		<!-- Spring Data - Redis Library -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.2.1.RELEASE</version>
		</dependency>
		<!-- Jedis Driver Library -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.4.2</version>
		</dependency>

		<!-- Spring Core -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>
		<!-- Spring Data commons -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-commons</artifactId>
			<version>1.5.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.0.4.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>r09</version>
		</dependency>
	</dependencies>
</project>

9. Primefaces + Spring Data + Redis-Demo

PrimeFaces und Spring Data und Redis-Integration

PrimeFaces und Spring Data und Redis-Integration 1

PrimeFaces- und Spring Data- und Redis-Integration – Suche

(wpdm_file id=93)

Kommentar verfassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Nach oben scrollen