Tuesday, July 06, 2010

Example showing integration of GWT, Spring and Hibernate

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>gwtSpringHibernate.server.GreetingServiceImplservlet-class>

servlet>

<servlet-mapping>

<servlet-name>dispatcherservlet-name>

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

servlet-mapping>

<servlet>

<servlet-name>greetServletservlet-name>

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

servlet>

<welcome-file-list>

<welcome-file>GWTSpringHibernate.htmlwelcome-file>

welcome-file-list>

<servlet-mapping>

<servlet-name>greetServletservlet-name>

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

servlet-mapping>

web-app>

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="gwtSpringHibernate.server.ServletWrappingController">

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

property>

<property name="servletInstance">

<ref bean="myService">ref>

property>

bean>

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

beans>

gwtSpringHibernate.gwt.xml:

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

<module rename-to='gwtspringhibernate'>

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

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

<entry-point class='gwtSpringHibernate.client.GWTSpringHibernate'/>

<servlet path="/services/myService" class="gwtSpringHibernate.server.GreetingServiceImpl"/>

<source path='client'/>

<source path='shared'/>

module>

GreetingService:

package gwtSpringHibernate.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("services/myService")

public interface GreetingService extends RemoteService {

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

//by Siddhu [

public String addValue(String value1, String value2) throws IllegalArgumentException;

//by Siddhu ]

}

GreetingServiceAsync:

package gwtSpringHibernate.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;

//by siddhu[

void addValue(String value1,String value2, AsyncCallback callback)

throws IllegalArgumentException;

//by siddhu]

}

GWTSpringHibernate:

package gwtSpringHibernate.client;

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

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

import com.google.gwt.event.dom.client.ClickEvent;

import com.google.gwt.event.dom.client.ClickHandler;

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

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

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

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

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

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

/**

* Entry point classes define onModuleLoad().

*/

public class GWTSpringHibernate implements EntryPoint {

/**

* The message displayed to the user when the server cannot be reached or

* returns an error.

*/

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

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

+ "connection and try again.";

/**

* Create a remote service proxy to talk to the server-side Greeting service.

*/

private final GreetingServiceAsync greetingService = GWT

.create(GreetingService.class);

/**

* This is the entry point method.

*/

public void onModuleLoad() {

final Button insertButton = new Button("Insert");

final Button updateButton = new Button("Update");

final Button deleteButton = new Button("Delete");

final Label idLabel = new Label();

idLabel.setText("ID:");

RootPanel.get("idLabelContainer").add(idLabel);

final TextBox idField = new TextBox();

RootPanel.get("idFieldContainer").add(idField);

final Label nameLabel = new Label();

nameLabel.setText("NAME:");

RootPanel.get("nameLabelContainer").add(nameLabel);

final TextBox nameField = new TextBox();

RootPanel.get("nameFieldContainer").add(nameField);

insertButton.addStyleName("Insert");

updateButton.addStyleName("Update");

deleteButton.addStyleName("Delete");

final Label errorLabel = new Label();

RootPanel.get("insertButtonContainer").add(insertButton);

RootPanel.get("updateButtonContainer").add(updateButton);

RootPanel.get("deleteButtonContainer").add(deleteButton);

RootPanel.get("errorLabelContainer").add(errorLabel);

// Focus the cursor on the name field when the app loads

idField.setFocus(true);

idField.selectAll();

// Create a handler for the sendButton and nameField

class MyHandler implements ClickHandler {

/**

* Fired when the user clicks on the sendButton.

*/

public void onClick(ClickEvent event) {

if(event.getSource().equals(insertButton))

{

insertToMYSQL();

}

else if(event.getSource().equals(updateButton))

{

updateToMYSQL();

}

else if (event.getSource().equals(deleteButton))

{

deleteToMYSQL();

}

}

/**

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

*/

private void insertToMYSQL() {

String idText = idField.getText();

String nameText = nameField.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 = 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 = 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:"));

}

});

}

}

// Add a handler to send the name to the server

MyHandler handler = new MyHandler();

insertButton.addClickHandler(handler);

updateButton.addClickHandler(handler);

deleteButton.addClickHandler(handler);

//nameField.addKeyUpHandler(handler);

}

}

GreetingServiceImpl:

package gwtSpringHibernate.server;

import gwtSpringHibernate.client.GreetingService;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

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();

}*/

Session session = null;

try{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

session =sessionFactory.openSession();

//Create new instance of Contact and set values in it by reading them from form object

test_table objtest_table = new test_table();

objtest_table.setId(id);

objtest_table.setName(name);

session.save(objtest_table);

}catch(Exception e){

e.printStackTrace();

}

finally{

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

}

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();

}*/

Session session = null;

try{

SessionFactory fact = new Configuration().configure().buildSessionFactory();

session = fact.openSession();

test_table objtest_table = (test_table)session.get(test_table.class, id);

Transaction tr = session.beginTransaction();

session.delete(objtest_table);

tr.commit();

session.close();

}catch(Exception e){

e.printStackTrace();

}finally{

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

}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();

}

*/

Session session = null;

try {

SessionFactory fact = new Configuration().configure().buildSessionFactory();

session = fact.openSession();

Transaction tr = session.beginTransaction();

test_table objtest_table = (test_table)session.get(test_table.class, id);

objtest_table.setName(name);

session.update(objtest_table);

tr.commit();

session.close();

}

catch(Exception e){

System.out.println(e.getMessage());

} finally{

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

}

return "failure";

}

//by siddhu[

public String addValue(String value1,String value2) throws IllegalArgumentException {

int addValue = Integer.parseInt(value1) + Integer.parseInt(value2);

Integer i = new Integer(addValue);

return i.toString();

}

//by siddhu]

}

ServletWrappingController:

package gwtSpringHibernate.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();

}

}

}

test_table:

package gwtSpringHibernate.server;

/**

* @author Siddharatha Dhumale

*

*

* Java Class to map to the datbase Contact Table

*/

public class test_table

{

private String id;

private String name;

/**

* @return

*/

public String getId() {

return id;

}

/**

* @return

*/

public void setId(String id) {

this.id = id;

}

/**

* @return

*/

public String getName() {

return name;

}

/**

* @return

*/

public void setName(String name) {

this.name = name;

}

}

FieldVerifier:

package gwtSpringHibernate.shared;

/**

*

* FieldVerifier validates that the name the user enters is valid.

*

*

* This class is in the shared packing because we use it in both

* the client code and on the server. On the client, we verify that the name is

* valid before sending an RPC request so the user doesn't have to wait for a

* network round trip to get feedback. On the server, we verify that the name is

* correct to ensure that the input is correct regardless of where the RPC

* originates.

*

*

* When creating a class that is used on both the client and the server, be sure

* that all code is translatable and does not use native JavaScript. Code that

* is note translatable (such as code that interacts with a database or the file

* system) cannot be compiled into client side JavaScript. Code that uses native

* JavaScript (such as Widgets) cannot be run on the server.

*

*/

public class FieldVerifier {

/**

* Verifies that the specified name is valid for our service.

*

* In this example, we only require that the name is at least four

* characters. In your application, you can use more complex checks to ensure

* that usernames, passwords, email addresses, URLs, and other fields have the

* proper syntax.

*

* @param name the name to validate

* @return true if valid, false if invalid

*/

public static boolean isValidName(String name) {

if (name == null) {

return false;

}

return name.length() > 3;

}

}

Hibernate.cfg.xml:

xml version='1.0' encoding='utf-8'?>

DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>

<property name="hibernate.connection.url">jdbc:mysql://localhost/siddhutest_dbproperty>

<property name="hibernate.connection.username">rootproperty>

<property name="hibernate.connection.password">property>

<property name="hibernate.connection.pool_size">10property>

<property name="show_sql">trueproperty>

<property name="dialect">org.hibernate.dialect.MySQLDialectproperty>

<property name="hibernate.hbm2ddl.auto">updateproperty>

<mapping resource="test_table.hbm.xml"/>

session-factory>

hibernate-configuration>

Test_table.hbm.xml:

xml version="1.0"?>

DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="gwtSpringHibernate.server.test_table" table="test_table">

<id name="id" column="id" >

<generator class="assigned"/>

id>

<property name="name">

<column name="name"/>

property>

class>

hibernate-mapping>

GWTSprngHybernate.html:

doctype html>

<html>

<head>

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

<link type="text/css" rel="stylesheet" href="GWTSpringHibernate.css">

<title>Web Application Starter Projecttitle>

<script type="text/javascript" language="javascript" src="gwtspringhibernate/gwtspringhibernate.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>Web Application Starter Projecth1>

<table align="center">

<tr>

tr>

<tr>

<td id="idLabelContainer">td>

<td id="idFieldContainer">td>

<td id="nameLabelContainer">td>

<td id="nameFieldContainer">td>

<td id="insertButtonContainer">td>

<td id="updateButtonContainer">td>

<td id="deleteButtonContainer">td>

tr>

<tr>

<td colspan="2" style="color:red;" id="errorLabelContainer">td>

tr>

table>

body>

html>

No comments: