Working with Database through JDBC

You can use JDBC to work with database. For this you can write JDBC code in the action method of the managed bean. Let's understand through an example.

Working with Database through JDBC

Working with Database through JDBC

        

You can use JDBC to work with database. For this you can write JDBC code in the action method of the managed bean. Let's understand through an example.

The code of jdbc.jsp

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

<html>
<head> 
<title>Login Page</title>
</head>
<body>
<f:view>
<h:form id="loginForm">
<center>
<br>
<h:outputText value="User Name or Password is incorrect." rendered="#{JdbcBean.error}" style="color:red"/>

<h:panelGrid columns="3" style="font-weight:bold;">
<h:outputText value="User Name"/>
<h:inputText id="uname" required="true" value="#{JdbcBean.username}"/>
<h:message for="uname" style="color:red"/>

<h:outputText value="Password" />
<h:inputSecret id="pwd" required="true" value="#{JdbcBean.password}"/> 
<h:message for="pwd" style="color:red"/>

<h:outputText value="" />
<h:commandButton value="Submit" action="#{JdbcBean.checkUserInDatabase}"/>

</h:panelGrid>
</center>
</h:form>
</f:view> 
</body>
</html>

Here the managed bean name is JdbcBean and checkUserInDatabase is the action method. Now the action method will contain the jdbc code to check whether the user name and password is authentic.

Here is the code of JdbcBean.java

package roseindia;

import java.sql.*;

public class JdbcBean {
public JdbcBean(){}

String username;
String password;

boolean error; 

public String getUsername() {
   return username;
}
public void setUsername(String username) {
   this.username = username;
}

public String getPassword() {
   return password;
}
public void setPassword(String password) {
   this.password = password;
}

public boolean isError() {
   return error;
}
public void setError(boolean error) {
   this.error = error;
}


public String checkUserInDatabase(){
   String returnString = "failure";

  Connection con = null;
  Statement st = null;
  try{
   Class.forName("com.mysql.jdbc.Driver");
   con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsfexamples","root","root");
   st = con.createStatement();
   ResultSet rs = st.executeQuery("select * from jsftable");

   while(rs.next()){ 
   if(username.equals(rs.getString(2)) && password.equals(rs.getString(2))){
   returnString = "success";
   break;
   }
  }
  if(returnString.equals("failure")){
   error = true;
  }
  }
  catch(Exception ex){
   ex.printStackTrace();
  }
  return returnString;
  }
}

Download code for all examples