I’m not going to go over all the reasons why you should have a RESTful service with javascript front-end (e.g. clean separation of front- and back-end, reusable web service components, etc). Here I’ll just show how you can quickly set up a RESTful web service in Java and a javascript/jQuery front-end to access it.
The server part requires just 4 things:
1) Add Jersey dependency
2) Write a java bean and annotate it
3) Write a Service class
4) Deploy the servlet in web.xml
1) Add Jersey dependency
If you’re using Maven, then add the following Jersey (JAX-RS implementation) dependency to your pom.xml
<dependency>
<groupId>com.cedarsoft.rest</groupId>
<artifactId>jersey</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
2) Write a java bean and annotate it
Create a java bean with the following:
1) annotate the class with @XmlRootElement
2) make sure there’s a null constructor (no arguments)
3) add public setters/getters
import javax.xml.bind.annotation.XmlRootElement
@XmlRootElement
public class Foo {
private String name;
public Foo() { }
public String getName() { return name; }
public void setName(String s) { name = s; }
}
3) Write a Service class
package com.kodingnotes.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path ("/foo")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class FooService {
@GET
@Path("/read")
public Foo getFoo(@QueryParam("input") String input) {
Foo foo = new Foo();
foo.setName(input);
return foo;
}
}
4) Deploy the servlet in web.xml
In your web.xml, add the following servlet
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<!-- ##### REFER TO THE PACKAGE WHERE YOU WANT JERSEY TO PICK UP THE RESOURCE CLASSES ###### -->
<!-- ##### Use semi-colon to specify multiple packages ###### -->
<param-value>com.kodingnotes.services</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.feature.logging.DisableEntitylogging</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JerseyREST</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Edit the <param-value> of the <param-name>com.sun.jersey.config.property.packages<param-name>