Wednesday, 9 November 2011

Struts2 UI Example


Struts 2 -> UI Example

Index.jsp
Register.jsp
Success.jsp
Struts.xml
Web.xml
Country.java
RegisterAction.java


Following figure show the struts 2 application structure.       






web.xml

web.xml is used to configure the servlet container properties of the First Simple appliation. The filter and the filter-mapping elements are used to setup the Struts 2 FilterDispatcher. The filter is mapped to the URL pattern "/*". This means all the incoming request that targets to the Struts 2 action will be handled by FilterDispatcher class.


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>


struts.xml

 

<!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">
           <action name="*Register" method="{1}" class="com.RegisterAction">
                <result name="success">/success.jsp</result>
                <result name="populate">/register.jsp</result>
           </action>
     </package>
</struts>

Com.RegisterAction -> RegisterAction is a class where you can write the action for the form.
In action tag * Register means you can call RegisterAction class using (e.g insertRegister,updateRegister etc) in place of * you can write any thing.



Index.jsp
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=populateRegister.action">
Register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
            pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Form</title>
</head>
<body>
<table border="1" align="center">
<s:form action="Register">
<tr>
<td><s:textfield name="userName" label="User Name"></s:textfield></td>
</tr>
<tr>
<td><s:password name="password" label="Password"></s:password></td>
</tr>
<tr>
<td><s:radio list="{'Male','Female'}" name="gender"           label="Gender"></s:radio></td>
</tr>
<tr>
<td><s:textarea name="address" label="Address"></s:textarea></td>
</tr>
<tr>
<td><s:select list="countryList" name="country" label="Country"
            listKey="countryId" listValue="countryName" headerKey="0"
                                                headerValue="Country"></s:select></td>
</tr>
<tr>
<td><s:checkbox name="licence" label="Licence Agreement"></s:checkbox></td>
</tr>
<tr>
<td><s:checkboxlist list="hobbyList" name="hobby"
                        label="Hobbies"></s:checkboxlist></td>
</tr>
<tr>
<td><s:submit value="Register" /></td>
</tr>
</s:form>
</table>
</body>
</html>

If you want to store static value in combo box then write (list = “’a’,’b’,’c’”)
->listKey is store as a comb obox value and listValue is display in combo box and header value is by default display in combo box.

Success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Successfully Register</title>
</head>
<body>
User Name : <s:property value="userName"/></br>
Password : <s:property value="password"/></br>
Gender : <s:property value="gender"/></br>
Address : <s:property value="address"/><br>
Country : <s:property value="country"/></br>
Licence : <s:property value="licence"/></br>
Hobbies : <s:property value="hobby"/>
</body>
</html>


Country.java

package com;

public class Country {

     public Country(int countryId, String countryName) {
           this.countryId = countryId;
           this.countryName = countryName;
     }

     private int countryId;
    
     private String countryName;

     public int getCountryId() {
           return countryId;
     }

     public void setCountryId(int countryId) {
           this.countryId = countryId;
     }

     public String getCountryName() {
           return countryName;
     }

     public void setCountryName(String countryName) {
           this.countryName = countryName;
     }
}


RegisterAction.java

package com;

import java.util.ArrayList;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport{

     private String userName;
    
     private String password;
    
     private String gender;
    
     private String address;
    
     private Boolean licence;
    
     private String[] hobby;
    
     private ArrayList<String> hobbyList;
    
     private String country;
    
     private ArrayList<Country> countryList;
    
     public ArrayList<Country> getCountryList() {
           return countryList;
     }

     public void setCountryList(ArrayList<Country> countryList) {
           this.countryList = countryList;
     }

     public String getCountry() {
           return country;
     }

     public void setCountry(String country) {
           this.country = country;
     }

     public String[] getHobby() {
           return hobby;
     }

     public void setHobby(String[] hobby) {
           this.hobby = hobby;
     }

     public ArrayList<String> getHobbyList() {
           return hobbyList;
     }

     public void setHobbyList(ArrayList<String> hobbyList) {
           this.hobbyList = hobbyList;
     }

     public Boolean getLicence() {
           return licence;
     }

     public void setLicence(Boolean licence) {
           this.licence = licence;
     }

     public String getAddress() {
           return address;
     }

     public void setAddress(String address) {
           this.address = address;
     }

     public RegisterAction(){
          
     }
    
     public String execute(){
           return "success";
     }
    
     public String populate(){
           hobbyList = new ArrayList<String>();
           hobbyList.add("Cricket");
           hobbyList.add("Music");
           hobbyList.add("Reading");
          
           countryList = new ArrayList<Country>();
           countryList.add(new Country(1,"India"));
           countryList.add(new Country(2,"USA"));
           countryList.add(new Country(3,"Pakistan"));
          
           return "populate";
     }

     public String getUserName() {
           return userName;
     }

     public String getGender() {
           return gender;
     }

     public void setGender(String gender) {
           this.gender = gender;
     }

     public void setUserName(String userName) {
           this.userName = userName;
     }

     public String getPassword() {
           return password;
     }

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




Learn more java tutorial and java blog visit : Visions Developer

Wednesday, 2 November 2011

Struts 2 Simple Example


Struts 2 -> First Simple Application

Login.java
Index.jsp
Success.jsp
Struts.xml
Web.xml


Following figure show the struts 2 application structure.


 web.xml
web.xml is used to configure the servlet container properties of the First Simple appliation. The filter and the filter-mapping elements are used to setup the Struts 2 FilterDispatcher. The filter is mapped to the URL pattern "/*". This means all the incoming request that targets to the Struts 2 action will be handled by FilterDispatcher class.


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>


We can change welcome fiel name like register.jsp or login.jsp

struts.xml

 

<!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">
        <action name="Login" class="com.Login">
            <result name="SUCCESS">/success.jsp</result>
        </action>
    </package>
</struts>

 

Index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login Page</title>
    </head>
    <body>
        <s:form action="Login">
            <s:textfield name="userName" label="User Name"></s:textfield>
            <s:submit name="submit" value="Submit"></s:submit>
        </s:form>
    </body>
</html>


Login.java

package com;

public class Login {
      private String userName;

      public Login(){
           
      }
     
      public String execute(){
            return "SUCCESS";
      }
      public String getUserName() {
            return userName;
      }

      public void setUserName(String userName) {
            this.userName = userName;
      }
     
}


Success.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login Information</title>
    </head>
    <body>
        <h1><s:property value="userName" /></h1>
    </body>
</html>


Type the following url in the browser "http://localhost:8080/Example1/index.jsp". The index page will be displayed.


Enter the user name and submit the form. Welcome <<user name>> message will be displayed.


Tuesday, 18 October 2011

Refresh Image Automatic from specific Folder.

If you click on start button then image refresh start and after every 3 min image change.


image.jsp
<%@ page language="java" import="java.util.*"%>
<%
List list = new ArrayList();
for (int i=0; i<8; i++ ) {
list.add("./images/000"+(i+1)+".jpg");
}
%>
<html>
<head>
<script language="JavaScript">
var i=0;
var ar = new Array();
<% for (int i=0; i<8; i++ ) { %>
ar['<%=i%>'] = '<%=(String) list.get(i)%>';
<% } %>

function MyTime() {
var img1 = document.getElementById("img1");
img1.src = ar[i];
i++;
if (i==6) i = 0;
setTimeout("MyTime()",3000);
}
</script>
</head>
<body>
<img src="./images/0001.jpg" height="200" width="200" id="img1" name="img1"/><br />
</br><br />
</br>
<form name="form1">
<input type="button" id = "btn1" name="btn1" value = "Start" onclick="MyTime()">

</form>
</body>
</html>

Auto Fill Combobox in JSP using Ajax

Data Base Design

Database Name : country
Table : Country
create table country(
id int,
name varchar(30)
);

Table : State
create table state(
id int,
name varchar(30),
cid int
);

Table : City
create table city(
id int,
name varchar(30),
sid int
);

Code:

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>

<script type="text/javascript">
function getState()
{
var xmlHttp;
var x = document.getElementById("fillState");
x.length = 0;
document.getElementById("fillCity").length = 0;

if(x.value!=-1){
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
        var showdata = xmlHttp.responseText;
        var str = showdata.split(":");
        var len = str.length;
          var i =0;
          for(i=0;i<len;){
              var option=document.createElement("option");
            option.text= str[i];
            option.value = str[i+1];
            try
              {
              // for IE earlier than version 8
              x.add(option,x.options[null]);
              }
            catch (e)
              {
              x.add(option,null);
              }
            i=i+2;
          }
      }
    }
  var val = document.getElementById("fillCountry").value;
  var url = "getOption.jsp?opt="+val+"&table=state";
  xmlHttp.open("GET",url,true);

  xmlHttp.send(null);
}

  }
 
  function getCity(){
      var xmlHttp;
      var x = document.getElementById("fillCity");
      x.length = 0;

      if(x.value!=-1){
      try
        {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
        }
      catch (e)
        {
        // Internet Explorer
        try
          {
          xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
          }
        catch (e)
          {
          try
            {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
          catch (e)
            {
            alert("Your browser does not support AJAX!");
            return false;
            }
          }
        }
        xmlHttp.onreadystatechange=function()
          {
          if(xmlHttp.readyState==4)
            {
              var showdata = xmlHttp.responseText;
              var str = showdata.split(":");
              var len = str.length;
                var i =0;
                for(i=0;i<len;){
                    var option=document.createElement("option");
                  option.text= str[i];
                  option.value = str[i+1];
                  try
                    {
                    // for IE earlier than version 8
                    x.add(option,x.options[null]);
                    }
                  catch (e)
                    {
                    x.add(option,null);
                    }
                  i = i+2;
                }
            }
          }
        var val = document.getElementById("fillState").value;
        var url = "getOption.jsp?opt="+val+"&table=city";
        xmlHttp.open("GET",url,true);

        xmlHttp.send(null);
      }
  }
</script>
<table>
<form name="myForm">
<%
Connection con = null;
Statement stat = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/country";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "dreams";
try {
    Class.forName(driver).newInstance();
    con = DriverManager.getConnection(url, userName, password);
    stat = con.createStatement();
    rs = stat.executeQuery("Select * from Country");
%>
<tr>
<td>Country : </td>
<td>
<select id ="fillCountry" onChange="getState();">
<option value=-1>Select</option>
<%
    while(rs.next()){
        out.println("<option value="+rs.getString(1)+">"+rs.getString(2)+"</option>");
    }
}
catch (Exception e) {
    e.printStackTrace();
}

%>
</select>
</td>
</tr>
<tr>
<td>State : </td>
<td>
<select id = "fillState" onChange = "getCity();">
<option>Select</option>
</select>
</td>
</tr>
<tr>
<td>City : </td>
<td>
</select>
<select id = "fillCity">
<option>Select</option>
</select>
</td>
</tr>
</form>
</table>
</body>
</html>


getOption.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.sql.*"%>

<%
Connection con = null;
Statement stat = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/country";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "dreams";
int id = Integer.parseInt(request.getParameter("opt"));
String table = request.getParameter("table");
try {
    Class.forName(driver).newInstance();
    con = DriverManager.getConnection(url, userName, password);
    stat = con.createStatement();
    if(table.equals("state")){
        rs = stat.executeQuery("Select * from state where cid = "+id);
    }else if(table.equals("city")){
        rs = stat.executeQuery("Select * from city where sid = "+id);
    }
    String str = "";
    while(rs.next()){
        str = str + rs.getString(2) + ":";
        str = str + rs.getString(1) + ":";
    }
    str = str.substring(0,str.length()-1);
    out.println(str);
}
catch (Exception e) {
    e.printStackTrace();
}

%>