Sunday, January 23, 2011

How to - Configure GWT 2.1 with Spring 3.0.5 and Hibernate 3.5.x or 3.6.x

Configuring GWT 2.1 with Spring 3.0.5 and Hibernate 3.5.x or 3.6.x

Step 1 : Download the corrosponding jar files for Spring 3.0.5 and Hibernate. Download the GWT 2.1 Application and create a gwt sample application via webAppCreator.

Spring:http://www.springsource.org/download
Hibernate:http://www.hibernate.org/downloads
GWT:http://code.google.com/webtoolkit/download.html

WebAppCreator command to create a sample GWT application -

webAppCreator -out MyWebApp com.mybasepackage.MyWebApp


Step 2: Create a web.xml file with configuration as below, where mywebapp denotes the main class file for gwt containing onmoduleload() routine -


PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">




org.springframework.web.context.ContextLoaderListener







mywebapp
org.springframework.web.servlet.DispatcherServlet
1



mywebapp
*.rpc



MyWebApp.html




Step 3: Create an application context file for spring configuration -


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="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">















base-package="com.yourapp.yourbasepackage" />




Step 4: Create servlet config file with name - mywebapp-servlet.xml -for dispatcher servlet to refer to -


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="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">


base-package="com.mybasepackage" />




greetController





















Step 5: Create Hibernate and DataSource config xml files -

Hibernate -

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-3.0.xsd">


class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">







org.hibernate.dialect.Oracle10gDialect
true





com.mybasepackage.server.model.greetTable






DataSource -

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-3.0.xsd">


class="org.springframework.jdbc.datasource.DriverManagerDataSource">








Step 6: Create a GreetGwtRpcController class which extends RemoteServiceServlet(GWT) and implements Controller & ServletContext(Spring)

package com.mybasepackage.server.rpc;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;


import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GreetGwtRpcController extends RemoteServiceServlet implements Controller, ServletContext{


/**
*
*/
private static final long serialVersionUID = 1L;

private ServletContext servletContext;

private RemoteService remoteService;

@SuppressWarnings("unchecked")
private Class remoteServiceClass;

@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {

super.doPost(request, response);

return null;
}

@Override
public String processCall(String payload) throws SerializationException {
try {

System.out.println("Invoked process call.." );
RPCRequest rpcRequest = RPC.decodeRequest(payload,
this.remoteServiceClass, null);

System.out.println("RPC request is .." + rpcRequest );

// delegate work to the spring injected service
return RPC.invokeAndEncodeResponse(this.remoteService, rpcRequest
.getMethod(), rpcRequest.getParameters());

} catch (IncompatibleRemoteServiceException ex) {
getServletContext()
.log(
"An IncompatibleRemoteServiceException was thrown while processing this call.",
ex);
System.out.println("Exception is caught .." );
return RPC.encodeResponseForFailure(null, ex);
}
}

@Override
public Object getAttribute(String name) {
// TODO Auto-generated method stub
return null;
}

@Override
public Enumeration getAttributeNames() {
// TODO Auto-generated method stub
return null;
}

@Override
public ServletContext getContext(String uripath) {
// TODO Auto-generated method stub
return null;
}

@Override
public String getContextPath() {
// TODO Auto-generated method stub
return null;
}

@Override
public int getMajorVersion() {
// TODO Auto-generated method stub
return 0;
}

@Override
public String getMimeType(String file) {
// TODO Auto-generated method stub
return null;
}

@Override
public int getMinorVersion() {
// TODO Auto-generated method stub
return 0;
}



@Override
public String getRealPath(String path) {
// TODO Auto-generated method stub
return null;
}

@Override
public RequestDispatcher getRequestDispatcher(String path) {
// TODO Auto-generated method stub
return null;
}

@Override
public URL getResource(String path) throws MalformedURLException {
// TODO Auto-generated method stub
return null;
}

@Override
public InputStream getResourceAsStream(String path) {
// TODO Auto-generated method stub
return null;
}

@Override
public Set getResourcePaths(String path) {
// TODO Auto-generated method stub
return null;
}

@Override
public String getServerInfo() {
// TODO Auto-generated method stub
return null;
}

@Override
public Servlet getServlet(String name) throws ServletException {
// TODO Auto-generated method stub
return null;
}

@Override
public String getServletContextName() {
// TODO Auto-generated method stub
return null;
}

@Override
public Enumeration getServletNames() {
// TODO Auto-generated method stub
return null;
}

@Override
public Enumeration getServlets() {
// TODO Auto-generated method stub
return null;
}

@Override
public void log(Exception exception, String msg) {
// TODO Auto-generated method stub
System.out.println("check");
}

@Override
public void removeAttribute(String name) {
// TODO Auto-generated method stub

}

@Override
public void setAttribute(String name, Object object) {
// TODO Auto-generated method stub

}

@Override
public ServletContext getServletContext() {
return servletContext;
}

public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}

public void setRemoteService(RemoteService remoteService) {
this.remoteService = remoteService;
this.remoteServiceClass = this.remoteService.getClass();
}

@Override
public RequestDispatcher getNamedDispatcher(String name) {
// TODO Auto-generated method stub
return null;
}
}

This class will create a webContext session and inject the bean implementation which is being invoked via rpc.

Step 7: Remove the @Service annotation from GreetingServiceImpl class and remove the extends clause for RemoteServiceServlet which gets generated when the webAppCreator creates the project.

GreetingServiceImpl.java

package com.mycompany.mywebapp.server;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Service;

import com.mycompany.mywebapp.client.GreetingService;
import com.mycompany.mywebapp.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
* The server side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class GreetingServiceImpl implements
GreetingService {

@PostConstruct
public void init() throws Exception {
}

@PreDestroy
public void destroy() {
}
public String greetServer(String input) 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 = "testingSI"; // getServletContext().getServerInfo();
String userAgent = "testingUA"; //getThreadLocalRequest().getHeader("User-Agent");

// Escape data from the client to avoid cross-site script vulnerabilities.
input = escapeHtml(input);
userAgent = escapeHtml(userAgent);

return "Hello, " + input + "!

I am running " + serverInfo
+ ".

It looks like you are using:
" + userAgent;
}

/**
* Escape an html string. Escaping data received from the client helps to
* prevent cross-site script vulnerabilities.
*
* @param html the html string to escape
* @return the escaped string
*/
private String escapeHtml(String html) {
if (html == null) {
return null;
}
return html.replaceAll("&", "&").replaceAll("<", "<").replaceAll(
">", ">");
}
}

Step 8: Annotate the service path with @RemoteServiceRelativePath("greet.rpc") in GreetService interface class.

Step 9: Compile the classes using 'ant build'.

This will act as reference for servlet dispatcher to dispatch all incoming requests to the beans as defined in mywebapp-servlet.xml

That's it - restart the application in dev mode and you should be good to go!.

No comments:

Post a Comment