creating modern java web applications based on struts2 and angularjs

39
Creating Modern Java Web Applications Based on and ApacheCon: Core Europe 2015 by ( ) Johannes Geppert @jogep

Upload: johannes-geppert

Post on 08-Jan-2017

2.726 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Creating modern java web applications based on struts2 and angularjs

Creating Modern Java WebApplications Based on

and

ApacheCon: Core Europe 2015 by ( )Johannes Geppert @jogep

Page 2: Creating modern java web applications based on struts2 and angularjs

About meApache Member and Struts PMC Member

Software Developer @

Living and working in Leipzig

Page 3: Creating modern java web applications based on struts2 and angularjs

About Struts2Action based Javaweb frameworkBuilt upon aRequest/ResponsecycleClean architectureEasy to extendwith plugins

Page 4: Creating modern java web applications based on struts2 and angularjs

Conceptual Overview

Page 5: Creating modern java web applications based on struts2 and angularjs

Struts 2.5 is on the way!

Page 6: Creating modern java web applications based on struts2 and angularjs

Cleanup and Maintenance!Switch to Java7Increased Security withSMIxwork­core merged intostruts­coreRemoval of deprecatedpluginsDojo PluginCode Behind PluginJSF PluginStruts1 Plugin

Page 7: Creating modern java web applications based on struts2 and angularjs

Support for bean validation

Now as a (built­in) plugin available

Page 8: Creating modern java web applications based on struts2 and angularjs

Log4j2 as new Logging Layer

Replacement for Struts2Logging LayerSupport for multiplelogging implementationsBetter performance

Page 9: Creating modern java web applications based on struts2 and angularjs

Beta2 is available!

Page 10: Creating modern java web applications based on struts2 and angularjs

Why AngularJS? AngularJS is a structural framework for dynamic web apps.It lets you use HTML as your template language and letsyou extend HTML's syntax to express your application'scomponents clearly and succinctly. Angular's data bindingand dependency injection eliminate much of the code youwould otherwise have to write. And it all happens within the

browser, making it an ideal partner with any servertechnology.

https://docs.angularjs.org/guide/introduction

Page 11: Creating modern java web applications based on struts2 and angularjs

AngularJS ­ Overview

Page 12: Creating modern java web applications based on struts2 and angularjs

Google TrendsAngularJS, React, Backbone and ember.js

Blue line is the trend for AngularJS

Page 13: Creating modern java web applications based on struts2 and angularjs

Quickstart with MavenArchetypes

mvn archetype:generate ­B \ ­DgroupId=com.mycompany.mysystem \ ­DartifactId=myWebApp \ ­DarchetypeGroupId=org.apache.struts \ ­DarchetypeArtifactId=struts2­archetype­angularjs \ ­DarchetypeVersion=<CURRENT_STRUTS_VERSION> \ ­DremoteRepositories=http://struts.apache.org

cd myWebAppmvn jetty:run

Open Browser http://localhost:8080

Page 14: Creating modern java web applications based on struts2 and angularjs

REST Based Actionswith Struts2 REST Plugin

Page 15: Creating modern java web applications based on struts2 and angularjs

REST ­ Action MappingHTTP method URI Class.method Parameters

GET /order OrderController.index

GET /order/1 OrderController.show id="1"

POST /order OrderController.create

PUT /order/1 OrderController.update id="1"

DELETE /order/1 OrderController.destroy id="1"

Page 16: Creating modern java web applications based on struts2 and angularjs

Configure the REST PluginAdd the rest plugin to the dependencies

<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2­rest­plugin</artifactId> <version>$struts2.version</version></dependency>

Disable restrictToGET default behaviour<constant name="struts.rest.content.restrictToGET" value="false"/>

Create packages for applications<constant name="struts.convention.default.parent.package" value="rest­angular"/><package name="rest­angular" extends="rest­default"> <default­action­ref name="index" /></package><package name="data" extends="rest­angular" namespace="/data"></package>

Page 17: Creating modern java web applications based on struts2 and angularjs

REST ­ Content Type Handler/order/1 or /order/1.action Dispatcher (e.g. JSP)

/order/1.xml XML Handler

/order/1.json JSON HandlerEasy to build e.g. for CSV resultBuilt­in Jackson support for JSON serialization

<bean type="org.apache.struts2.rest.handler.ContentTypeHandler" name="jackson" class="org.apache.struts2.rest.handler.JacksonLibHandler"/><constant name="struts.rest.handlerOverride.json" value="jackson"/>

Page 18: Creating modern java web applications based on struts2 and angularjs

Live Demohttps://github.com/apache/struts­examples/tree/master/rest­

angular

Page 19: Creating modern java web applications based on struts2 and angularjs

Exception Handling

Page 20: Creating modern java web applications based on struts2 and angularjs

Custom ExceptionInterceptor

protected String doIntercept(ActionInvocation actionInvocation) throws Exception try return actionInvocation.invoke(); catch (Exception exception) Map<String, Object> errors = new HashMap<>(); HttpHeaders httpHeaders = new DefaultHttpHeaders() .disableCaching().withStatus(HttpServletResponse.SC_BAD_REQUEST) .renderResult(Action.INPUT); if(exception instanceof SecurityException) errors.put(ACTION_ERROR, "Operation not allowed!"); httpHeaders.setStatus(HttpServletResponse.SC_FORBIDDEN); else errors.put(ACTION_ERROR, exception.getMessage()); return manager.handleResult(actionInvocation.getProxy().getConfig(), httpHeaders, errors);

Page 21: Creating modern java web applications based on struts2 and angularjs

Extend the DefaultInterceptor Stack

<package name="data" extends="rest­angular" namespace="/data"> <interceptors> <interceptor name="dataError" class="....ExceptionHandlerInterceptor"/>

<interceptor­stack name="dataDefaultStack"> <interceptor­ref name="dataError"/> <interceptor­ref name="restDefaultStack"/> </interceptor­stack> </interceptors> <default­interceptor­ref name="dataDefaultStack"/></package>

Page 22: Creating modern java web applications based on struts2 and angularjs

Dispatch an error eventExtend the generic _request method in DataService$http(req).success(function(data) def.resolve(data);).error(function(data, code) def.reject(data); if(data.actionError) $rootScope.$emit('data­error', msg: data.actionError ); );

Page 23: Creating modern java web applications based on struts2 and angularjs

Listen to error eventse.g in a Controller

$rootScope.$on('data­error', function(event, alert) console.log(alert.msg););

Page 24: Creating modern java web applications based on struts2 and angularjs

Live Demohttps://github.com/apache/struts­examples/tree/master/rest­

angular

Page 25: Creating modern java web applications based on struts2 and angularjs

Bean Validation

Client and Server sideNew bean validation plugin

Page 26: Creating modern java web applications based on struts2 and angularjs

Setup bean validation

Page 27: Creating modern java web applications based on struts2 and angularjs

Specify a validation http status codelike "Not Acceptable"

<!­­ Set validation failure status code ­­><constant name="struts.rest.validationFailureStatusCode" value="406"/>

Page 28: Creating modern java web applications based on struts2 and angularjs

Change rest interceptor stackDefault validation interceptor is using the old validationinterceptorCopy the rest default interceptor stackDefine the new one<interceptor name="beanValidation" class="....interceptor.BeanValidationInterceptor"/>

Replace the "validation" reference with "beanValidation"reference in the stack

Page 29: Creating modern java web applications based on struts2 and angularjs

Live Demohttps://github.com/apache/struts­examples/tree/master/rest­

angular

Page 30: Creating modern java web applications based on struts2 and angularjs

Multi­Language Support

Page 31: Creating modern java web applications based on struts2 and angularjs

Where do we need it?

Frontend Validation Backend

Page 32: Creating modern java web applications based on struts2 and angularjs

Resource BundlesSplit them up!

<constant name="struts.custom.i18n.resources" value="frontend,validation,exceptions"/>

Sample for validation messages#validation_en.propertiesvalidation.order.client = Client name can not be blankvalidation.order.amount = Order amount needs to be between 10 and 666

#validation_de.propertiesvalidation.order.client = Kunden Name darf nicht leer seinvalidation.order.amount = Anzahl muss zwischen 10 und 666 sein

Page 33: Creating modern java web applications based on struts2 and angularjs

Language Controllerpublic class LanguageController extends RestActionSupport implements ModelDriven<Map<String, String>>

private Map<String, String> model;

public String index() throws Exception ResourceBundle bundle = getTexts("frontend"); this.model = bundle.keySet().stream() .collect(Collectors.toMap( key ­> key, key ­> bundle::getString));

return Action.SUCCESS;

public Map<String, String> getModel() return model;

Page 34: Creating modern java web applications based on struts2 and angularjs

Setup Angular Translate

(function() 'use strict';

angular.module('app', ['ngRoute', 'ui.bootstrap', 'pascalprecht.translate']);)();

$translateProvider.registerAvailableLanguageKeys(['en', 'de']);$translateProvider.fallbackLanguage('en');$translateProvider.useUrlLoader('data/language.json', queryParameter: 'request_locale');$translateProvider.determinePreferredLanguage();

Page 35: Creating modern java web applications based on struts2 and angularjs

With translate filter in templates'order.client' | translate

In validation messages@NotBlank(message = "validation.order.client")@Min(value = 10, message = "validation.order.amount")@Max(value = 666, message = "validation.order.amount")

In java codethrow new RuntimeException(getText("exception.not.supported"));

Page 36: Creating modern java web applications based on struts2 and angularjs

Live Demohttps://github.com/apache/struts­examples/tree/master/rest­

angular

Page 37: Creating modern java web applications based on struts2 and angularjs

Thank you!https://twitter.com/jogep

Page 38: Creating modern java web applications based on struts2 and angularjs

Resources ­

­ ­

­ ­

Apache Struts Project https://struts.apache.orgStruts2 Maven Archetypes https://struts.apache.org/docs/struts­2­maven­archetypes.htmlStruts2 Examples https://github.com/apache/struts­examplesAngularJS https://angularjs.orgAngular Translate https://angular­translate.github.io

Page 39: Creating modern java web applications based on struts2 and angularjs

AttributionsLeipzig Pictures by

by by

by by

by by

Ruthe Cartoon by by

by by

by by

Johannes GeppertModel in the wind tunnel DLR ­ German Aerospace CenterRoad NicolaClean Up Allen GoldblattBeans MatthewMatrix pills ThomasThomasShaking Hands Aaron Gilson

ruthe.deLanguage Scramble Eric AndresenWindows Box Perfection Rachel KramerKrakow Door John Finn1949 Ford Coupe ­ flat head V8 engine dave_7Questions Alexander Henning Drachmann