React.js Tutorial: Consuming JavaEE RESTful Web Services

In this post I’m going to show how to consume Web Services with React.js, more specificalyJavaEE RESTful Web Services. I’ve already written a post showing how to create these web services with EJB 3, if you haven’t seen it yet just click on this link for more details, but if you’re already familiar with Java EE feel free to skip it and create your owm web service.

For this tutorial I’m going to use the following service (Which is almost the same as I created on the other post):

1
2
3
4
5
6
7
8
9
10
11
@Stateless
@Path("/test")
public class WebServiceTest {
 
    @GET
    @Produces("text/plain")
    public String test() {
        return "Web Service Test";
    }
 
}

This is as simple as it gets, just a method returning a string, simple as that! If you deploy the project you’ll be able to see the text “Web Service Test” on your browser by adding /test to the end of your URL:

Java EE REST Web Service Example
Java EE REST Web Service Example

Now let’s create the React.js project to consume this web service. Again, I already have a post about how to get started with React.js, click on the link to see it, though it doesn’t say anything about how to consume web services it can still be useful for those who are not familiar with react.

Since my goal here is to just show how to consume a web service, I’ll keep the react code very simple as well, just copy the following code into your index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
    <head>
        <title>React Flux</title>
        <script src="https://fb.me/react-0.13.3.js"></script>
        <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body>
        <div id="component"></div>
 
        <script type="text/jsx">
            var JavaEEWSTest = React.createClass({
                getInitialState: function () {
                    return {text: ''};
                },
                componentDidMount: function(){
                    $.ajax({
                        url: "http://localhost:8080/WebServiceEJB-war/test"
                    }).then(function(data) {
                        this.setState({text: data});
                    }).bind(this)
                },
                render: function() {
                    return <div>Response - {this.state.text}</div>;
                }
            });
 
            React.render(<JavaEEWSTest />, document.getElementById('component'));
 
        </script>
    </body>
</html>

As you can see I have 3 functions here: getInitialState, componentDidMount and render. They do exactly what their names sugest, the first one sets all the initial values, the second executes when the component is mounted, and the last one is responsible for rendering the component. The most important for us is the componentDidMount, that’s where the web service is called, and after it receives the response it will be assigned to the variable ‘text’.

We’re almost done, now if you execute it you will probably see the following error (you need firebug installed):

Cross-Origin Request Blocke
Cross-Origin Request Blocke

To see more details about this error click here, to solve it just add the following filter to your Java EE project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
 
public class CORSFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, x-auth-token, "
                + "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
 
}

And in the web.xml:

1
2
3
4
5
6
7
8
<filter>
    <filter-name>cors</filter-name>
    <filter-class>yourPackage.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Perfect!! Now if you refresh the page this will be the result:

Simple React.js application getting data from Java EE REST Web Service
Simple React.js application getting data from Java EE REST Web Service

It’s really simple, but the string ‘Web Service Test’ is coming from our web service.

Hope this tutorial was helpful for you, till next time!

Recommended for you

3 comments on “React.js Tutorial: Consuming JavaEE RESTful Web Services

  1. Steve Howard

    I don’t know why, but when I ran what is above, I constantly received a “TypeError: $.ajax(…).then(…).bind is not a function” error. I changed the call to…

            componentDidMount: function(){
              $.get("http://myhost/test",
                 function(data) {
                   this.setState({text: data});
                 }.bind(this));
            },

    …and all was well with the world.

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>