Você está na página 1de 10

JSF With MySQL Database

1.Create a table in MySQL database CREATE TABLE `customer` ( `CUSTOMER_ID` varchar(20), `NAME` varchar(100), `ADDRESS` varchar(255), `CREATED_DATE` varchar(100) , PRIMARY KEY (`CUSTOMER_ID`) ) 2.Create a Web Project As earlier i mentioned 3.Create a package com.customer.model under src folder 4.Create InsertCustomer.java bean file under com.customer.model folder for getter & setter method. 5.create Customer.java bean file under com.customer.model folder for getter & setter method. 6.configure those bean file in faces-config.xml file. 7.Create JDBC connection class & copy mysql-connector-java-5.1.18-bin.jar and paste into WEB_INF/lib folder 8.create two jsp file insert.jsp and myJSFDATA.jsp WebApp will be look like

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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Jsf_Mysql</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</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> </servlet-mapping> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>resources.application</param-value> </context-param> <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> <description> This parameter tells MyFaces if javascript code should be allowed in the rendered HTML output. If javascript is allowed, command_link anchors will have javascript code that submits the corresponding form. If javascript is not allowed, the state saving info and nested parameters will be added as url parameters. Default is 'true'</description> <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name> <param-value>true</param-value> </context-param> <context-param> <description> If true, rendered HTML code will be formatted, so that it is 'humanreadable' i.e. additional line separators and whitespace will be written, that do not influence the HTML code. Default is 'true'</description> <param-name>org.apache.myfaces.PRETTY_HTML</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name> <param-value>false</param-value> </context-param> <context-param> <description> If true, a javascript function will be rendered that is able to restore the former vertical scroll on every request. Convenient feature if you have pages with long lists and you do not want the browser page to always jump to the top

if you trigger a link or button action that stays on the same page. Default is 'false' </description> <param-name>org.apache.myfaces.AUTO_SCROLL</param-name> <param-value>true</param-value> </context-param> <listener> <listenerclass>org.apache.myfaces.webapp.StartupServletContextListener</listenerclass> </listener> </web-app>

faces-config.xml
<?xml version="1.0" encoding="UTF-8"?> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" 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"> <managed-bean> <managed-bean-name>customer</managed-bean-name> <managed-bean-class>com.customer.model.Customer</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>insertCustomer</managed-bean-name> <managed-bean-class>com.customer.model.InsertCustomer</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/insert.jsp</from-view-id> <navigation-case> <from-outcome>Success</from-outcome> <to-view-id>/myJSFDATA.jsp</to-view-id> <redirect/> </navigation-case> </navigation-rule> </faces-config>

Customer.java
package com.customer.model; import import import import import import import import java.sql.CallableStatement; java.sql.Connection; java.sql.ResultSet; java.sql.SQLException; java.sql.Statement; java.util.ArrayList; java.util.Date; java.util.List;

public class Customer {

Connection con1 = null; CallableStatement call= null; ResultSet result = null; Statement stmt = null; private List custInfoAll = new ArrayList(); //connect to DB and get customer list public List getCustomerList() throws SQLException{ Labcon lc = new Labcon(); con1 = lc.getLocalConnection(); stmt=con1.createStatement(); String strSql="select customer_id, name, address, created_date from customer order by customer_id asc"; System.err.println("****"+strSql); result=stmt.executeQuery(strSql); while(result.next()){ custInfoAll.add(new CusomerInfo(result.getString(1),result.getString(2),result.getString(3),resul t.getString(4))); } return custInfoAll; } public class CusomerInfo { public String customerID; public String name; public String address; public String created_date; public CusomerInfo(String customerID,String name,String address,String created_date) { this.customerID = customerID; this.name = name; this.address = address; this.created_date = created_date; } public String getCustomerID() { return customerID; } public String getName() { return name; } public String getAddress() { return address; } public String getCreated_date() { return created_date; }

} }

InsertCustomer.java
package com.customer.model; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement;

public class InsertCustomer { public String customerID; public String getCustomerID() { return customerID; } public void setCustomerID(String customerID) { this.customerID = customerID; } 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 String getCreated_date() { return created_date; } public void setCreated_date(String created_date) { this.created_date = created_date; } public String name; public String address; public String created_date; public String addAction() throws SQLException { try { Connection con1 = null; Statement stmt = null; Labcon lc = new Labcon(); con1 = lc.getLocalConnection(); stmt = con1.createStatement(); String custid=this.customerID; String custname=this.name; String custadd=this.address; String custdt=this.created_date;

String query = "insert into customer(customer_id, name, address, created_date) values ('"+custid+"','"+custname+"','"+custadd+"','"+custdt+"')"; System.out.println("insert query is--" +query); stmt.executeUpdate(query); }catch(Exception ex){ System.out.println("Exception is:-"+ex.getMessage());

} return "Success"; } }

Labcon.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Labcon { Connection con = null; public Connection getLocalConnection() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root") ; } catch (ClassNotFoundException e) { System.err.println("ClassNotFoundException in getConnection, " + e.getMessage()); } catch (SQLException e) {

System.err.println("SQLException in getConnection, " + e.getMessage()); } return con; } public void setConnectionClose() throws SQLException { con.close(); } }

insert.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ 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"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <f:view> <h:form id="insertCustomer"> <table> <tr><td> <h:outputLabel value="CustomerID---"/> <h:message id="customerIDMessage" for="customerID" style="color:red;" /> <h:inputText id="customerID" value="#{insertCustomer.customerID}" required="true"/> </td></tr><tr><td> <h:outputLabel value="Name---"/> <h:message id="nameMessage" for="name" style="color:red;" /> <h:inputText id="name" value="#{insertCustomer.name}" required="true"/> </td></tr><tr><td> <h:outputLabel value="Address---"/> <h:message id="addressMessage" for="address" style="color:red;" /> <h:inputText id ="address" value="#{insertCustomer.address}" required="true"/> </td></tr><tr><td> <h:outputLabel value="Creation Date---"/> <h:message id="created_dateMessage" for="created_date" style="color:red;" /> <h:inputText id="created_date" value="#{insertCustomer.created_date}" required="true"/> </td></tr> </table> <h:commandButton value="Add" action="#{insertCustomer.addAction}" /> </h:form> </f:view>

</body> </html>

myJSFDATA.jsp
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <f:view> <html> <head> <link rel="stylesheet" type="text/css" href="css/table-style.css" /> </head> <h:dataTable value="#{customer.customerList}" var="c" styleClass="order-table" headerClass="order-table-header" rowClasses="order-table-odd-row,order-table-even-row"> <h:column> <f:facet name="header"> <h:outputText value="Customer ID" /> </f:facet> <h:outputText value="#{c.customerID}" > </h:outputText> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Name" /> </f:facet> <h:outputText value="#{c.name}" > </h:outputText> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Address" /> </f:facet> <h:outputText value="#{c.address}" > </h:outputText> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Creation Date" /> </f:facet> <h:outputText value="#{c.created_date}" > </h:outputText> </h:column> </h:dataTable> </html></f:view>

Then run insert.jsp file

Você também pode gostar