GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial – Eclipse and Maven 2 showcase
This step by step guide will present how to develop a simple web application using Google’s Web Toolkit (GWT) for the rich client and Spring as the back – end, server side framework. The sample web application will provide functionality to make CRUD (Create Retrieve Update Delete) operations to a database. For the data access layer we will use JPA over Hibernate and for a database we will use Hypersonic. Of course you can change the configuration and use whatever you like. We will deploy the web application to an Apache – Tomcat instance.
Maven comes in two flavors, the standalone tool with command line support, and as an IDE (Eclipse and Netbeans) integration plugin. Our preferred development environment is Eclipse, so as a prerequisite you must have Eclipse with Maven support installed. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. Nevertheless you will need the following components :
We will be using Eclipse Galileo and „m2eclipse“ Maven Integration for Eclipse Plugin version 0.10.0, GWT version 2.0.3, Spring version 3.0.1, Hibernate version 3.5.1, Hypersonic version 1.8.0.10, slf4j-log4j12 version 1.5.8, c3p0 connection pool version 0.9.1.2 and spring4gwt version 0.0.1 for this tutorial.
Enough talk, lets get our hands dirty!
- Create a new Maven project, go to File ? Project ? Maven ? Maven Project
- In the „Select project name and location“ page of the wizard, make sure that „Create a simple project (skip archetype selection)“ option is unchecked, hit „Next“ to continue with default values
- In the „Select an Archetype“ page of the wizard, select „Nexus Indexer“ at the „Catalog“ drop down list and after the archetypes selection area is refreshed, select the „gwt-maven-plugin“ archetype from „org.codehaus.mojo“ to use. You can use the „filter“ text box to narrow search results. Hit „Next“ to continue
- In the „Enter an artifact id“ page of the wizard, you can define the name and main package of your project. We will set the „Group Id“ variable to „com.javacodegeeks“ and the „Artifact Id“ variable to „gwtspring“. The aforementioned selections compose the main project package as „com.javacodegeeks.gwtspring“ and the project name as „gwtspring“. Hit „Finish“ to exit the wizard and to create your project
Let’s recap a few things about the Maven GWT project structure
- /src/main/java folder contains source files for the dynamic content of the application
- {main_package}.client sub-package contains source files only available to the client side of the application
- {main_package}.server sub-package contains source files only available to the server side part of the application (this sub-package is not automatically created upon project creation)
- {main_package}.shared sub-package contains source files available to both the client and server side of the application (this sub-package is not automatically created upon project creation)
- /src/main/resources contains source files for static content e.g. static html pages and resource files of the application e.g. css files
- /src/test/java folder contains all source files for unit tests
- /src/main/webapp folder contains essential files for creating a valid web application, e.g. „web.xml“
- /target folder contains the compiled and packaged deliverables
- /war folder is used in the build and package process
- The „pom.xml“ is the project object model (POM) file. The single file that contains all project related configuration
In order to properly integrate Spring with GWT at runtime, we must provide all necessary libraries to the web application. Open the graphical editor of your „pom.xml“ and perform the following changes :
- Locate the „Properties“ section at the „Overview“ page of the POM editor and perform the following changes:
- Create a new property with name org.springframework.version and value 3.0.1.RELEASE
- Create a new property with name org.hibernate.version and value 3.5.1-Final
- Alter gwt.version propery’s value to 2.0.3
- Alter maven.compiler.source and maven.compiler.target properties values according to the version of your Java runtime environment, we will use 1.6
- Navigate to the „Dependencies“ page of the POM editor and create the following dependencies (you should fill the „GroupId“, „Artifact Id“ and „Version“ fields of the „Dependency Details“ section at that page) :
- Group Id : org.springframework Artifact Id : spring-orm Version : ${org.springframework.version}
- Group Id : org.springframework Artifact Id : spring-web Version : ${org.springframework.version}
- Group Id : org.hibernate Artifact Id : hibernate-core Version : ${org.hibernate.version}
- Group Id : org.hibernate Artifact Id : hibernate-annotations Version : ${org.hibernate.version}
- Group Id : org.hibernate Artifact Id : hibernate-entitymanager Version : ${org.hibernate.version}
- Group Id : org.hibernate.javax.persistence Artifact Id : hibernate-jpa-2.0-api Version : 1.0.0.Final
- Group Id : org.slf4j Artifact Id : slf4j-log4j12 Version : 1.5.8
- Group Id : org.hsqldb Artifact Id : hsqldb Version : 1.8.0.10
- Group Id : c3p0 Artifact Id : c3p0 Version : 0.9.1.2
- Locate the “Show Advanced Tabs” button at the top right of your POM editor and click it. Navigate to the “Repositories” page and create the following repository (you should fill the „Id” and „URL“ fields of the „Repository Details“ section at that page) :
- Id : JBoss URL : http://repository.jboss.org/maven2/
As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated. Nevertheless not all libraries are available to public repositories. In that case we must download the required library by hand and use it in our project. Such a case is the „spring4gwt“ library. To use it we must create a „lib“ folder under /src/main/webapp/WEB-INF folder and place „spring4gwt-0.0.1.jar“ there. In a future article we will discuss how to create you own Maven shared repository and install libraries that are not publicly available, so stay tuned!
The next step is to provide hooks for the web application so as to load the Spring context upon startup and to allow for „spring4gwt“ to intercept RPC calls between the client and the server and transform them to Spring service invocations.
Locate the „web.xml“ file under /src/main/webapp/WEB-INF and add the following :
For loading the Spring context upon startup,
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
At the servlets section include
<servlet> <servlet-name>springGwtRemoteServiceServlet</servlet-name> <servlet-class>org.spring4gwt.server.SpringGwtRemoteServiceServlet </servlet-class> </servlet>
At the servlet-mapping section include, for spring4gwt to intercept RPC calls.
<servlet-mapping> <servlet-name>springGwtRemoteServiceServlet</servlet-name> <url-pattern>/com.javacodegeeks.gwtspring.Application/springGwtServices/*</url-pattern> </servlet-mapping>
Things to notice here :
- The url-pattern child element of the servlet-mapping element for the springGwtRemoteServiceServlet servlet, should be changed to whatever your GWT module name is e.g. {module_name}/springGwtServices/*, the module name is by default {main_package}.Application
- You can change the name of spring4gwt servlet (springGwtRemoteServiceServlet here) to whatever you like
The next step is to create the „persistence.xml“ file so as to describe the connection with the database using JPA. The „pesistence.xml“ file must be located inside a META-INF directory which in turn has to be accessible by the web application at runtime (on the classpath). To fulfill the aforementioned requirements we have to create the META-INF folder under the project’s /src/main/resources folder. Finally create the „persistence.xml“ file inside the /src/main/resources/META-INF folder. An example persistence.xml is presented below
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.hbm2ddl.auto" value="update" /> <property name="hibernate.show_sql" value="false" /> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" /> <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" /> <property name="hibernate.connection.url" value="jdbc:hsqldb:mem:javacodegeeks" /> <property name="hibernate.connection.username" value="sa" /> <property name="hibernate.connection.password" value="" /> <property name="hibernate.c3p0.min_size" value="5" /> <property name="hibernate.c3p0.max_size" value="20" /> <property name="hibernate.c3p0.timeout" value="300" /> <property name="hibernate.c3p0.max_statements" value="50" /> <property name="hibernate.c3p0.idle_test_period" value="3000" /> </properties> </persistence-unit> </persistence>
Now lets create the applicationContext.xml file that will drive Spring container. Create the file under /src/main/webapp/WEB-INF directory. An example „applicationContext.xml“ is presented below
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.gwtspring" /> <tx:annotation-driven /> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="MyPersistenceUnit" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> </beans>
Things to notice here :
- Change the base-package attribute of the context:component-scan element to whatever is the base package of your project so as to be scanned for Spring components (services, DAOs etc)
- Change the value attribute of entityManagerFactory bean persistentUnitName property to the name of your persistent unit as dictated in the „persistence.xml“ file
In the last part of this tutorial we are going to present the Data Transfer Object (DTO) for transferring data between the client and the server, the Data Access Object (DAO) that is used to access the database and the Spring service to expose functionality to the GWT Web client.
The DTO is an object that can be used by both the client and the server, thus you should create a „shared.dto“ sub-package under your main package (in our case com.javacodegeeks.gwtspring) and place the DTO there. We are going to create an EmployeeDTO containing information for an employee like below
package com.javacodegeeks.gwtspring.shared.dto; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "EMPLOYEE") public class EmployeeDTO implements java.io.Serializable { private static final long serialVersionUID = 7440297955003302414L; @Id @Column(name="employee_id") private long employeeId; @Column(name="employee_name", nullable = false, length=30) private String employeeName; @Column(name="employee_surname", nullable = false, length=30) private String employeeSurname; @Column(name="job", length=50) private String job; public EmployeeDTO() { } public EmployeeDTO(int employeeId) { this.employeeId = employeeId; } public EmployeeDTO(long employeeId, String employeeName, String employeeSurname, String job) { this.employeeId = employeeId; this.employeeName = employeeName; this.employeeSurname = employeeSurname; this.job = job; } public long getEmployeeId() { return employeeId; } public void setEmployeeId(long employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getEmployeeSurname() { return employeeSurname; } public void setEmployeeSurname(String employeeSurname) { this.employeeSurname = employeeSurname; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } }
For the DTO object to be available to the GWT client we must instruct the GWT compiler to parse it. To do so, locate the main GWT module file, it should be named „Application.gwt.xml“ and located under your main package (in our case com.javacodegeeks.gwtspring) and append the following directives :
<!-- Specify the paths for translatable code --> <source path='client'/> <source path='shared'/>
The DAO object will be used to access the database and perform CRUD (Create Retrieve Update Delete) operations. It is a server side component so it should be placed under a “server” sub-package of our project. Create a “server.dao” sub-package under your main project package (in our case com.javacodegeeks.gwtspring) and place the DAO there. An example DAO is presented below
package com.javacodegeeks.gwtspring.server.dao; import javax.annotation.PostConstruct; import javax.persistence.EntityManagerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.javacodegeeks.gwtspring.shared.dto.EmployeeDTO; @Repository("employeeDAO") public class EmployeeDAO extends JpaDAO<Long, EmployeeDTO> { @Autowired EntityManagerFactory entityManagerFactory; @PostConstruct public void init() { super.setEntityManagerFactory(entityManagerFactory); } }
As you can see the EmployeeDAO class extends a basic DAO class (JpaDAO). The EmployeeDAO class can contain specific queries concerning the EmployeeDTO object, but all CRUD operations can be handled from the basic DAO class (JpaDAO). Place the JpaDAO class at the same level as the EmployeeDAO class, under the “dao” subpackage. Below we present the JpaDAO class
package com.javacodegeeks.gwtspring.server.dao; import java.lang.reflect.ParameterizedType; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceException; import javax.persistence.Query; import org.springframework.orm.jpa.JpaCallback; import org.springframework.orm.jpa.support.JpaDaoSupport; public abstract class JpaDAO<K, E> extends JpaDaoSupport { protected Class<E> entityClass; @SuppressWarnings("unchecked") public JpaDAO() { ParameterizedType genericSuperclass = (ParameterizedType) getClass() .getGenericSuperclass(); this.entityClass = (Class<E>) genericSuperclass .getActualTypeArguments()[1]; } public void persist(E entity) { getJpaTemplate().persist(entity); } public void remove(E entity) { getJpaTemplate().remove(entity); } public E merge(E entity) { return getJpaTemplate().merge(entity); } public void refresh(E entity) { getJpaTemplate().refresh(entity); } public E findById(K id) { return getJpaTemplate().find(entityClass, id); } public E flush(E entity) { getJpaTemplate().flush(); return entity; } @SuppressWarnings("unchecked") public List<E> findAll() { Object res = getJpaTemplate().execute(new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { Query q = em.createQuery("SELECT h FROM " + entityClass.getName() + " h"); return q.getResultList(); } }); return (List<E>) res; } @SuppressWarnings("unchecked") public Integer removeAll() { return (Integer) getJpaTemplate().execute(new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { Query q = em.createQuery("DELETE FROM " + entityClass.getName() + " h"); return q.executeUpdate(); } }); } }
Finally we are going to create the service interface and implementation classes for the GWT client to access. The service interface should be accessible by both the client and the server, so it should be placed under the “shared” sub-package of our project. Create a “services” sub-package and place the service interface there. An example interface class follows
package com.javacodegeeks.gwtspring.shared.services; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import com.javacodegeeks.gwtspring.shared.dto.EmployeeDTO; @RemoteServiceRelativePath("springGwtServices/employeeService") public interface EmployeeService extends RemoteService { public EmployeeDTO findEmployee(long employeeId); public void saveEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception; public void updateEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception; public void saveOrUpdateEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception; public void deleteEmployee(long employeeId) throws Exception; }
Things to notice here :
- GWT client has to be able to make asynchronous Remote Procedure Calls (RPCs) to the server side service. Thus the service interface must extend the RemoteService interface. An asynchronous counterpart of the specified interface is automatically created by Maven before project compilation and packaging faces
- We annotate the interface so as to define the URL under which the service will be accessible. As the service is a Spring service we want „spring4gwt“ to intercept the RPC calls and perform a Spring service invocation. To do that we define a relative path that will be handled by “springGwtRemoteServiceServlet” declared in our „web.xml“ as shown above
- The service name declared at “RemoteServiceRelativePath” annotation, here “employeeService”, must match the Spring service bean name. We will define the Spring service bean name in the service implementation class (see below)
The service implementation class is a server side component, so we must place it under “server” sub-package of our project. Create the “services” sub-package and place it there. An example service implementation class is presented below
package com.javacodegeeks.gwtspring.server.services; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.javacodegeeks.gwtspring.server.dao.EmployeeDAO; import com.javacodegeeks.gwtspring.shared.dto.EmployeeDTO; import com.javacodegeeks.gwtspring.shared.services.EmployeeService; @Service("employeeService") public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeDAO employeeDAO; @PostConstruct public void init() throws Exception { } @PreDestroy public void destroy() { } public EmployeeDTO findEmployee(long employeeId) { return employeeDAO.findById(employeeId); } @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public void saveEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception { EmployeeDTO employeeDTO = employeeDAO.findById(employeeId); if(employeeDTO == null) { employeeDTO = new EmployeeDTO(employeeId, name,surname, jobDescription); employeeDAO.persist(employeeDTO); } } @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public void updateEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception { EmployeeDTO employeeDTO = employeeDAO.findById(employeeId); if(employeeDTO != null) { employeeDTO.setEmployeeName(name); employeeDTO.setEmployeeSurname(surname); employeeDTO.setJob(jobDescription); } } @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public void deleteEmployee(long employeeId) throws Exception { EmployeeDTO employeeDTO = employeeDAO.findById(employeeId); if(employeeDTO != null) employeeDAO.remove(employeeDTO); } @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public void saveOrUpdateEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception { EmployeeDTO employeeDTO = new EmployeeDTO(employeeId, name,surname, jobDescription); employeeDAO.merge(employeeDTO); } }
Things to notice here :
- We use the @Service(“employeeService”) stereotype annotation so as to declare that this class represents a Spring service by the name “exampleService”. The Spring container will instantiate all services at start up
- We use the @Autowire annotation to inject the instance of the DAO class to the “employeeService”. For proper instantiation of the service Spring container has to resolve first all potential references among services, so it instantiates the DAO class and injects the instance to the appropriate field of “employeeService” – the “employeeDAO” field. In case you wonder, the dependency injection is done according to type (Class) and if not satisfied according to name, meaning that if we have defined multiple services of the same type (Class) the one injected would be the one with the same name as the designated field
- We use the Java annotations @PostConstruct and @PreDestroy to declare the methods that will be invoked by Spring container after initialization (all dependency injection is done) and prior destruction of the service
- We use the @Transactional annotation for all methods that need to perform update operation on the database (INSERT, UPDATE, DELETE)
- We DO NOT use the @Transactional annotation on methods that perform retrieve (FIND) operations on the database (except for objects that contain lazily initialized references – see below), and/or perform no database operations. That is because every time you invoke a method annotated as transactional, Spring container involves in the invocation JPA‘s entity manager and as a consequence platform’s transaction manager, so as to define the transactional behavior that will be applied, introducing a noticeable performance penalty especially for low latency / high throughput applications
- For methods that perform retrieve (FIND) operations for objects that contain lazily initialized references you should use the @Transactional annotation, designating “NESTED” propagation type in order for Spring to maintain Hibernate session open for the entire method call
- Transactional behavior is applied only on client calls to the service. Transactional behavior is not applied to intra operation calls. For example if a client invokes an operation that is not annotated as transactional and the implementation of the latter introduces a call to another operation of the same service that is annotated transactional then for the combined operations no transactional behavior will be applied. That is because Spring uses AOP proxy classes to enforce transactional behavior
We are almost done!, we have to develop the GWT user interface to access our Spring service.
Locate the entry point of your GWT application. The file should be named „Application.java“ and located under “client” sub-package or our main package. Alter the entry point class as shown below
package com.javacodegeeks.gwtspring.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; 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; import com.google.gwt.user.client.ui.VerticalPanel; import com.javacodegeeks.gwtspring.shared.dto.EmployeeDTO; import com.javacodegeeks.gwtspring.shared.services.EmployeeServiceAsync; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class Application 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. The error is : "; /** * Create a remote service proxy to talk to the server-side Employee service. */ private final EmployeeServiceAsync employeeService = EmployeeServiceAsync.Util.getInstance(); /** * This is the entry point method. */ public void onModuleLoad() { final Button saveOrUpdateButton = new Button("SaveOrUpdate"); final Button retrieveButton = new Button("Retrieve"); final TextBox employeeInfoField = new TextBox(); employeeInfoField.setText("Employee Info"); final TextBox employeeIdField = new TextBox(); final Label errorLabel = new Label(); // We can add style names to widgets saveOrUpdateButton.addStyleName("sendButton"); retrieveButton.addStyleName("sendButton"); // Add the nameField and sendButton to the RootPanel // Use RootPanel.get() to get the entire body element RootPanel.get("employeeInfoFieldContainer").add(employeeInfoField); RootPanel.get("updateEmployeeButtonContainer").add(saveOrUpdateButton); RootPanel.get("employeeIdFieldContainer").add(employeeIdField); RootPanel.get("retrieveEmployeeButtonContainer").add(retrieveButton); RootPanel.get("errorLabelContainer").add(errorLabel); // Focus the cursor on the name field when the app loads employeeInfoField.setFocus(true); employeeInfoField.selectAll(); // Create the popup dialog box final DialogBox dialogBox = new DialogBox(); dialogBox.setText("Remote Procedure Call"); dialogBox.setAnimationEnabled(true); final Button closeButton = new Button("Close"); // We can set the id of a widget by accessing its Element closeButton.getElement().setId("closeButton"); final Label textToServerLabel = new Label(); final HTML serverResponseLabel = new HTML(); VerticalPanel dialogVPanel = new VerticalPanel(); dialogVPanel.addStyleName("dialogVPanel"); dialogVPanel.add(new HTML("<b>Sending request to the server:</b>")); dialogVPanel.add(textToServerLabel); dialogVPanel.add(new HTML("<br><b>Server replies:</b>")); dialogVPanel.add(serverResponseLabel); dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT); dialogVPanel.add(closeButton); dialogBox.setWidget(dialogVPanel); // Add a handler to close the DialogBox closeButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { dialogBox.hide(); saveOrUpdateButton.setEnabled(true); saveOrUpdateButton.setFocus(true); retrieveButton.setEnabled(true); } }); // Create a handler for the saveOrUpdateButton and employeeInfoField class SaveOrUpdateEmployeeHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the saveOrUpdateButton. */ public void onClick(ClickEvent event) { sendEmployeeInfoToServer(); } /** * Fired when the user types in the employeeInfoField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendEmployeeInfoToServer(); } } /** * Send the employee info from the employeeInfoField to the server and wait for a response. */ private void sendEmployeeInfoToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = employeeInfoField.getText(); // Then, we send the input to the server. saveOrUpdateButton.setEnabled(false); textToServerLabel.setText(textToServer); serverResponseLabel.setText(""); String[] employeeInfo = textToServer.split(" "); long employeeId = Long.parseLong(employeeInfo[0]); String employeeName = employeeInfo[1]; String employeeSurname = employeeInfo[2]; String employeeJobTitle = employeeInfo[3]; employeeService.saveOrUpdateEmployee(employeeId, employeeName, employeeSurname, employeeJobTitle, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { // Show the RPC error message to the user dialogBox .setText("Remote Procedure Call - Failure"); serverResponseLabel .addStyleName("serverResponseLabelError"); serverResponseLabel.setHTML(SERVER_ERROR + caught.toString()); dialogBox.center(); closeButton.setFocus(true); } public void onSuccess(Void noAnswer) { dialogBox.setText("Remote Procedure Call"); serverResponseLabel .removeStyleName("serverResponseLabelError"); serverResponseLabel.setHTML("OK"); dialogBox.center(); closeButton.setFocus(true); } }); } } // Create a handler for the retrieveButton and employeeIdField class RetrieveEmployeeHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the retrieveButton. */ public void onClick(ClickEvent event) { sendEmployeeIdToServer(); } /** * Fired when the user types in the employeeIdField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendEmployeeIdToServer(); } } /** * Send the id from the employeeIdField to the server and wait for a response. */ private void sendEmployeeIdToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = employeeIdField.getText(); // Then, we send the input to the server. retrieveButton.setEnabled(false); textToServerLabel.setText(textToServer); serverResponseLabel.setText(""); employeeService.findEmployee(Long.parseLong(textToServer), new AsyncCallback<EmployeeDTO>() { public void onFailure(Throwable caught) { // Show the RPC error message to the user dialogBox .setText("Remote Procedure Call - Failure"); serverResponseLabel .addStyleName("serverResponseLabelError"); serverResponseLabel.setHTML(SERVER_ERROR + caught.toString()); dialogBox.center(); closeButton.setFocus(true); } public void onSuccess(EmployeeDTO employeeDTO) { dialogBox.setText("Remote Procedure Call"); serverResponseLabel .removeStyleName("serverResponseLabelError"); if(employeeDTO != null) serverResponseLabel.setHTML("Employee Information <br>Id : " + employeeDTO.getEmployeeId() + "<br>Name : " + employeeDTO.getEmployeeName() + "<br>Surname : " + employeeDTO.getEmployeeSurname() + "<br>Job Title : " + employeeDTO.getJob()); else serverResponseLabel.setHTML("No employee with the specified id found"); dialogBox.center(); closeButton.setFocus(true); } }); } } // Add a handler to send the employee info to the server SaveOrUpdateEmployeeHandler saveOrUpdateEmployeehandler = new SaveOrUpdateEmployeeHandler(); saveOrUpdateButton.addClickHandler(saveOrUpdateEmployeehandler); employeeInfoField.addKeyUpHandler(saveOrUpdateEmployeehandler); // Add a handler to send the employee id to the server RetrieveEmployeeHandler retrieveEmployeehandler = new RetrieveEmployeeHandler(); retrieveButton.addClickHandler(retrieveEmployeehandler); employeeIdField.addKeyUpHandler(retrieveEmployeehandler); } }
As you can see, Spring service invocations are performed just like classic GWT service invocations, transparently to the client.
Finally locate the main web page for your project. The file should be named „Application.html“ and located under /src/main/resources/{main_package}/public folder of your project (in our case /src/main/resources/com/javacodegeeks/gwtspring/public). Alter the main web page as shown below
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <!-- The HTML 4.01 Transitional DOCTYPE declaration--> <!-- above set at the top of the file will set --> <!-- the browser's rendering engine into --> <!-- "Quirks Mode". Replacing this declaration --> <!-- with a "Standards Mode" doctype is supported, --> <!-- but may lead to some differences in layout. --> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!-- --> <!-- Any title is fine --> <!-- --> <title>Spring GWT Web Application Starter Project</title> <!-- --> <!-- This script loads your compiled module. --> <!-- If you add any GWT meta tags, they must --> <!-- be added before this line. --> <!-- --> <script type="text/javascript" language="javascript" src="com.javacodegeeks.gwtspring.Application.nocache.js"></script> </head> <!-- --> <!-- The body can have arbitrary html, or --> <!-- you can leave the body empty if you want --> <!-- to create a completely dynamic UI. --> <!-- --> <body> <!-- OPTIONAL: include this if you want history support --> <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe> <!-- RECOMMENDED if your web app will not function without JavaScript enabled --> <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 align="center">Spring GWT Web Application Starter Project</h1> <table align="center"> <tr> <td colspan="2" style="font-weight:bold;">Please enter employee info (id name surname job):</td> </tr> <tr> <td id="employeeInfoFieldContainer"></td> <td id="updateEmployeeButtonContainer"></td> </tr> <tr> <tr> <td colspan="2" style="font-weight:bold;">Please enter employee id:</td> </tr> <tr> <td id="employeeIdFieldContainer"></td> <td id="retrieveEmployeeButtonContainer"></td> </tr> <tr> <td colspan="2" style="color:red;" id="errorLabelContainer"></td> </tr> </table> </body> </html>
To build the application right click on your project ? Run As ? Maven package
To deploy the web application just copy the „.war“ file from the „target“ directory to Apache – Tomcat “webapps” folder
To lunch the application point your browser to the following address
http://localhost:8080/{application_name}/
If all went well you should see your main web page. Two text boxes should be displayed followed by a button each. In the first text box you can save or update an employee to the database. Provide as input the id, the name, the surname, and a job description separated by a space character. Clicking on the “SaveOrUpdate” button the provided information will be stored to the database. For existing employee entries (same id) an update will be performed. The second text box is used to retrieve existing employee entries. Provide an employee id and click on the “Retrieve” button. If the employee exists you should see the employee id, name, surname and job description.
You can download the project from here
Hope you liked it
Justin
- GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial
- GWT Spring and Hibernate enter the world of Data Grids
- Spring 3 HornetQ 2.1 Integration Tutorial
- Spring 3 RESTful Web Services
- JAX–WS with Spring and Maven Tutorial
Thanks!!! I had the same problem.
go to ‘Source’ tab and add the repository configuration:
JBoss
http://repository.jboss.org/maven2/
between ” and ”.
When you have done it, go to ‘Effective POM’ and you will see the repository added at your configuration.
Good article, but is outdate.
I have tried to make it work with Eclipse Indigo + GWT 2.4, but it doesn’t work.
Are you going to update the article?
Thanks.
Where is the EmployeeServiceAsync class definition?
I have got error “EmployeeServiceAsync cannot be resolved”
Hi did you fix the error. If so kindly let me know.how to solve this error.
The class EmployeeServiceAsync is not missing. It will be autogenerated by build. Just put into projects Run Configurations… for Maven build in Goals the following:
clean org.codehaus.mojo:gwt-maven-plugin:generateAsync install
After that just launch Run As -> Maven build and the build will succeed. I ran this tutorial application and it worked, thanks!
There is even better solution: Delete goal generateAsync from your pom.xml, so delete this line(s): generateAsync After that run Maven->Clean, create the following Java file and then run Maven->Install and the application should have no errors and should work: package com.javacodegeeks.gwtspring.shared.services; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.javacodegeeks.gwtspring.shared.dto.EmployeeDTO; public interface EmployeeServiceAsync { /** * GWT-RPC service asynchronous (client-side) interface * @see com.javacodegeeks.gwtspring.shared.services.EmployeeService */ void findEmployee( long employeeId, AsyncCallback callback ); /** * GWT-RPC service asynchronous (client-side) interface * @see com.javacodegeeks.gwtspring.shared.services.EmployeeService */ void saveEmployee( long employeeId, String name, String surname, String jobDescription, AsyncCallback callback ); /** * GWT-RPC service asynchronous… Read more »
For some reason the Application.java is not getting called .. Any clue on what could be wrong..
I am getting the following ouptut .. but no text box to enter the details
_________________________________________________________________________________
Spring GWT Web Application Starter Project
Please enter employee info (id name surname job):
Please enter employee id:
Hi There, I also got the same error and after hours I came to know that it’s a Application.html code that is causing the issue and not allowing control to go to the Application.java class. Best you can do is to keep the default generated html that got created when you first created the project and only insert the following table structure that forms the display.
Please enter employee info (id name surname job):
Please enter employee id:
It will get resolved after that.
Cheers !
Ashok…
hi, get error in this step:
3. in the „Select an Archetype“ page of the wizard, select „Nexus Indexer“ at the „Catalog“ drop down list and after the archetypes selection area is refreshed, select the „gwt-maven-plugin“ archetype from „org.codehaus.mojo“ to use. You can use the „filter“ text box to narrow search results. Hit „Next“ to continue
say this:
No archetypes currently available. The archetype list will refresh when the indexes finish updating.
help me please…
Hi, I have got error 404 beim run on Server . How to solve this ???
HTTP Status 404 – /gwtspring/com.javacodegeeks.gwtspring.Application/Application.html
type Status report
message /gwtspring/com.javacodegeeks.gwtspring.Application/Application.html
description The requested resource is not available.
Apache Tomcat/7.0.56
Hello!
How to debug this project?
Hi, thanks for tutorial. I have problem with build my project via Maven to the war. Is necessary that the Model, DAO, Service packages were inside client, server, shared packages ? Because I have these packages outside and I think that, can be problem, I try add to the gwt.gwt.xml source path for “Dao”, “Model”, “Service” but still build failure on the : Finding entry point classes [INFO] Tracing compile failure path for type ‘com.something.list.client.gwt’ [INFO] [ERROR] Errors in ‘file:/C:/Users/user/Documents/list/src/main/java/com/something/list/client/gwt.java’ [INFO] [ERROR] Line 39: No source code is available for type com.something.list.user.Service.ListOfUsersService; did you forget to inherit a required module?… Read more »
Code cannot be downloaded anymore