Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Recipe for Angular in a Java EE Environment: Two Improvements

DZone's Guide to

The Recipe for Angular in a Java EE Environment: Two Improvements

Discussion of a project that provides a Maven multi-module project that integrates Angular and JavaEE and is designed to be run in Eclipse and Wildfly.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

The project Angular2AndJavaEE is now stable. It provides a Maven multi-module project that integrates Angular and JavaEE. The project is designed to be run in Eclipse and Wildfly. It has an in-memory DB so no further setup is needed. The intention is to provide a starting point for everybody who wants to use Angular in a Java EE environment. To get to the point of calling the Angular2AndJavaEE project stable, two major improvements have been implemented.

  1. The Maven build now uses npm to call the Angular-CLI.
  2. The Angular front-end uses the Angular-CLI proxy feature to call the REST services.

The front-end is updated to the most recent version of Angular and will be updated to the future versions.

There are more updates like a bit of eye candy on the root component or a pop-up, but those are minor improvements.

The Maven Build

Step 4

It builds the Angular application with Angular-CLI and A package.json script of npm.

<execution>
  <id>angular-cli build</id>
  <goals>
    <goal>exec</goal>
  </goals>
  <phase>generate-resources</phase>
  <configuration>
    <executable>npm</executable>
    <arguments>
      <argument>run</argument>
      <argument>build</argument>
    </arguments>
    <workingDirectory>${basedir}/target/angular/carrental</workingDirectory>
  </configuration>
</execution>

In line 6, the phrase "generate-resources" is used to run the execution after the "npm install" step.

In the lines 8-11, the "npm run build" of the package.json file is executed.

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build --prod --aot --base-href /carrental-web/de/ --output-path dist/de --i18n-locale de --i18nFile=./src/locale/messages.xlf && ng build --prod --aot --base-href /carrental-web/en/ --output-path dist/en --i18n-locale en --i18nFile=./src/locale/messages.en.xlf",
    "test": "ng test --browsers PhantomJS --watch=false",
    "test-junit": "ng test --browsers PhantomJS --reporters junit --single-run",
    "lint": "ng lint",
    "e2e": "ng e2e"    
},

In line 4, the build for German and English is executed. The Angular-CLI is called with the same arguments that have been described in the article about the Aot build.

Step 5

It executes the tests with Angular-CLI and the npm package.json.

<execution>
  <id>angular-cli test</id>
  <goals>
    <goal>exec</goal>
  </goals>
  <phase>test</phase>
  <configuration>
    <executable>npm</executable>
    <arguments>
      <argument>run</argument>
      <argument>test</argument>
    </arguments>
    <workingDirectory>${basedir}/target/angular/carrental</workingDirectory>
  </configuration>
</execution>

In line 6, the phrase "test" is used to execute the tests after everything is built.

In line 8-11, "npm run test" of the package.json is executed.

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build --prod --aot --base-href /carrental-web/de/ --output-path dist/de --i18n-locale de --i18nFile=./src/locale/messages.xlf && ng build --prod --aot --base-href /carrental-web/en/ --output-path dist/en --i18n-locale en --i18nFile=./src/locale/messages.en.xlf",
    "test": "ng test --browsers PhantomJS --watch=false",
    "test-junit": "ng test --browsers PhantomJS --reporters junit --single-run",
    "lint": "ng lint",
    "e2e": "ng e2e"       
},

In line 5, the "test" script is used to have Angular-CLI execute the tests on the PhantomJS browser with watch=false to have a single run.

These changes to the build make different profiles for different OSs redundant because npm and node need to be installed on the systems anyway and they take care of the differences. That simplifies the build.

REST Interface

Angular-CLI has a proxy feature that makes it possible to route the REST requests from the browser to the proxy and the REST interface of Wildfly. Angular-CLI is started in development with the "npm start" command that includes the proxy config for Angular-CLI. The former CORS problem is solved that way because the application is served by Angular-CLI and the REST requests are sent to the Angular-CLI proxy. That makes the distinction between REST calls in dev or prod environments in the crrest.service.ts redundant. It also simplifies the REST interface on the server side because the "Options" calls are no longer needed. Now the handling of the REST calls in dev and prod environments are the same.

First the config for the Angular-CLI proxy:

{
  "/carrental-web": {
    "target": "http://localhost:8080/",
    "secure": false
  }
}

In line 2, the URL part that is proxied is set.

In line 3, the target to which the requests are sent is set.

In line 4, secure could be set to true if the requests have to be sent to the server with HTTPS.

Second, the Angular service:

@Injectable()
export class CrRestService {
    static readonly NEWID = 'newId';
    private _crTableUrlProd = '/rest/model/crTable/mietNr/{mietNr}';  // URL to web api
    private _crDetailUrlProd = '/rest/model/crDetail/mietNr/{mietNr}/jahr/{jahr}';
    public _crPdfUrlProd = '/rest/model/crTable/mietNr/{mietNr}/pdf';
    public _baseHRef = '/carrental-web';
    private _reqOptionsArgs =  { headers: new HttpHeaders().set( 'Content-Type', 'application/json' ) };

    constructor( private http: HttpClient, private pl: PlatformLocation ) {        
    }

    getCrTableRows( policeNr: string ) : Observable<CrTableRow[]> {
        let url = this._baseHRef + this._crTableUrlProd;       
        url = this.cleanUrl(url);
        url = url.replace( "{mietNr}", policeNr );
        console.log(url);
        return this.http.get<CrTableRow[]>( url, this._reqOptionsArgs).pipe(catchError( this.handleError ));
}

In lines 14-16, the URL is created.

In line 18, the REST request is made to the service with the pipe feature of Rxjs 6 in Angular 6. The result is an Observable of CrTableRows.

Third, the Java EE REST service:

@RequestScoped
@Path("/model/crTable")
@Produces({ "application/json" })
@Api(value = "/model/crTable")
public class CrTableResource {
  @Inject
  private CrTableService service;

  public CrTableResource() {
  }

  public CrTableResource(CrTableService service) {
    this.service = service;
  }

  @GET
  @Path("/mietNr/{mietNr}")
  @DisableCaching
  @ApiOperation(value = "gets the rows for the table", response = CrTableRow.class, responseContainer = "List")
  public Response getAll(@PathParam("mietNr") final String mietNr, 
    @HeaderParam("Accept-Language") final String acceptLang) {
    String[] langs = acceptLang.split(",");
    Locale locale = Locale.forLanguageTag(langs[0]);
    return Response.ok(service.readCrRowsByMiete(mietNr, locale)).build();  
  }

In lines 16-18, the REST interface gets defined.

In line 19, the information for Swagger is provided.

In lines 20-21, the path param and the language param are retrieved.

In lines 22-23, the language is converted in a Locale.

In line 24, the service in a session bean is called and the result returned in a Response.

Conclusion

The Angular2AndJavaEE project is now stable. The improvements are done and the Angular and Java EE features are used to make the integration of both technologies simple. The project will be maintained and upgraded to current versions of Angular and Wildfly. The news of the project can be found in the project diary.

Angular and Java EE are a match that makes full-stack development for Java developers a very nice option. Both technologies complement each other and make front-end development fun again. The reason to separate front-end from backend teams is disappearing. Depending on existing backends this technology stack enables the integration of more Agile aspects in the development process. Angular can be the next step forward for Java EE applications.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
maven ,java ee ,angular ,angular cli ,WEB DEV

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}