Posts on this Category



Integrating an Angular2 app with a PHP app

In this tutorial I’m going to show you how to use Angular2 Http client to communicate with an php application. I don’t want this to be a very long post, so I’m going to make everything as simple as possible.

The first step, of course, is to provide a php web service, it doesn’t need to be anything sophisticated, just returning a json dataset will do for now. We can achieve this by creating an php app with just an index.php file containing the following code:

<?php
 	header("Access-Control-Allow-Origin: *");
	$data = array(
		array('id' => '1','first_name' => 'Cynthia'),
		array('id' => '2','first_name' => 'Keith'),
		array('id' => '3','first_name' => 'Robert'),
		array('id' => '4','first_name' => 'Theresa'),
		array('id' => '5','first_name' => 'Margaret')
	);
 
	echo json_encode($data);
?>

As you can see, in this file I’m just manually creating my dataset. Note that I’ve included the line header("Access-Control-Allow-Origin: *"); at the beginning, by doing this I’m avoiding the Cross-Origin Request Blocked error, which is a very common error for people who are getting started with web services, no matter which programming language you are using, if you don’t allow other applications to access your service you’ll see this error.

Now let’s get started with our angular2 application, you probably already have everything set up, but if you don’t, just follow the instructions on the Angular2 Quickstart to create an empty project.

We’re going to need Http Client to be able to send requests to our server, in order to use it on our project we have to register it as a service provider on our main.ts:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import {HTTP_PROVIDERS} from '@angular/http';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [HTTP_PROVIDERS]);

Next let’s create the component, if you followed the instructions from the angular2 quickstart you already have the app.component.ts in your project, just open this file and paste the following code into it:

import {Http, Response} from '@angular/http';
import {Injectable, Component } from '@angular/core';
 
@Component({
  selector: 'my-app',
  template: `<ul>
		<li *ngFor="let person of data">
		   {{person.id}} - {{person.first_name}}
		</li>
	     </ul>`
})
export class AppComponent { 
 
    private data;
 
    constructor(private http:Http){
    }
 
    ngOnInit(){
    	this.getData();
    }
 
    getData(){
        this.http.get('http://localhost/AngularWithPhpTest/')
        		.subscribe(res => this.data = res.json());
    }
}

Most of what’s in this code probably isn’t new for you, so I won’t bother to explain all the basic things again. What matters here is the getData() method, that’s where we’re getting the data from that php web service we created at the beginning.

Now let’s see how it actually works, if you take a look at the code you’ll see that I’ve used two functions to be able to get the data: get() and subscribe(). The first receives the web service url and calls the server to get the data, while the second one specifies the actions that should be taken when it receives the response, in this case I’m just assigning the received data to the this.data variable, pretty simple right?

This was a really simple example, but feel free to leave a comment if you have any doubts. I showed you just how to load a dataset, but there are a lot more that could be done here, you don’t necessary have to get a json dataset as a result, it could be anything you want, and you could also add some parameters to your url and read them on the server-side, that would allow you to send information back and forth between your applications.

AngularJS Tutorial: Consuming Java EE Web Services

It’s very common to see people asking how to integrate Java EE applications with some of the popular JavaScript frameworks, specially with AngularJS. In most cases developers already have an application (or a great portion of it) written in Java EE containing all the business logic, and since it’s not feasible to rewrite everything in JavaScript, they look for ways to integrate and add new technology to the project without losing any existing code.

That’s when Web Services comes in handy!! They allow your AngularJS application to send and receive data from the Java EE module in a very easy way. Of course there are more sophisticated ways to do this communication, but that is a subject for another post.

The first step is to expose the Web Service in your Java EE project, I’m assuming that you already have this project ready, but if you don’t, just create one by following the instructions in this link.

Now that you already have your web service, make sure it’s working before you continue, to do that, open your browser and call your service by typing it’s URL, it should follow this pattern:

1
2
3
{domain}:{port}/{projectName}/{webServicePath}
 
//example: http://localhost:8080/WebServiceEJB-war/test

If everything is right the browser will display the data returned by your web service, if it doesn’t you’re probably missing something, make sure you followed every instruction in the example I mentioned above.

Now we can start writing some AngularJS code, after setting up the project let’s create the app.js file like this:

1
2
3
4
5
6
7
var app = angular.module('angularWS',[]);
app.controller('myController', function($scope, $http){
	$http.get('http://localhost:8080/WebServiceEJB-war/test')
		.success(function(data){
			$scope.text = data;		
		});	
});

This is the simplest way to consume a web service with angular, the $http.get function will make the request to the Java EE application, all you need to do is to pass the web service URL, when it receives the data, it will execute the callback passed to the success() function, there you can do anything you want with the data, in my case I’m just assigning it to the $scope.text variable. When your Angular application make the request, it’ll probably get an Cross-Origin Request Blocked error, in this case just follow the steps in this link to fix it.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

This is a very common error for people who are just getting started with Web Services, it’s really simple to solve but sometimes developers spend hours struggling to find a solution. It happens when you create a web service and tries to access it from a different application, it won’t work because you don’t have Cross-origin resource sharing (CORS) enabled, which means an application loaded in one domain cannot interact with resources from a different domain. All you have to do is to enable CORS.

How you can active it will depending on your scenario, in this tutorial I’m going to show how to enable CORS for a Java EE application running on Glassfish, I’m assuming you have an EJB RESTful web service similar to this one, and when other applications tries to consume it you see the Cross-Origin Request Blocked error on your firebug console, in this case all you have to do is to create a filter in your application, just create a class exactly like this one on your 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
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() {
 
    }
 
}

Now you have to register the filter in your web.xml, copy the following code and replace “yourPackage” with your actual package name:

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>

That’s it! Now your application will allow its resources to be shared with other domains.

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!

Tutorial: Creating RESTful Web Services with EJB 3.1

RESTful web services has gained a lot of acceptance across the web, they are basically web services that follows the REST guidelines. In this short tutorial I’m going to create a very simple Hello World application that implements a RESTful Web Service using EJB 3.1.

I’m assuming that you already have your environment setup and also a Java EE project created and ready to use.
So let’s get started, the first step is to create a session bean that looks like this:

1
2
3
4
5
6
7
8
9
10
@Stateless
@Path("/sayHello")
public class HelloWorld {
 
   @GET
   @Produces("text/plain")
   public String sayHello() {
       return "Hello World!!";
   }
}

That’s really a straightforward implementation, we’ve used the annotation @Path to specify the URI path we’re going to use to access this service, we also created an operation accessible via HTTP GET (indicated by the @GET annotation), and lastly we specified the media type that this operation will produce, in this case it’s a plain text, but it could also be a JSON, XML, etc.
After creating the session bean, the second and last step is to register the servlet adaptor in the web.xml:

1
2
3
4
5
<servlet>        
     <servlet-name>ServletAdaptor</servlet-name>        
     <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>        
     <load-on-startup>1</load-on-startup>    
</servlet>

That’s it! You have already created a RESTful Web Service!!
Now if you deploy you project, you can go to your browser and type http://{projectURL}/sayHello, you’ll see the string “Hello World!!” displayed on the page.

Hope this post was helpful for you,
Till next Time!