শনিবার, ১৭ জুলাই, ২০১০

Java-MySQL Connection with Struts2

Hello everybody,

Here I will describe one by one steps to insert data in MySQL Database using struts2 and JAVA. This example project is build using NetBean 6.0. So it is more easy to those who has knowledge to use NetBean IDE.

After complete the project tree structure of the project folder will be as follows:





















Add all jar files need for struts and Database. Jar files can be added in two ways:
i) Copy all jar files to lib folder of Tomcat server
ii)RMC (Right Mouse Click) on Libraries folder on your project » Add Jar/Folder »Select jar files or the folder containing jar files

*** Following jar files needed to work with struts2 and MySQL

** commons-beanutils-core.jar

** commons-logging.jar

** struts2-core-2.0.11.jar

** xwork-2.0.4.jar

** ognl-2.6.11.jar

** mysql-connector-java-5.0.7-bin.jar

1.For create just a simple web project:
» New Project » Java Web » Web Application » Give a Project Name (Given SimpleStruts2)

2.Create a struts.xml file in the following way:
» RMC (Right Mouse Click) on in Source Packages » New » XML document » .... » then write the following code:

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="SimpleBrowserPage" extends="struts-default">

<action name="actionName" method="methodInJavaFile" class="com.Test.Action.JavaFileAction">

<result name="success">ForSuccess.jsp</result>

<result name="error">ForError.jsp</result>

</action>

</package>

</struts>

3. Create a form in the index.jsp. Code of index.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

<%--This line used for struts--%>

<!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=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1>Please insert Name and Email address</h1>

<form action="actionName.action" method="post">

Name:<input type="text" size="30" name="name"/><br/>

Email:<input type="text" size="30" name="email"/><br/>

<input type="submit" value="Submit"/>

</form>

</body>

</html>

4.Create a ForSuccess.jsp .Code of ForSuccess.jsp :

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

<%--This line used for struts--%>

<!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=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1>Insertion Success</h1>

Thank you, Mr. <s:property value="name"/>

</body>

</html>

5.Create a ForError.jsp .Code of ForError.jsp :

<%--

Document : ForError

Created on : Apr 9, 2009, 11:51:05 AM

Author : shahalom

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

<%--This line used for struts--%>

<!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=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1> Error:: <s:property value="%{message}"/></h1>

<h2>Please insert Name and Email address</h2>

<form action="actionName.action">

Name:<input type="text" size="30" name="name"/><br>

Email:<input type="text" size="30" name="email"/><br>

<input type="submit" value="Submit"/><br>

</form>

</body>

</html>

6.Create a package for java file :

RMC on Source Packages » New » Java Package » Write com.Test.Action.

7.Create a new Java file (name given ‘JavaFileAction.java’).Write the following code:

package com.Test.Action;

import com.opensymphony.xwork2.Action;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

/**

* @author shahalom

*/

public class JavaFileAction {

private String name;

private String email;

private String message;

public String methodInJavaFile() {

Connection con = null;

Statement stm = null;

try {

if (this.getName().equalsIgnoreCase("") || this.getEmail().equalsIgnoreCase("")) {

throw new Exception();

}

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "root", "aaa");

stm = con.createStatement();

String query = "insert into infoTable(name,email) values('" + this.getName() + "','" + this.getEmail() + "');";

System.out.println("****************** " + query);

stm.executeUpdate(query);

stm.close();

con.close();

} catch (Exception e) {

this.setMessage(e.getMessage());

return Action.ERROR;

}

return Action.SUCCESS;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

}

8. Replace the following code in web.xml file:

<?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>

9.Now Configure MySQL 5.1 to port#3306 and Run the following query in MySQL console:

--Create database

create database dbName;
use dbName;

--Create table
create table infoTable (
id int(5) unsigned NOT NULL auto_increment,
name varchar(30),
email varchar(30),
PRIMARY KEY (id));

Last of all, after trying this tutorial, if anbody need the example code/project, Just let me know I will try to send the example project. Thanks for visiting the blog.


বুধবার, ৯ ডিসেম্বর, ২০০৯

Dynamic Google Map with Struts2 Framework

Hello,

I am writing this blog using NetBean6.0 IDE with struts2 framework of JAVA. So, it will more easy for those web programmer who has knowledge of struts2 framework. Here I send a location district name, Country name to class file to get Latitude and Longtitude value from Google Web service. Then, in another jsp page I got those latitude and longtitude value through JavaScript Code and send to Google Server.

Library/Jar files to configure struts2 framework:

**** commons-logging-1.1.1.jar

**** commons-logging-adapters-1.1.1.jar

**** commons-logging-api-1.1.1.jar

**** commons-logging.jar

**** ezmorph-1.0.4.jar

**** freemarker-2.3.8.jar

**** jasper-jdt.jar

**** ognl-2.6.11.jar

**** struts2-core-2.0.11.jar

**** xwork-2.0.4.jar



Library/Jar files for google map:

**** bp-ui-14.jar

**** shale-remoting.jar



Step 1: Create a jsp file( name suppose-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">


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>

<body style="padding:10px 200px 10px 200px">
<h1>Hello World!</h1>
<div>

<form action="getGoogleMap.action">
<input type="text" name="location"><br>
<input type="submit" value="Show Map">
</form>
</div>


</body>
</html>


Step 2: Create a jsp file to send location (Suppose ShowGoogleMap.jsp)

<%@ taglib prefix="s" uri="/struts-tags" %>

<%@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">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

<script src="http://maps.google.com/maps?file=api&v=2&

key=GOOGLE API KEY" type="text/javascript"></script>

<script type="text/javascript">

var map;

var icon0;

var newpoints = new Array();

function addLoadEvent(func) {

var oldonload = window.onload;

if (typeof window.onload != 'function'){

window.onload = func

} else {

window.onload = function() {

oldonload();

func();

}

}

}

addLoadEvent(loadMap);

addLoadEvent(addPoints);

function loadMap() {

var latVal = document.getElementById("a").value;

var langVal = document.getElementById("b").value;

var zoomLebel = 11;

map = new GMap2(document.getElementById("map"));

map.addControl(new GLargeMapControl());

map.addControl(new GMapTypeControl());

map.setCenter(new GLatLng( latVal, langVal), zoomLebel);

map.setMapType(G_NORMAL_MAP);

icon0 = new GIcon();

icon0.image = "http://www.google.com/mapfiles/marker.png";

icon0.shadow = "http://www.google.com/mapfiles/shadow50.png";

icon0.iconSize = new GSize(20, 34);

icon0.shadowSize = new GSize(37, 34);

icon0.iconAnchor = new GPoint(9, 34);

icon0.infoWindowAnchor = new GPoint(9, 2);

icon0.infoShadowAnchor = new GPoint(18, 25);

}

function addPoints() {

var latVal = document.getElementById("a").value;

var langVal = document.getElementById("b").value;

var propertyLocation = document.getElementById("propertyLocation").value;

newpoints[0] = new Array(23.709801, 90.407112, icon0, 'yourLocation', '<div align="center">The Capital of Bangladesh</div>');

newpoints[1] = new Array(latVal, langVal, icon0, 'yourLocation', '<div align="center">Property Location::<br>'+propertyLocation+'</div>');

for(var i = 0; i < newpoints.length; i++) {

var point = new GPoint(newpoints[i][1],newpoints[i][0]);

var popuphtml = newpoints[i][4] ;

var marker = createMarker(point,newpoints[i][2],popuphtml);

map.addOverlay(marker);

}

}

function createMarker(point, icon, popuphtml) {

var popuphtml = "<div id=\"popup\">" + popuphtml + "<\/div>";

var marker = new GMarker(point, icon);


GEvent.addListener(marker, "click", function() {

marker.openInfoWindowHtml(popuphtml);

});
return marker;

}
//]]>

</script>


<style type="text/css">

div#popup {
background:#EFEFEF; border:1px solid #999999; margin:0px; padding:7px; width:270px;

}

</style>

</head>

<body>

<s:form>

<s:hidden id="a" name="a" value="%{latValue}"/>

<s:hidden id="b" name="b" value="%{longValue}"/>

<s:hidden id="propertyLocation" name="propertyLocation" value="%{location}"/>

</s:form>

<div id="map" style="width:600px;height:450px"></div>

</body>

</html>



N:B: Google api key can achieved from google web site using gmail account name & password.

One can get api by click on the address: (http://code.google.com/apis/maps/signup.html)


Step 3: Create a java file to get Latitude and Longtitude value as well as return value for struts.xml file (Suppose ShowMapAction.java)

package com.shahalom.Action;

import com.opensymphony.xwork2.Action;
import com.sun.j2ee.blueprints.ui.geocoder.GeoCoder;
import com.sun.j2ee.blueprints.ui.geocoder.GeoPoint;
import com.sun.j2ee.blueprints.ui.mapviewer.MapMarker;
import com.sun.j2ee.blueprints.ui.mapviewer.MapPoint;

/**
*
* @author Shah Alom
*/

public class ShowMapAction {

private MapMarker mapMarker=new MapMarker();
private MapPoint mapPoint=new MapPoint();
private String location="Dhaka, Bangladesh";
private Double latValue;
private Double longValue;


public String getGoogleMap(){
getLatLangtitudeValueFromGoogleService();
return Action.SUCCESS;

}

public void getLatLangtitudeValueFromGoogleService(){
GeoCoder geoCoder=new GeoCoder();
GeoPoint points[]=geoCoder.geoCode(getLocation());
mapMarker.setLatitude(points[0].getLatitude());
mapMarker.setLongitude(points[0].getLongitude());
mapMarker.setMarkup(points[0].toString());
mapPoint.setLatitude(points[0].getLatitude());
mapPoint.setLongitude(points[0].getLongitude());

this.setLatValue(mapMarker.getLatitude());
this.setLongValue(mapMarker.getLongitude());
System.out.println("Location is ::"+getLocation() );
System.out.println("getLatitude ::" +mapMarker.getLatitude());
System.out.println("getLongitude ::" +mapMarker.getLongitude());

}

public String getLocation() {

return location;

}

public void setLocation(String location) {

this.location = location;

}

public Double getLatValue() {

return latValue;

}

public void setLatValue(Double latValue) {

this.latValue = latValue;

}

public Double getLongValue() {

return longValue;

}

public void setLongValue(Double longValue) {

this.longValue = longValue;

}

}

Step 4: Create a struts.xml in the default package file

<?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="EndUserBeforLogin" extends="struts-default" >

<action name="getGoogleMap" method="getGoogleMap" class="com.shahalom.Action.ShowMapAction">
<result name="success">ShowMap.jsp</result>

</action>

</package>
</struts>


Step 5: Configure web.xml to detect struts.xml by the project (Whole code)


<?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>