Tuesday, July 06, 2010

Integration of ExtGWT and Spring to perform CRUD operation on My-SQL Db.





ExtGWTSpringCRUDExample - Combination of ExtGWTand Spring to perform CRUD operation on My-SQL Db.

ExtGWTSpringCRUDExample.gwt.xml:

xml version="1.0" encoding="UTF-8"?>

<module rename-to='extgwtspringcrudexample'>

<inherits name='com.google.gwt.user.User'/>

<inherits name='com.google.gwt.user.theme.standard.Standard'/>

<inherits name='com.extjs.gxt.ui.GXT' />

<entry-point class='extGWTSpringCRUDExample.client.ExtGWTSpringCRUDExample'/>

<source path='client'/>

<source path='shared'/>

module>

ExtGWTSpringCRUDExample:

package extGWTSpringCRUDExample.client;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;

import com.extjs.gxt.ui.client.event.ButtonEvent;

import com.extjs.gxt.ui.client.event.SelectionListener;

import com.extjs.gxt.ui.client.widget.Info;

import com.extjs.gxt.ui.client.widget.Layout;

import com.extjs.gxt.ui.client.widget.LayoutContainer;

import com.extjs.gxt.ui.client.widget.VerticalPanel;

import com.extjs.gxt.ui.client.widget.button.Button;

import com.extjs.gxt.ui.client.widget.form.FormButtonBinding;

import com.extjs.gxt.ui.client.widget.form.FormPanel;

import com.extjs.gxt.ui.client.widget.form.TextField;

import com.extjs.gxt.ui.client.widget.layout.AnchorLayout;

import com.extjs.gxt.ui.client.widget.layout.FormData;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.core.client.GWT;

import com.google.gwt.user.client.Element;

import com.google.gwt.user.client.rpc.AsyncCallback;

import com.google.gwt.user.client.ui.HTML;

import com.google.gwt.user.client.ui.RootPanel;

/**

* Entry point classes define onModuleLoad().

*/

public class ExtGWTSpringCRUDExample implements EntryPoint {

private static final String SERVER_ERROR = "An error occurred while "

+ "attempting to contact the server. Please check your network "

+ "connection and try again.";

private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

public void onModuleLoad() {

//to add something TBD

@SuppressWarnings("unused")

Layout junk = new AnchorLayout();

TemplateExample objTemplateExample = new TemplateExample();

RootPanel.get().add(objTemplateExample);

}

private VerticalPanel vp;

private FormData formData;

//by siddhu[

class TemplateExample extends LayoutContainer {

@Override

protected void onRender(Element parent, int index) {

super.onRender(parent, index);

formData = new FormData("-20");

vp = new VerticalPanel();

vp.setSpacing(10);

//createForm1();

FormPanel simple = new FormPanel();

simple.setHeading("Ext GWT CRUD Form");

simple.setFrame(true);

simple.setWidth(350);

final TextField id = new TextField();

id.setFieldLabel("Id");

//firstName.setAllowBlank(false);

simple.add(id, formData);

final TextField name = new TextField();

name.setFieldLabel("Name");

//name.setAllowBlank(false);

simple.add(name, formData);

SelectionListener l = new SelectionListener() {

@Override

public void componentSelected(ButtonEvent ce) {

//Info.display("Click", ce.getButton().getText() + " clicked");

if(ce.getButton().getText()!= null && (!ce.getButton().getText().equals("")&&ce.getButton().getText().equals("Insert")))

{

//String idText = id.getValue();

//String nameText = name.getValue();

insertToMYSQL(id.getValue(), name.getValue());

}

if(ce.getButton().getText()!= null && (!ce.getButton().getText().equals("")&&ce.getButton().getText().equals("Update")))

{

updateToMYSQL(id.getValue(), name.getValue());

}

if(ce.getButton().getText()!= null && (!ce.getButton().getText().equals("")&&ce.getButton().getText().equals("Delete")))

{

deleteToMYSQL(id.getValue(), name.getValue());

}

}

};

Button insert = new Button("Insert",l);

simple.addButton(insert);

Button update = new Button("Update",l);

simple.addButton(update);

Button delete = new Button("Delete",l);

simple.addButton(delete);

simple.setButtonAlign(HorizontalAlignment.CENTER);

FormButtonBinding binding = new FormButtonBinding(simple);

binding.addButton(insert);

binding.addButton(update);

binding.addButton(delete);

vp.add(simple);

add(vp);

//idText = id.getSelectedText();

//nameText = name.getSelectedText();

}

/**

* Send the name from the nameField to the server and wait for a response.

*/

private void insertToMYSQL(String idText, String nameText) {

//String idText = id.getText();

//String nameText = name.getText();

String methodname = "Insert";

greetingService.greetServer(idText,nameText,methodname,

new AsyncCallback() {

public void onFailure(Throwable caught) {

// Show the RPC error message to the user

RootPanel.get().add(new HTML("RPC call failed. :-("));

}

public void onSuccess(String result) {

RootPanel.get().add(new HTML("RPC call Success:"));

}

});

}

private void updateToMYSQL(String idText, String nameText) {

//String idText = idField.getText();

//String nameText = nameField.getText();

String methodname = "Update";

greetingService.greetServer(idText,nameText,methodname,

new AsyncCallback() {

public void onFailure(Throwable caught) {

// Show the RPC error message to the user

RootPanel.get().add(new HTML("RPC call failed. :-("));

}

public void onSuccess(String result) {

RootPanel.get().add(new HTML("RPC call Success:"));

}

});

}

private void deleteToMYSQL(String idText, String nameText) {

//String idText = idField.getText();

//String nameText = nameField.getText();

String methodname = "Delete";

greetingService.greetServer(idText,nameText,methodname,

new AsyncCallback() {

public void onFailure(Throwable caught) {

// Show the RPC error message to the user

RootPanel.get().add(new HTML("RPC call failed. :-("));

}

public void onSuccess(String result) {

RootPanel.get().add(new HTML("RPC call Success:"));

}

});

}

}

//by siddhu]

}

GreetingService:

package extGWTSpringCRUDExample.client;

import com.google.gwt.user.client.rpc.RemoteService;

import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

/**

* The client side stub for the RPC service.

*/

@RemoteServiceRelativePath("greet")

public interface GreetingService extends RemoteService {

String greetServer(String id,String name,String methodName) throws IllegalArgumentException;

}

GreetingServiceAsync:

package extGWTSpringCRUDExample.client;

import com.google.gwt.user.client.rpc.AsyncCallback;

/**

* The async counterpart of GreetingService.

*/

public interface GreetingServiceAsync {

public void greetServer(String input1,String input2,String methodName, AsyncCallback callback)

throws IllegalArgumentException;

}

GreetingServiceImpl:

package extGWTSpringCRUDExample.server;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

import extGWTSpringCRUDExample.client.GreetingService;

import extGWTSpringCRUDExample.shared.FieldVerifier;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**

* The server side implementation of the RPC service.

*/

@SuppressWarnings("serial")

public class GreetingServiceImpl extends RemoteServiceServlet implements

GreetingService {

String dbUrl = "jdbc:mysql://localhost/siddhutest_db";

String dbClass = "com.mysql.jdbc.Driver";

public String greetServer(String id,String name,String methodName) throws IllegalArgumentException {

// Verify that the input is valid.

/*

if (!FieldVerifier.isValidName(input)) {

// If the input is not valid, throw an IllegalArgumentException back to

// the client.

throw new IllegalArgumentException(

"Name must be at least 4 characters long");

}

String serverInfo = getServletContext().getServerInfo();

String userAgent = getThreadLocalRequest().getHeader("User-Agent");

return "Hello, " + input + "!

I am running " + serverInfo

+ ".

It looks like you are using:
" + userAgent;

*/

if(methodName.equals("Insert"))

{

try {

Class.forName(dbClass).newInstance();

Connection con = DriverManager.getConnection(dbUrl,"root","");

Statement stmt = con.createStatement();

String query = "insert into test_table (id, name) values ("+id+",'"+name+"')";

int i = stmt.executeUpdate(query);

con.close();

return "success";

} //end try

catch(Exception e) {

e.printStackTrace();

}

}

else if(methodName.equals("Delete"))

{

try {

Class.forName(dbClass).newInstance();

Connection con = DriverManager.getConnection(dbUrl,"root","");

Statement stmt = con.createStatement();

String query = "delete from test_table where id ="+id;

int i = stmt.executeUpdate(query);

con.close();

return "success";

} //end try

catch(Exception e) {

e.printStackTrace();

}

}else if (methodName.equals("Update"))

{

try {

Class.forName(dbClass).newInstance();

Connection con = DriverManager.getConnection(dbUrl,"root","");

Statement stmt = con.createStatement();

String query = "update test_table set name = '"+name+"' where id ="+id;

int i = stmt.executeUpdate(query);

con.close();

return "success";

} //end try

catch(Exception e) {

e.printStackTrace();

}

}

return "failure";

}

}

ServletWrappingController:

package extGWTSpringCRUDExample.server;

import java.util.Enumeration;

import java.util.Properties;

import javax.servlet.Servlet;

import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.BeanNameAware;

import org.springframework.beans.factory.DisposableBean;

import org.springframework.beans.factory.InitializingBean;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.AbstractController;

/**

* Spring Controller implementation that mimics standard ServletWrappingController behaviour

* (see its documentation), but with the important difference that it doesn't instantiate the

* Servlet instance directly but delegate for this the BeanContext, so that we can also use IoC.*

*/

public class ServletWrappingController extends AbstractController

implements BeanNameAware, InitializingBean, DisposableBean {

private Class servletClass;

private String servletName;

private Properties initParameters = new Properties();

private String beanName;

private Servlet servletInstance;

public void setServletClass(Class servletClass) {

System.out.print("setServletClass : "+servletClass);

this.servletClass = servletClass;

}

public void setServletName(String servletName) {

System.out.print("setServletName : "+servletName);

this.servletName = servletName;

}

public void setInitParameters(Properties initParameters) {

System.out.print("setInitParameters : "+initParameters);

this.initParameters = initParameters;

}

public void setBeanName(String name) {

System.out.print("setBeanName : "+name);

this.beanName = name;

}

public void setServletInstance(Servlet servletInstance) {

System.out.print("setServletInstance : "+servletInstance);

this.servletInstance = servletInstance;

}

public void afterPropertiesSet() throws Exception {

System.out.print("afterPropertiesSet");

if (this.servletInstance == null) {

throw new IllegalArgumentException("servletInstance is required");

}

if (!Servlet.class.isAssignableFrom(servletInstance.getClass())) {

throw new IllegalArgumentException("servletInstance [" + this.servletClass.getName() +

"] needs to implement interface [javax.servlet.Servlet]");

}

if (this.servletName == null) {

this.servletName = this.beanName;

}

this.servletInstance.init(new DelegatingServletConfig());

}

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)

throws Exception {

System.out.print("handleRequestInternal");

this.servletInstance.service(request, response);

return null;

}

public void destroy() {

System.out.print("destroy");

this.servletInstance.destroy();

}

private class DelegatingServletConfig implements ServletConfig {

public String getServletName() {

return servletName;

}

public ServletContext getServletContext() {

return getWebApplicationContext().getServletContext();

}

public String getInitParameter(String paramName) {

return initParameters.getProperty(paramName);

}

public Enumeration getInitParameterNames() {

return initParameters.keys();

}

}

}

dispatcher-servlet.xml:

xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="urlMapping"

class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="urlMap">

<map>

<entry key="myService">

<ref bean="ServiceController">ref>

entry>

map>

property>

bean>

<bean id="ServiceController" class="extGWTSpringCRUDExample.server.ServletWrappingController">

<property name="servletName" value="myService">

property>

<property name="servletInstance">

<ref bean="myService">ref>

property>

bean>

<bean id="myService" class="extGWTSpringCRUDExample.server.GreetingServiceImpl" />

beans>

web.xml:

xml version="1.0" encoding="UTF-8"?>

DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>dispatcherservlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

<load-on-startup>1load-on-startup>

servlet>

<servlet>

<servlet-name>myServiceservlet-name>

<servlet-class>extGWTSpringCRUDExample.server.GreetingServiceImplservlet-class>

servlet>

<servlet-mapping>

<servlet-name>dispatcherservlet-name>

<url-pattern>/services/*url-pattern>

servlet-mapping>

<servlet>

<servlet-name>greetServletservlet-name>

<servlet-class>extGWTSpringCRUDExample.server.GreetingServiceImplservlet-class>

servlet>

<servlet-mapping>

<servlet-name>greetServletservlet-name>

<url-pattern>/extgwtspringcrudexample/greeturl-pattern>

servlet-mapping>

<welcome-file-list>

<welcome-file>ExtGWTSpringCRUDExample.htmlwelcome-file>

welcome-file-list>

<servlet-mapping>

<servlet-name>greetServletservlet-name>

<url-pattern>/extgwtspringcrudexample/services/myServiceurl-pattern>

servlet-mapping>

web-app>

ExtGWTSpringCRUDExample.html:

doctype html>

<html>

<head>

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

<link rel="stylesheet" type="text/css" href="resources/css/gxt-all.css" />

<title>Web Application Starter Projecttitle>

<script type="text/javascript" language="javascript" src="extgwtspringcrudexample/extgwtspringcrudexample.nocache.js">script>

head>

<body>

<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0">iframe>

<noscript>

<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">

Your web browser must have JavaScript enabled

in order for this application to display correctly.

div>

noscript>

<h1>Ext GWT Spring CRUD Projecth1>

body>

html>

No comments: