Learn the latest Spring Framework and pass Spring Core Certification 4.x with online udemy training

Learn the latest Spring Framework and pass Spring Core Certification 4.x with online udemy training

https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25
https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25

https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25

Redemption Code: edulearnspring25

Hi,

I am Tuna Tore and the owner of this technical blog;

I created an online course for learning the details and usages of Spring Framework in commercial environments.

If you would like to learn the latest version of Spring Framework with step by step examples/codes and pass Core Spring Framework Certification 4.x then you can attend this udemy course through the following link;

Spring Framework 4.x Course and Core Spring Certification

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

If you attend this course through this link, I will provide more than %50 discount coupon.
Actual course price is 59 euros and with this link you will be able to learn and code Spring Framework Applications by only paying
25 euros (instead of 59 euros)

Here you can find the contents of udemy Spring Framework Course;

  • Spring Container, Dependency, and IOC (Inversion of Control)
  • Spring Aspect Oriented Programming
  • Spring JDBC, Transactions, and ORM (Hibernate)
  • Spring MVC
  • Spring Security
  • Spring Messaging (JMS)
  • REST
  • Unit Testing with JUnit for Spring Applications
  • Library Management with Maven using STS (Spring Tool Suite)

After attending the course, if you have any questions, I will be ready to support you.

Regards,

Advertisements

java.lang.ClassNotFoundException: javax.faces.webapp.FacesServlet Eclipse luna with correct libraries


java.lang.ClassNotFoundException: javax.faces.webapp.FacesServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:120)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1095)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5201)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

solution follows

if you have related jars and getting the exception above

1

click right on project / click properties and select Deployment Assembly

da

and do the following steps click add

2

select java build path entries

3

add maven dependencies and redeploy your code

4

How to integrate JSF and Spring Framework


If you would like to integrate the JSF MVC framework with the Spring Framework, you can use the following approach;
There are also other configurations  available however this one fits very well while developing web applications using JSF and Spring.

In this example, I am using the basic .jars required by Spring Framework. These jars are;

spring-web.jar
spring-webmvc-2.5.jar
org.springframework.expression-3.1.0.RC1.jar
org.springframework.core-3.1.0.RC1.jar
org.springframework.context-3.1.0.RC1.jar
org.springframework.beans-3.1.0.RC1.jar
org.springframework.asm-3.1.0.RC1.jar

You also the following jars inside your project’s lib folder in order to use JSF framework;

jstl.jar
standard.jar
jsf-impl.jar
jsf-api.jar
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-logging.jar

Here you can see the project’s library structure;

SpringJSFApplication.class this class will be used as  the main application inside the program, it also has a reference for the FooService class  initialized by Spring Framework.

package com.tunatore.spring.application;

import com.tunatore.spring.service.FooService;

/**
*
* @author tunatore
*/
public class SpringJSFApplication {

private FooService fooService;

/**
* @return the fooService
*/
public FooService getFooService() {
return fooService;
}

/**
* @param fooService the fooService to set
*/
public void setFooService(FooService fooService) {
this.fooService = fooService;
}

}

 Foo.class is used a regular bean and it is solely Java POJO

package com.tunatore.spring.bean;

/**
*
* @author tunatore
*/
public class Foo {
private String name = "FooBean Name is here!";

public Foo(String name) {
this.name = name;
}

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}

}

 FooService.class is used to get a Foo Object (or from Database)

package com.tunatore.spring.service;

import com.tunatore.spring.bean.Foo;

/**
*
* @author tunatore
*/
public class FooService {
public Foo getFooBean() {
return new Foo("This is a new Foo [initiated by Spring Framework]");
}
}

The following file is required to configure Spring beans

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Document : applicationContext.xml
 Created on : 28 November 2011, 13:47
 Author : tunatore
 Description:
 applicationContext.xml file is used by
 Spring for bean initializations
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<bean id="springJSFApplication" class="com.tunatore.spring.application.SpringJSFApplication">
 <property name="fooService" ref="fooService"/>
</bean>

<bean id="fooService" class="com.tunatore.spring.service.FooService"/>

</beans>

web.xml file should include the location of the applicationContext.xml and two Spring specific listeners
org.springframework.web.context.ContextLoaderListener
org.springframework.web.context.request.RequestContextListener

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <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>
 <session-config>
 <session-timeout>
 30
 </session-timeout>
 </session-config>
 <welcome-file-list>
 <welcome-file>faces/index.jsp</welcome-file>
 </welcome-file-list>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/applicationContext*.xml</param-value>
 </context-param>
 <listener>
 <listener-class>
 org.springframework.web.context.ContextLoaderListener
 </listener-class>
 </listener>
 <listener>
 <listener-class>
 org.springframework.web.context.request.RequestContextListener
 </listener-class>
 </listener>
</web-app>

With the following faces-config.xml file
fooService Service object will be initialized through Spring Framework. You  also need to define 
org.springframework.web.jsf.DelegatingVariableResolver inside this file.

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="1.2"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

<application>
 <variable-resolver>
 org.springframework.web.jsf.DelegatingVariableResolver
 </variable-resolver>
 </application>
 <managed-bean>
 <managed-bean-name>SpringJSFApplication</managed-bean-name>
 <managed-bean-class>
 com.tunatore.spring.application.SpringJSFApplication
 </managed-bean-class>
 <managed-bean-scope>session</managed-bean-scope>
 <managed-property>
 <property-name>fooService</property-name>
 <value>#{fooService}</value>
 </managed-property>
 </managed-bean>
</faces-config>

This index page will be call fooService methods 

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<f:view>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
 <title>Spring JSF Integration Example</title>
 </head>
 <body>
 <h1><h:outputText value="#{SpringJSFApplication.fooService.fooBean.name}"/></h1>
 </body>
 </html>
</f:view>

When you run the program, you will see the following screen on the browser;

You can download the program’s source by clicking here (This is a war file including sources)

Comments or questions are welcomed

How to run OS commands (Windows OS) from Java Web Applications (J2EE)


If you want to call OS specific commands inside a Java J2EE web application, you can use the following code.

By using this code, you can also get the output from the command console and use it for displaying or other purposes.

Here you can find the BatchFileExecuter class

package com.tunatore.batchoperations;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author tunatore
 */
public class BatchFileExecuter extends HttpServlet {
    protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, InterruptedException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader bufferedReader = null;
Process process = null;
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet BatchFileExecuter</title>");
out.println("</head>");
out.println("<body><center><h1>Content</h1><table border=\"1\">");
//this is the directory which will be used as home directory for the command executing
File directory = new File("C:\\Program Files\\Java\\jdk1.6.0_27\\");
process = Runtime.getRuntime().exec("cmd /c dir", null ,directory);
//reading the InputStream using Buffered Reader
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String currentLine; //reading line by line the output from the command console
while ((currentLine = bufferedReader.readLine()) != null) {
//this piece of code is used for formating the InputStream getting from the command console
  out.println("<tr><td>"
  + currentLine.replace("<", "&lt;").replace(">", "&gt;")
+ "</td></tr>");
}
out.println("</table></center></body>");
out.println("</html>");
} finally {
bufferedReader.close();
//process.destroy();
out.close();
  }
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
try {
handleRequest(request, response);
} catch (InterruptedException ex) {
   Logger.getLogger(BatchFileExecuter.class.getName()).log(Level.SEVERE, null, ex);
}
}
 @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
try {
handleRequest(request, response);
} catch (InterruptedException ex) {
            Logger.getLogger(BatchFileExecuter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}


You can call this class from a JSP file called index.jsp

<%--
    Document   : index
    Created on : 07-11-2011, 15:30:42
    Author     : tunatore
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JavaExecuteBatchWebProject</title>
    </head>
    <body>
        <h1>JavaExecuteBatchWebProject</h1>
        <i>(`cmd /c dir`)</i> command will be executed on the Server Machine </br></br>
        <i>C:\\Program Files\\Java\\jdk1.6.0_27\\</i> will be used for applying the command dir</br></br>
        The output of the command will be published on the browser  </br></br>
<a href="/JavaExecuteBatchWebProject/BatchFileExecuter">Run command on Windows OS</a>
   </body>
</html>

And lastly your web.xml file should like the following;

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>BatchFileExecuter</servlet-name>
        <servlet-class>com.tunatore.batchoperations.BatchFileExecuter</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>BatchFileExecuter</servlet-name>
        <url-pattern>/BatchFileExecuter</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Here you can see the outputs;

First index.jsp output

Second screen’s output

Download All Source

How to use BoneCP Java Database Connection pool (JDBC Pool) library


Hi Friends, the following course is created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

In this post, basically I am going to show you how to configure and get a connection from BoneCP Java Database Connection by providing code examples. This configuration option allows you to define Connection Pool manually without configuring server for the Connection Pool (You don’t need to do anything on Application Server Machine).

By using this solution, you can define the CP from Java Code. And this example is designed to work on any Java EE Servers. If you investigate the documentation of BoneCP, there are some points omitted when you first look at but I will try to explain it by providing more information on this example.

To use the BoneCP first you should download the required jars from the following link;

http://repo1.maven.org/maven2/com/jolbox/bonecp/0.7.1.RELEASE/bonecp-0.7.1.RELEASE.jar

Downloading BoneCP is not enough because there are some dependencies as you can download from here;

BoneCP uses a logging framework so you should download it http://www.slf4j.org/download.html (file name:slf4j-1.6.4.zip)
And for some the of underlying operations it uses Google’s Guava Library can be downloaded here

http://search.maven.org/remotecontent?filepath=com/google/guava/guava/10.0.1/guava-10.0.1.jar

So basically, in this web application, we are going to implement the basic approach (I will provide a better approach such as using Spring’s JDBC template and BoneCP together on my future blog post)  for getting a connections from the database and we will open and close it manually by configuring the BoneCP localy for opening and closing connections.

BoneCP will open connections and  store inside it for us. You can configure how many connections you want by changing the BoneCPConfig config = new BoneCPConfig(); object’s parameters.

First, for this web application we need a ServletContextListener to initialize the connection pool from locally.

Here is the code;

package com.tunatore.db;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public final class ContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        ConnectionManager.configureConnPool();
    }

    public void contextDestroyed(ServletContextEvent sce) {
        ConnectionManager.shutdownConnPool();
    }

}

The main purpose of this listener is to initialize the connection pool and make the necessary configurations inside the main ConnectionManager class. And there are two methods,

Inside the first method;
ConnectionManager.configureConnPool();
method is used for configuring Conn. Pool and opening the connections automatically for the application. (Or you can set lazy initialization functionality by changing the BoneCPConfig’s config.setLazyInit(true); property. and this allows the program open a connection when you call the getConnection() method for the first time from your application.)

The second method  ConnectionManager.shutdownConnPool(); is used to shutdown the pool and close all connections . This method is important because you have to close the pool otherwise all connections will stay alive for some  time (time-out) If you forget to call this method and run your code, there will be many connections unclosed by the Application.  So the contextDestroyed() method will call it only once when the web application un-deployed and this is what we need.

The main class is;

package com.tunatore.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class ConnectionManager {

private static BoneCP connectionPool = null;

public static void configureConnPool() {

try {
Class.forName("com.mysql.jdbc.Driver"); //also you need the MySQL driver
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/testproject");
config.setUsername("root");
config.setPassword("admin");
config.setMinConnectionsPerPartition(5); //if you say 5 here, there will be 10 connection available   config.setMaxConnectionsPerPartition(10);
config.setPartitionCount(2); //2*5 = 10 connection will be available
//config.setLazyInit(true); //depends on the application usage you should chose lazy or not
//setting Lazy true means BoneCP won't open any connections before you request a one from it.
connectionPool = new BoneCP(config); // setup the connection pool
System.out.println("contextInitialized.....Connection Pooling is configured");
System.out.println("Total connections ==&gt; " + connectionPool.getTotalCreatedConnections());
ConnectionManager.setConnectionPool(connectionPool);

} catch (Exception e) {
e.printStackTrace(); //you should use exception wrapping on real-production code
}

}

public static void shutdownConnPool() {

try {
BoneCP connectionPool = ConnectionManager.getConnectionPool();
System.out.println("contextDestroyed....");
if (connectionPool != null) {
 connectionPool.shutdown(); //this method must be called only once when the application stops.
//you don't need to call it every time when you get a connection from the Connection Pool
System.out.println("contextDestroyed.....Connection Pooling shut downed!");
}

} catch (Exception e) {
e.printStackTrace();
}
}

public static Connection getConnection() {

Connection conn = null;
try {
 conn = getConnectionPool().getConnection();
//will get a thread-safe connection from the BoneCP connection pool.
//synchronization of the method will be done inside BoneCP source

} catch (Exception e) {
e.printStackTrace();
}
return conn;

}

public static void closeStatement(Statement stmt) {
try {
if (stmt != null)
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}

}

public static void closeResultSet(ResultSet rSet) {
try {
if (rSet != null)
rSet.close();
} catch (Exception e) {
e.printStackTrace();
}

}

public static void closeConnection(Connection conn) {
try {
if (conn != null)
conn.close(); //release the connection - the name is tricky but connection is not closed it is released
   //and it will stay in pool
} catch (SQLException e) {
e.printStackTrace();
}

}

public static BoneCP getConnectionPool() {
return connectionPool;
}

public static void setConnectionPool(BoneCP connectionPool) {
ConnectionManager.connectionPool = connectionPool;
}

}

Here I will code some unit test for getting connection from the Conn. Pool.

package com.tunatore.db;

import static org.junit.Assert.*;
import java.sql.Connection;
import com.tunatore.db.ConnectionManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestConnectionManager {

   //you application server will call the following two methods for you in production env.
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ConnectionManager.configureConnPool();
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
 ConnectionManager.shutdownConnPool();
}

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void testGetConnection() {
Connection conn = ConnectionManager.getConnection();
 assertNotNull(conn);
 ConnectionManager.closeConnection(conn);      //releasing the connection

}

}

The output;

contextInitialized…..Connection Pooling is configured
Total connections ==> 10
705 [main] INFO com.jolbox.bonecp.BoneCP – Shutting down connection pool…
710 [main] INFO com.jolbox.bonecp.BoneCP – Connection pool has been shutdown.
contextDestroyed….
contextDestroyed…..Connection Pooling shut downed!

IMPORTANT: If you want to use this manual  approach,  do not forget to close statements and resulset objects before releasing the connection to the Conn. Pool. You can close all these inside finally block.

I will post How to use BoneCP and Spring Framework post later and show why using Spring JDBC Template provides a good solution for accessing the database,opening connections,closing connections or similar operations.

****update: Here you can find new post regarding BoneCP and Spring Framework****

https://tunatore.wordpress.com/2011/11/16/how-to-use-spring-jdbc-template-with-bonecp-connection-pooling/

How to use <h:dataTable> JSF component


Use the following 2 classes to generate the content for h:dataTable  JSF UI component

package content;

/**
*
* @author tunatore
*/
public class Employee {

private int employeeID;
private String employeeName;
private String employeeSurname;
private String employeePhoneNumber;

/**
* @return the employeeID
*/
public int getEmployeeID() {
return employeeID;
}

/**
* @param employeeID the employeeID to set
*/
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}

/**
* @return the employeeName
*/
public String getEmployeeName() {
return employeeName;
}

/**
* @param employeeName the employeeName to set
*/
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

/**
* @return the employeeSurname
*/
public String getEmployeeSurname() {
return employeeSurname;
}

/**
* @param employeeSurname the employeeSurname to set
*/
public void setEmployeeSurname(String employeeSurname) {
this.employeeSurname = employeeSurname;
}

/**
* @return the employeePhoneNumber
*/
public String getEmployeePhoneNumber() {
return employeePhoneNumber;
}

/**
* @param employeePhoneNumber the employeePhoneNumber to set
*/
public void setEmployeePhoneNumber(String employeePhoneNumber) {
this.employeePhoneNumber = employeePhoneNumber;
}

}
package content;

import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

/**
*
* @author tunatore
*/
@ManagedBean(name = "EmployeeGenerator")
@RequestScoped
public class EmployeeGenerator {

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

public EmployeeGenerator() {

Employee e1 = new Employee();
e1.setEmployeeID(1);
e1.setEmployeeName("Tuna");
e1.setEmployeeSurname("Tore");
e1.setEmployeePhoneNumber("12345678");

Employee e2 = new Employee();
e2.setEmployeeID(2);
e2.setEmployeeName("James");
e2.setEmployeeSurname("Gosling");
e2.setEmployeePhoneNumber("2222222222");

Employee e3 = new Employee();
e3.setEmployeeID(3);
e3.setEmployeeName("Linus");
e3.setEmployeeSurname("Torvalds");
e3.setEmployeePhoneNumber("3333333333");

Employee e4 = new Employee();
e4.setEmployeeID(4);
e4.setEmployeeName("Bill");
e4.setEmployeeSurname("Gates");
e4.setEmployeePhoneNumber("44444444");

Employee e5 = new Employee();
e5.setEmployeeID(5);
e5.setEmployeeName("Larry");
e5.setEmployeeSurname("Ellison");
e5.setEmployeePhoneNumber("555555555");

Employee e6 = new Employee();
e6.setEmployeeID(6);
e6.setEmployeeName("Tim");
e6.setEmployeeSurname("Berners-Lee");
e6.setEmployeePhoneNumber("66666666");

employees.add(e1);
employees.add(e2);
employees.add(e3);
employees.add(e4);
employees.add(e5);
employees.add(e6);

}

public List<Employee> getEmployees() {

return employees;
}
}

index.html content

<?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:f="http://java.sun.com/jsf/core">
<h:head>
<title>JSF <h:dataable> example</title>
</h:head>
<h:body>
<h:dataTable cellpadding="4" border="1" bgcolor="cyan" value="#{EmployeeGenerator.employees}" var="employee">
<f:facet name="header">
<h:outputText value="Emlpoyee <h:datatable> Example" />
</f:facet>

<h:column>
<f:facet name="header" >
<h:outputText value="Employee ID"/>
</f:facet>
<h:outputText value="#{employee.employeeID}"/>
</h:column>

<h:column>
<f:facet name="header" >
<h:outputText value="Employee Name"/>
</f:facet>
<h:outputText value="#{employee.employeeName}"/>
</h:column>

<h:column>
<f:facet name="header" >
<h:outputText value="Employee Surname"/>
</f:facet>
<h:outputText value="#{employee.employeeSurname}"/>
</h:column>

<h:column>
<f:facet name="header" >
<h:outputText value="Employee Phone"/>
</f:facet>
<h:outputText value="#{employee.employeePhoneNumber}"/>
</h:column>
</h:dataTable>

</h:body>
</html>

Use this url for accessing the index.xhtml page

http://localhost:8080/JSFhdatatableExample/faces/index.xhtml

The output of the program;

Download source

How to use <x:parse> tag of JSTL for parsing XML documents


If you want to parse a XML document, you can use x:parse tag like the following example;

Before using this example don’t forget to include standard.jar and jstl.jar inside lib folder.

Here is the content for the XML file used in this example

<?xml version="1.0" encoding="UTF-8"?>
<SERVERCONFIG>
<SERVERS>
<SERVER NAME="server1" ENABLED="Y">
<IP>10.1.2.1</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>12345</PASSWORD>
<DESCRIPTION>Application Server1</DESCRIPTION>
</SERVER>
<SERVER NAME="server2" ENABLED="Y">
<IP>10.1.2.2</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>54321</PASSWORD>
<DESCRIPTION>Application Server1</DESCRIPTION>
</SERVER>
<SERVER NAME="server3" ENABLED="N">
<IP>10.1.2.3</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>012345</PASSWORD>
<DESCRIPTION>Application Server3</DESCRIPTION>
</SERVER>
<SERVER NAME="server4" ENABLED="Y">
<IP>10.1.2.4</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>0123456</PASSWORD>
<DESCRIPTION>Application Server4</DESCRIPTION>
</SERVER>
<SERVER NAME="server5" ENABLED="N">
<IP>10.1.2.5</IP>
<USERNAME>admin</USERNAME>
<PASSWORD>01234567</PASSWORD>
<DESCRIPTION>Application Server5</DESCRIPTION>
</SERVER>
</SERVERS>
</SERVERCONFIG>

And the JSP page for processing XML content

index.jsp file

<%--
Document   : index
Created on : 16.Eyl.2011, 11:35:25
Author     : tunatore
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body style="background-color: aliceblue">
<center>
<h1>&lt;x:parse&gt; example</h1>
<!--c:import var="server" url="http://localhost:8080/JSTLxparseTagExample/servers.xml"/>-->
<c:import var="server" url="servers.xml"/>
<x:parse xml="${server}" var="output"/>
<table>
<tr>
<td align="center"><b> Getting the first server's information using XPath evaluation of &lt;x:out&gt; tag </b></td>
</tr>
<tr>
<td align="center">
<table border="2">
<tr><td><b>IP:</b></td><td><b><x:out select="$output/SERVERCONFIG/SERVERS/SERVER[1]/IP" /></b></td></tr>
<tr><td><b>USERNAME:</b></td><td><b><x:out select="$output/SERVERCONFIG/SERVERS/SERVER[1]/USERNAME" /></b></td></tr>
<tr><td><b>PASSWORD:</b></td><td><b><x:out select="$output/SERVERCONFIG/SERVERS/SERVER[1]/PASSWORD" /></b></td></tr>
<tr><td><b>DESCRIPTION:</b></td><td><b><x:out select="$output/SERVERCONFIG/SERVERS/SERVER[1]/DESCRIPTION" /></b></td></tr>
</table>
</td>
</tr>
<tr>
<td align="center"><b> Getting all servers using &lt;x:forEach&gt; tag  </b></td>
</tr>
<tr>
<td align="center">
<table border="2">
<x:forEach select="$output/SERVERCONFIG/SERVERS/SERVER"  >
<tr><td><b>SERVER--></b></td><td><b><x:out select="@NAME" /></b></td></tr>
<tr><td><b>IP:</b></td><td><b><x:out select="IP" /></b></td></tr>
<tr><td><b>USERNAME:</b></td><td><b><x:out select="USERNAME" /></b></td></tr>
<tr><td><b>PASSWORD:</b></td><td><b><x:out select="PASSWORD" /></b></td></tr>
<tr><td><b>DESCRIPTION:</b></td><td><b><x:out select="DESCRIPTION" /></b></td></tr>
</x:forEach>
</table>
</td>
</tr>
</table>
</center>
</body>
</html>

And this is the output for the program;

Download sample project