JSF Insert Data Into Database Table

JSF Insert Data Into Database Table


Posted in : Java Posted on : October 22, 2012 at 12:18 PM Comments : [ 0 ]

In this section we will discuss about How to insert data to the Database table.

JSF Insert Data Into Database Table

In this section we will discuss about How to insert data to the Database table.

To insert the data into a table at first we will required to create a table in the database. Here I have created the table 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 I have created a project in Eclipse IDE where I have created a class named User.java which contains the data member userID, name, address, created_date, and their setter getter methods then created a method named add() where write the code for inserting the data. Then I have created an XHTML page named insert.xhtml using which I have created an User Interface to provide the data to insert into the table. When you will try to insert the data to the table after executing this example and if the data is added successfully to the table the add function will return the String 'output' and it will redirect to the output.xhtml page and if the data is not added to the table successfully then the add() function will return the String 'invalid' and it will redirect to the invalid.xhtml page. For the page redirection I have created a navigation-rule in faces-config.xml file

Directory Structure

User.java

package com.dev.user.model;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;


@ManagedBean(name="user")
@RequestScoped
public class User {

private long userID;
private String name;
private String address;
private Date created_date;

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
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/record", "root", "root");
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";
}
} 
}

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>

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>jsfJdbcInsert</display-name>
<welcome-file-list>
<welcome-file>/insert.xhtml</welcome-file>
</welcome-file-list>
<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>
</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>

Output

When you will execute the above example you will get the output as follows :

When you will provide the value to the textboxes then the output will be as follows :

When you will click on inset button then the output will be as follows :

An error page like if you will try to reinsert the value with duplicate id in the table then the output will be as follows :

And at the console you will see the message as follows :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics