22 Oct 2016

Inserting Data into Database using Java Web Application (Building Java Web Application Part III)

Step 1: Create DataController.java class in controller package including logic for both inserting as well as viewing the inserted data

 

DataController.java Code:

 package engdictionary.controller;  
   
 import java.io.IOException;  
 import java.sql.Connection;  
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 import java.sql.Statement;  
 import java.util.ArrayList;  
 import java.util.List;  
   
 import com.opensymphony.xwork2.ActionSupport;  
 import com.opensymphony.xwork2.ModelDriven;  
   
 import engdictionary.model.WordModel;  
 import engdictionary.connection.DbConnection;  
   
 public class DataController extends ActionSupport implements ModelDriven<WordModel> {  
      WordModel model = new WordModel();  
      List<WordModel> words = new ArrayList<WordModel>();  
      public WordModel getModel() {  
           return model;  
      }  
      public void setModel(WordModel model) {  
           this.model = model;  
      }  
             
      public List<WordModel> getWords() {  
           return words;  
      }  
      public void setWords(List<WordModel> words) {  
           this.words = words;  
      }  
      public String addWord() throws ClassNotFoundException,IOException  
      {  
           try {  
                Connection con = DbConnection.getConnection();  
                String query = "insert into tbl_word (word,type,meaning1,meaning2,meaning3,comment) values (?,?,?,?,?,?)";  
                PreparedStatement ps = con.prepareStatement(query);  
                ps.setString(1, model.getWord());  
                ps.setString(2, model.getWord_type());  
                ps.setString(3, model.getMeaning1());  
                ps.setString(4, model.getMeaning2());  
                ps.setString(5, model.getMeaning3());  
                ps.setString(6, model.getComment());  
                ps.executeUpdate();  
                return ERROR;  
           }   
           catch (SQLException e) {  
                // TODO: handle exception  
           e.printStackTrace();  
           }  
           return SUCCESS;  
      }  
   
      public String viewWord() throws ClassNotFoundException,IOException  
      {  
           try {  
                  
                Connection con = DbConnection.getConnection();  
                Statement st;  
                  
                st = con.createStatement();  
                ResultSet rs = st.executeQuery("select * from tbl_word");  
                WordModel model = null;  
                while(rs.next()){  
                     model = new WordModel();  
                     model.setWord(rs.getString("word"));  
                     model.setWord_type(rs.getString("type"));  
                     model.setMeaning1(rs.getString("meaning1"));  
                     model.setMeaning2(rs.getString("meaning2"));  
                     model.setMeaning3(rs.getString("meaning3"));  
                     model.setComment(rs.getString("comment"));  
                     words.add(model);            
                }  
                setWords(words);            
           } catch (SQLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           return SUCCESS;  
      }  
 }  

 

Step 2: Add the following action in struts.xml


 <action name="addWord" class="engdictionary.controller.DataController" method="addWord">  
                <result name="success" type="tiles">add.tiles</result>  
                <result name="error" type="tiles">add.tiles</result>  
           </action>  

 

Step 3: Add action argument to the form tag in add.jsp


 <form name="f1" method="post" action="addWord.action" enctype="multipart/form-data">  
 .  
 .  
 </form  

 

Step 4: Inserting the data in add.jsp


 

Step 5: Viewing the data

Step 5.1: Update the code of <tbody /> tag in view.jsp with the following code.

 <tbody>  
             <s:iterator value="words">  
              <tr>  
                   <td><s:property value="word"/></td>  
                   <td><s:property value="word_type"/></td>  
                   <td><s:property value="meaning1"/></td>  
                   <td><s:property value="meaning2"/></td>  
                   <td><s:property value="meaning3"/></td>  
                   <td><s:property value="comment"/></td>  
              </tr>   
         </s:iterator>    
        </tbody>  

Step 5.2: Add class and method arguments to action named view in struts.xml.

 <action name="view" class="engdictionary.controller.DataController" method="viewWord">  
                <result type="tiles">view.tiles</result>  
           </action>  

Step 5.3: View inserted data by running the web application.



Database Connectivity and Iterating Values in Drop-down List from Database (Building Java Web Application Part II)

Step 1: Creating connection class (DbConnection.java) in connection package

DbConnection.java code:

 package engdictionary.connection;  
   
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.SQLException;  
   
 public class DbConnection {  
      static Connection con;       
      public static Connection getConnection() throws ClassNotFoundException  
      {            
           try  
           {  
                Class.forName("com.mysql.jdbc.Driver");  
                con = DriverManager.getConnection("jdbc:mysql://localhost/db_english_dictionary","root","");  
           }  
           catch(SQLException e)  
           {  
           e.printStackTrace();       
           }  
      return con;  
      }  
 }  

Step 2: Creating model classes in model package for every relation (table) in the database

Step 2.1: Declare the variables corresponding to the fields in the relation. Note that every relation will have its own individual model class.


Step 2.2: Generate Getters and Setters of variables as shown below:


Select All the variables and press OK button.


Similarly create the model class for another relation in our database.

I have created TypeModel.java and WordModel.java model classes corresponding to tbl_type and tbl_word relations in the database db_english_dictionary, respectively. 

TypeModel.java code:

 package engdictionary.model;  
   
 public class TypeModel {  
 String type,abbr;  
   
 public String getType() {  
      return type;  
 }  
   
 public void setType(String type) {  
      this.type = type;  
 }  
   
 public String getAbbr() {  
      return abbr;  
 }  
   
 public void setAbbr(String abbr) {  
      this.abbr = abbr;  
 }  
 }  
   

WordModel.java code:

 package engdictionary.model;  
   
 public class WordModel {  
 String word,type,meaning1,meaning2,meaning3,comment;  
   
 public String getWord() {  
      return word;  
 }  
   
 public void setWord(String word) {  
      this.word = word;  
 }  
   
 public String getType() {  
      return type;  
 }  
   
 public void setType(String type) {  
      this.type = type;  
 }  
   
 public String getMeaning1() {  
      return meaning1;  
 }  
   
 public void setMeaning1(String meaning1) {  
      this.meaning1 = meaning1;  
 }  
   
 public String getMeaning2() {  
      return meaning2;  
 }  
   
 public void setMeaning2(String meaning2) {  
      this.meaning2 = meaning2;  
 }  
   
 public String getMeaning3() {  
      return meaning3;  
 }  
   
 public void setMeaning3(String meaning3) {  
      this.meaning3 = meaning3;  
 }  
   
 public String getComment() {  
      return comment;  
 }  
   
 public void setComment(String comment) {  
      this.comment = comment;  
 }  
   
 }  
   

Step 3: Creating type controller class (TypeController.java) in controller package

We are creating TypeController.java in order to iterate values of tbl_type into the following drop-down list. Controller classes comprises of the actual logic.


TypeController.java code:

 package engdictionary.controller;  
   
 import java.io.IOException;  
 import java.sql.Connection;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 import java.sql.Statement;  
 import java.util.ArrayList;  
 import java.util.List;  
   
 import com.opensymphony.xwork2.ActionSupport;  
 import com.opensymphony.xwork2.ModelDriven;  
   
 import engdictionary.model.TypeModel;  
 import engdictionary.connection.DbConnection;  
   
 public class TypeController extends ActionSupport implements ModelDriven<TypeModel> {  
      TypeModel model = new TypeModel();  
      List<TypeModel> word_type = new ArrayList<TypeModel>();  
        
      public TypeModel getModel() {  
           return model;  
      }  
      public void setModel(TypeModel model) {  
           this.model = model;  
      }  
        
      public List<TypeModel> getWord_type() {  
           return word_type;  
      }  
      public void setWord_type(List<TypeModel> word_type) {  
           this.word_type = word_type;  
      }  
      public String viewType() throws ClassNotFoundException,IOException  
      {  
           try {            
                Connection con = DbConnection.getConnection();  
                Statement st;  
                  
                st = con.createStatement();  
                ResultSet rs = st.executeQuery("select * from tbl_type");  
                TypeModel model = null;  
                while(rs.next()){  
                     model = new TypeModel();  
                     model.setType(rs.getString("type"));  
                     model.setAbbr(rs.getString("abbr"));  
                     word_type.add(model);            
                }  
                setWord_type(word_type);            
           } catch (SQLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();       
           }  
           return SUCCESS;  
      }  
 }  
   

Step 4: Iterating the values

Step 4.1: Add the following lines at the top of add.jsp (page comprising the drop-down list).

 <%@ taglib uri="/struts-tags" prefix="s" %>  
   <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="t" %>  

Step 4.2: Update <select /> block with the following code:

 <select type="text" name="word_type" style="height:auto;" onfocus='this.size=8;' onblur='this.size=1;' onchange='this.size=1;this.blur();'>  
          <option value="none">~Choose the word type~</option>  
               <s:iterator value="word_type">  
                               <option value="<s:property value="abbr"/>"><s:property value="type"/></option>   
               </s:iterator>  
          </select>  

add.jsp code:

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
   <%@ taglib uri="/struts-tags" prefix="s" %>  
   <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="t" %>  
 <!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>  
 <div class="container">  
      <div class="for_title"><span id="add_title">Add A New Word</span></div>  
      <hr/>  
      <form name="f1" method="post" enctype="multipart/form-data">  
        <div class="col">  
       <div class="label">New Word:<sup>*</sup></div>  
        <div class="field">  
        <input type="text" name="word" placeholder="Enter the word"/>  
        </div>  
        </div>  
          
        <div class="col">  
       <div class="label">Type:<sup>*</sup></div>  
        <div class="field">  
        <select type="text" name="word_type" style="height:auto;" onfocus='this.size=8;' onblur='this.size=1;' onchange='this.size=1;this.blur();'>  
          <option value="none">~Choose the word type~</option>  
               <s:iterator value="word_type">  
                               <option value="<s:property value="abbr"/>"><s:property value="type"/></option>   
               </s:iterator>  
          </select>  
        </div>  
        </div>  
          
        <div class="col">  
       <div class="label">Meaning 1:<sup>*</sup></div>  
        <div class="field">  
        <input type="text" name="meaning1" placeholder="Enter the meaning"/>  
        </div>  
        </div>  
          
        <div class="col">  
       <div class="label">Meaning 2:</div>  
        <div class="field">  
        <input type="text" name="meaning2" placeholder="Enter the second meaning (optional)"/>  
        </div>  
        </div>  
          
        <div class="col">  
       <div class="label">Meaning 3:</div>  
        <div class="field">  
        <input type="text" name="meaning3" placeholder="Enter the third meaning (optional)"/>  
        </div>  
        </div>  
     
        <div class="col">  
       <div class="label">Comment:</div>  
        <div class="field">  
        <input type="text" name="comment" placeholder="Enter the special comment (if any)"/>  
        </div>  
        </div>  
          
        <div class="col">  
         <button type="submit" onClick="return validation()">Add</button>  
        </div>  
      </form>  
    </div>  
 </body>  
 </html>  

Step 4.3: Add class and method arguments to action named add in struts.xml.

 <action name="add" class="engdictionary.controller.TypeController" method="viewType">  
                <result type="tiles">add.tiles</result>  
           </action>  

Step 4.4: Run the project and you will see the iterated values in the drop-down list as follows.


21 Oct 2016

Integrating web pages in Eclipse IDE (Building Java Web Application Part I)

Apparatus:

  • Eclipse Java EE IDE for Web Developers. Version: Luna Service Release 2 (4.4.2)
  • Apache Tomcat Server / XAMPP
  • Java Development Kit
  • Java Runtime Environment

Steps:

Step 1: Creating New Project

Step 1.1: Start the Eclipse IDE.
Step 1.2: Select File > New > Dynamic Web Project.


A wizard will pop up as shown below. Give the Project name EnglishDictionary. Select the Target runtime. If the server is not configured, select New Runtime... button. We will learn configuring Apache Tomcat server later.


On pressing Next > button, we will have the following step. Check the Generate web.xml deployment descriptor and click Finish button. You have created your project in the eclipse workspace.

Step 2: Configuring Apache Tomcat Server

On clicking New Runtime... button, you will get the following window. Select Apache Tomcat version as per your requirement and click the Next > button.


You will get the following window. Specify the installation directory where actually Apache Tomcat server is installed in C drive by clicking the Browse... button. Then click the Finish button. Your server is now configured.

Step 3: Adding Web App Libraries to Project (Libraries of MySQL Connector, Struts, and Tiles)

Step 3.1: Copy the following 23 library files at the following location:
D:\java_16t016\EnglishDictionary\WebContent\WEB-INF\lib
D:\java_16t016 is my Eclipse workspace location.

Step 3.2: Refresh the workspace. You will be able to see the added libraries.


Step 3.3: Configure Build Path by right clicking on the project and then selecting Build Path > Configure Build Path....


Before pressing OK button, never forget to check the Targeted Runtimes as shown below.

 

Step 4: Creating the Packages as per the MVC (Model View Controller) Architecture

Right click on the src package as shown below in the directory tree.


Create new package engdictionary by selecting New > Package as shown below. 


Add sub packages connection, controller, and model to package engdictionary as shown below.


Configure Build Path after creating the MVC packages. It will look like as shown below.


Step 5: Actually Integrating the Web Pages

Step 5.1: Create the sub folders dictFiles and dictPages in WebContent folder of project.
dictFiles will contain js and css folders whereas dictPages will contain actual jsp pages.

Step 5.2: Copy the js and css folders from your design template to dictFiles.

Step 5.3: Create header.jsp, footer.jsp, and container.jsp pages in dictPages folder.

Step 5.4: Copy the header content, footer content, and home page (or any other page) content into header.jsp, footer.jsp, and container.jsp respectively.

Step 5.5: Create dictContent.jsp in WebContent folder which will contain all the css and js linkings.

dictContent.jsp Code:

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
   <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <link rel="stylesheet" type="text/css" href="dictFiles/css/dictionary.css"/>  
 <script type="text/javascript" src="dictFiles/js/validate.js"></script>  
 <title><tiles:insertAttribute name="title"/></title>  
 </head>  
   
 <body>  
      <section id="container">  
           <tiles:insertAttribute name="header"/>  
           <tiles:insertAttribute name="container"/>  
           <tiles:insertAttribute name="footer"/>  
      </section>  
 </body>  
 </html>  

Step 5.6: Change the css and js linkings into the web page and check using Ctrl key and mouse. If the linking will be successfully done, then an underline will appear below the link as shown below.


Create another jsp pages in the same manner.

Step 5.7: Create tiles.xml file in WEB-INF folder.

tiles.xml Code:

 <?xml version="1.0" encoding="UTF-8"?>  
   
 <!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"  
  "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">  
 <tiles-definitions>  
   
      <definition name="maintemplate" template="/dictContent.jsp">  
           <put-attribute name="title" value="Welcome to English Dictionary" />  
           <put-attribute name="header" value="/dictPages/header.jsp" />  
           <put-attribute name="container" value="/dictPages/container.jsp" />  
           <put-attribute name="footer" value="/dictPages/footer.jsp" />       
      </definition>  
        
      <definition name="dictHome.tiles" extends="maintemplate">  
      </definition>  
        
      <definition name="abbreviations.tiles" extends="maintemplate">  
      <put-attribute name="title" value="Abbreviations"></put-attribute>       
           <put-attribute name="container" value="/dictPages/abbreviations.jsp"></put-attribute>  
      </definition>  
        
      <definition name="add.tiles" extends="maintemplate">  
      <put-attribute name="title" value="Add a new word"></put-attribute>       
           <put-attribute name="container" value="/dictPages/add.jsp"></put-attribute>  
      </definition>  
        
      <definition name="reference.tiles" extends="maintemplate">  
      <put-attribute name="title" value="Reference"></put-attribute>       
           <put-attribute name="container" value="/dictPages/reference.jsp"></put-attribute>  
      </definition>  
        
      <definition name="view.tiles" extends="maintemplate">  
      <put-attribute name="title" value="View"></put-attribute>       
           <put-attribute name="container" value="/dictPages/view.jsp"></put-attribute>  
      </definition>  
        
 </tiles-definitions>  

Step 5.8: Create struts.xml file in resources Source Folder in Java Resources Source Folder. You will have to create the resources Source Folder.

struts.xml Code:

 <?xml version="1.0" encoding="UTF-8" ?>  
 <!DOCTYPE struts PUBLIC  
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
        "http://struts.apache.org/dtds/struts-2.0.dtd">  
   
 <struts>  
      <package name="default" extends="struts-default" namespace="/">  
           <result-types>  
                <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />  
           </result-types>  
             
           <action name="abbreviations">  
                <result type="tiles">abbreviations.tiles</result>  
           </action>  
             
           <action name="home">  
                <result type="tiles">dictHome.tiles</result>  
           </action>  
             
           <action name="add">  
                <result type="tiles">add.tiles</result>  
           </action>  
             
           <action name="reference">  
                <result type="tiles">reference.tiles</result>  
           </action>  
             
           <action name="view">  
                <result type="tiles">view.tiles</result>  
           </action>  
      </package>  
 </struts>  

Step 5.9: Update web.xml file with the following code:

 <?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" 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>EnglishDictionary</display-name>  
  <welcome-file-list>  
   <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
  <filter>  
         <filter-name>action</filter-name>  
         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
      </filter>  
      <filter-mapping>  
         <filter-name>action</filter-name>  
         <url-pattern>*.action</url-pattern>  
      </filter-mapping>  
      <listener>  
             <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>  
       </listener>  
       <context-param>  
                 <param-name>tilesdefinitions</param-name>  
                 <param-value>/WEB-INF/tiles.xml</param-value>  
       </context-param>  
       <session-config>  
        <session-timeout>1</session-timeout>  
      </session-config>  
 </web-app>  

Step 5.10: Create index.jsp file in WebContent folder.

index.jsp Code:

 <META http-equiv="REFRESH" content="0; URL=home.action">  

Now your template is completely integrated. Never forget to build the path before running the web application.

Step 6: Running the Web Application:

To run the project on the server, right click on the project EnglishDictionary and select Run As > 1 Run on Server. Do not forget to start the server from XAMPP control panel before running the project.


The directory structure of the web application is as follows:


Note: Perform Step 3, after downloading the project and before proceeding to Step 7.

Step 7: After downloading the project, import it into the Eclipse IDE.

Step 7.1: To import the project, click File > Import... . You will get the following window. Select Existing Projects into Workspace and then click Next > button.


Step 7.2: In the next wizard, you will have to browse the project directory and click the Finish button as shown in the following snapshot.


Happy Java Web Application programming..!