In this section we will discuss that how to integrate JSF and JDBC by configuring DataSource into Tomcat.
JSF And JDBC By Configuring DataSource Into Tomcat
In this section we will discuss that how to integrate JSF and JDBC by configuring DataSource into Tomcat.
Here I am using the JSF 2, Tomcat 7 and the MySQL. So I have downloaded the all of these jar files (You can download these jar files from here). And for the latest version you can visit the following sites individually :
- To Download JSF 2 you can visit this Link http://javaserverfaces.java.net/download.html.
- To Download Tomcat 7 you can visit this Link apache-tomcat-7.0.20-windows-x86.zip
- To Download MySQL connector you can visit this link http://www.mysql.com/downloads/connector/j/
Now come back to our topic the configuration of DataSource into Tomcat. We would have to create a Resource definition like as follows
- By defining the Context elements (context elements are loaded by the all
webapps of that host) explicitly as context.xml file as /META-INF/context.xml in the application
files.
In the context.xml file Resource can be defined as :
<Context> <Resource name="jdbc/database" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/record"/> </Context>
Description of the used attributes of Resource element
- name : The attribute specifies the name of resource to be created.
- auth : Value of this attribute can be either the 'Application' or 'Container'. These values specifies that who will signed on to the resource manager, Application specifies that the web Application code will signed on and the Container specifies that the Container will signed on in place of the application. This attribute is made essential to use with the Resource element if in the web.xml file you are using the <resource-ref> otherwise it is optional if the <resource-env-ref> is used.
- type : Specifies the fully qualified Java class name to lookup this resource. A web application is looked up for the resource using the value of this attribute.
- driverClassName : Value of this attribute specifies the JDBC Driver Name.
- username : This attribute specifies the user name after prousing which the database can be accessed.
- password : This attribute specifies the password after providing which the database can be accessed
- url : This attribute specifies the url of the database.
- Then in the web.xml (deployment descriptor) file following entries should be
made :
<resource-ref> <description>Database for User</description> <res-ref-name>jdbc/database</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
Example :
Now I have created an example in Eclipse IDE to insert the record into the database table. For this I have created a database table like as follows :
CREATE TABLE `user1` ( `userId` bigint(10) NOT NULL, `name` varchar(15) NOT NULL, `address` varchar(255) NOT NULL, `created_date` date NOT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 ROW_FORMAT=DYNAMIC
Then created a JSF application named jsfJdbcWithConnectionResource then created a User.java class with a constructor, some data members and their setter getter methods and method add() to insert the data to the database table. Inside the Constructor I have created an instance of the Context and looked up for the Resource using the lookup() method. In the add() method first get the connection and then perform the sql operation to insert the record into table. Then created an insert.xhtml page that facilitate to insert the data into table and the others xhtml files are called on the special condition which i.e. if the data is inserted successfully then the output.xhtml page will be displayed and if getting any error into inserting the data then the invalid.xhtml page will be executed.
Directory Structure
User.java
package com.dev.user.model; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; @ManagedBean(name = "user") @RequestScoped public class User { private DataSource ds; private long userID; private String name; private String address; private Date created_date; public User() { try { Context ctx = new InitialContext(); ds = (DataSource) ctx.lookup("java:comp/env/jdbc/database"); } catch (NamingException e) { e.printStackTrace(); } } public long getUserID() { return userID; } public void setUserID(long userID) { this.userID = userID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getCreated_date() { return created_date; } public void setCreated_date(Date created_date) { this.created_date = created_date; } public String add() { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); int i = 0; if (userID != 0) { PreparedStatement ps = null; Connection con = null; try { if (ds != null) { con = ds.getConnection(); if (con != null) { String sql = "INSERT INTO user1(userId, name, address, created_date) VALUES(?,?,?,?)"; ps = con.prepareStatement(sql); ps.setLong(1, userID); ps.setString(2, name); ps.setString(3, address); if (created_date != null) { String date = fmt.format(created_date); Object obj = date; if (obj == null) { ps.setDate(4, null); } else { java.sql.Date dt = java.sql.Date .valueOf(new String(date)); ps.setDate(4, dt); } } i = ps.executeUpdate(); System.out.println("Data Added Successfully"); } } } catch (Exception e) { System.out.println(e); } finally { try { con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } if (i > 0) { return "output"; } else { return "invalid"; } } else { return "invalid"; } } }
context.xml
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/database" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/record"/> </Context>
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/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>jsfJdbcWithConnectionResource</display-name> <welcome-file-list> <welcome-file>/insert.xhtml</welcome-file> </welcome-file-list> <resource-ref> <description>Database for User</description> <res-ref-name>jdbc/database</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> <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> <url-pattern>*.jsf</url-pattern> <url-pattern>*.xhtml</url-pattern> <url-pattern>*.jsp</url-pattern> </servlet-mapping> <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>client</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>resources.application</param-value> </context-param> <listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> </web-app>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?> <faces-config 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_2_0.xsd" version="2.0"> <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class>com.dev.user.model.User</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <description>add user</description> <from-view-id>/insert.xhtml</from-view-id> <navigation-case> <from-action>#{user.add}</from-action> <from-outcome>output</from-outcome> <to-view-id>/output.xhtml</to-view-id> </navigation-case> <navigation-case> <from-action>#{user.add}</from-action> <from-outcome>invalid</from-outcome> <to-view-id>/invalid.xhtml</to-view-id> </navigation-case> </navigation-rule> </faces-config>
insert.xhtml
<!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"> <h:head> <title>Insert Data</title> </h:head> <h:body> <f:view> <h:form> <table> <tr> <td> <h:messages showDetail="true" /> </td> </tr> <tr> <td><h:outputText value="Enter Id : "/></td> <td><h:inputText value="#{user.userID}"/></td> </tr> <tr> <td><h:outputText value="Enter Name : " /></td> <td><h:inputText value="#{user.name}" /></td> </tr> <tr> <td><h:outputText value="Enter your address : "/></td> <td><h:inputText value="#{user.address}" /></td> </tr> <tr> <td><h:outputText value="Enter Created Date : "/></td> <td><h:inputText value="#{user.created_date}"> <f:convertDateTime pattern="yyyy-MM-dd"/> </h:inputText></td> </tr> <tr> <td></td> <td><h:commandButton value="Insert" action="#{user.add}"/></td> </tr> </table> </h:form> </f:view> </h:body> </html>
output.xhtml
<!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"> <h:body> <h:outputText value="Value added to database successfully."/> </h:body> </html>
invalid.xhtml
<!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"> <h:body> <h:form> <h:outputText value="Error into adding data "/> <h:outputLink value="insert.xhtml">Try Again</h:outputLink> </h:form> </h:body> </html>
Output :
1. Before inserting the data into the database table lets assumed that there is no record in the table and it is like as follows :
2. And when you will execute the above discussed example you will see the home page as follows :
3. Input some data into the corresponding fields and click on insert button like as follows :
4. After clicking on insert button if, the data will be added successfully then the output will be as follows :
And the database table will be look like as follows :
5. And if any error occurred during insertion of record into the database table then the output will be as follows :
Here I have tried to reinsert the record with the id = 1 which is a declared as primary key in the database table so it throws the 'Duplicate entry for the primary key' sql exception and due to this data can not be inserted into the table and output is :
[ 0 ] Comments