Spring MVC Angular Js integration without template engine - angularjs

I would like to integrate Spring MVC with Angular JS without any Template Engine
I checked a few answers, but I could not resolve it . Below I have listed Xml,Controller and Html files. What I am missing here exactly?
app-Servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<annotation-driven />
<context:component-scan base-package="com.angular.app" />
<resources mapping="/views/**" location="/WEB-INF/views/" />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<beans:property name="order" value="1" />
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="html" value="text/html" />
</beans:map>
</beans:property>
</beans:bean>
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="order" value="2" />
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value="" />
</beans:bean>
</beans:beans>
Controller
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home.html";
}
#RequestMapping(value="/app/welcome",method = RequestMethod.GET)
public #ResponseBody String welcome() {
logger.info("entering into original controller");
System.out.println("entering into original controller");
String text="Hello World!!!! Welcome";
return text;
}
home.html
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="">
<div>
Name: <input type="text" ng-model="name">
</div>
<p ng-bind="name"></p>
<div ng-controller="helloworldcontroller">
<h1>{{title}}</h1>
</div>
</div>
<script>
function helloworldcontroller($scope, $http) {
$http.get("http://localhost:8080/app/welcome").success(
function(response) {
$scope.title = response;
alert("sucess");
});
}
</script>
</body>
</html>

I'm working on some projects using the architecture Spring MVC + AngularJs and can give you feedback about:
You are trying to control the routes of html pages through the Spring MVC Contollers and I think this is not the best approach, since the AngularJs has its own engine to control routes and pages through the ng-route or ui-router.
In architectures of my projects work with a Spring MVC project providing a whole REST API to be consumed by a web AngularJs application.
The project structure is as follows:
parent-maven-project:
|_project-core: Have all bussiness logic, data source config, persistence config, Services, Repositories, Entities, etc.
|_project-web: Have a angularJs App (that controls the html pages routing using ui-router), API REST (Spring MVC Controllers) to be consumed and give the business layer access (project-core).
|_project-ear: Pack core and web projects to deploy on JBoss EAP 6.2
In Spring MVC REST layer (project-web) | set up a Spring OAuth2 server that is used to authenticate users and make the session & access control through Spring Security. When the user logs into the application, the angularjs application receives an access token Bearer that is used to make the user requests during all the time that he remain logged in. All REST services are in request scope, are stateless, then the token is used to retrieve the Spring Security session and make all user access validation.

Related

On page load using Asp.net mvc angularjs (data-ng-Init)

Hi i have create that sending request to asp.net web api when page loads using angularjs 'data-ng-Init' this is working on localhost and local IIS server but it is not working on Server System IIS server. for explanation purpose
html code
<div ng-controller="myCtrl">
<div ng-if="status==true">
<input type="date" ng-model="date" ng-change="getyear("#Url.Content("~/api/getDate")")" />
<div data-ng-Init="GetData('#Url.Content("~/api/getDate")')></div>
</div>
<div ng-if="status==false">
<input type="date" ng-model="date" ng-change="getYear("#Url.Content("~/api/getYear")")" />
<div data-ng-Init="GetYear('#Url.Content("~/api/getYear")')></div>
</div>
</div>
AngularJS
$scope.getData=function(link){
$http({
method:'POST',
url:link,
data:{data:'somedata'}
}).then(function(result){
...result
},function(error){
...error
});
}]);
like this i have return.
i can send request without writing the code in function, but i have two div's tag which is written in if condition any one div tag will executes.
And the code was working when ng-change means when change the date its working fine but only not working when page loads 'data-ng-Init'.
I am Getting Error like this "192.124.213.12/projectname/api/getDate/ 500 Internal Server Error"

Swagger in Angularjs

I am trying to add swagger in my Angularjs project
OBJECTIVE
I want to test my API via swagger by sending a payload and in return I will get response code 200.
I am following tutorials:
https://www.phpflow.com/jquery-plugin-2/how-to-integrate-swagger-with-angular/
http://orange-opensource.github.io/angular-swagger-ui/ (WORKING DEMO of TUTORIAL)
What I have done so far:
Added these two libraries in my project
<script src="bower_components/angular-swagger-ui/dist/scripts/swagger-ui.js"></script>
<link rel="stylesheet" href="bower_components/angular-swagger-ui/dist/css/swagger-ui.min.css">
HTML
<div >
<h3 class="dispInline">Rest Json file:</h3>
<form name="urlForm" ng-submit="urlForm.$valid&&(swaggerUrl=url)" class="form-inline dispInline">
<input type="url" placeholder="swagger URL" class="form-control" id="url" method="post" name="url" ng-model="url" required style="width:400px">
<button type="submit" class="btn btn-primary">explore</button>
</form>
<div swagger-ui url="swaggerUrl" try-it="true" error-handler="myErrorHandler" transform-try-it="myTransform"></div>
</div>
CONTROLLER
$scope.url = 'https://server.event.com/alert/event/1.0/eventpublicationmanagement_01/events';
// error management
$scope.myErrorHandler = function(data, status){
alert('failed to load swagger: '+status);
console.log(data);
};
// transform try it request
$scope.myTransform = function(request){
request.headers['Authorization'] = 'Bearer 123123123-1231-123-134313313c';
};
But when I click on explore, I get 405 error that method is not allowed. My method is post but browser is somehow sending GET. My token is also not sending in request. How can I solve that?
Also, I am confused because with working of swagger, My API is published on WSO2 API Store which contains a default swagger and my API swagger looks something like this:
If I shall call my API by clicking on explore button, will it show/return an option like API Store is showing? -> /eventpublicationmanagement_01/events
How will I set my JSON as well?
I am very confused. Some guidance and help will be very much appreciated.
To use Swagger You need a swagger.json file. More info You can find in the link: How to generate swagger.json

How to use polymer client side routing with app engine endpoints?

My application makes use of polymer for front-end and app engine endpoints (Java) for my backend. For reasons I don't understand, my endpoints client is not loading and I could see some strange url requests failing which seem to have been modified by app-route in my polymer front-end. I see the following failures:-
https://(app-id).appspot.com/_ah/api/images/gweld_logo.png - Failed to load
resource: the server responded with a status of 404 ()
https://(app-id).appspot.com/src/_ah.html - Failed to load resource: the server responded with a status of 404 ()
My polymer code is based on the starter kit provided by polymer-cli. Here's the code for my-app.html:-
<app-location route="{{route}}"></app-location>
<app-route
route="{{route}}"
pattern="/:page"
data="{{routeData}}"
tail="{{subroute}}"></app-route>
.
.
<template is="dom-if" if="{{!userSignedIn}}">
<div class="container">
<paper-card image="/images/gweld_logo.png" alt="(Company Name)" class="logo">
<div class="card-content horizontal layout center-justified">
Company Portal
</div>
<div class="card-actions horizontal layout center-justified">
<google-signin label-signin="Sign-in"
client-id="(client-id)"
scopes="https://www.googleapis.com/auth/userinfo.email"
signed-in="{{userSignedIn}}">
</google-signin>
</div>
</paper-card>
</div>
</template>
<template is="dom-if" if="{{userSignedIn}}">
.
.
<iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
<a name="view1" href="/view1" paper-drawer-toggle>View One</a>
</iron-selector>
.
.
<iron-pages
selected="[[page]]"
attr-for-selected="name"
fallback-selection="view404"
role="main">
<my-view1 name="view1"></my-view1>
<my-view404 name="view404"></my-view404>
</iron-pages>
.
.
</template>
.
.
Polymer({
is: 'my-app',
properties: {
page: {
type: String,
reflectToAttribute: true,
observer: '_pageChanged'
}
},
observers: [
'_routePageChanged(routeData.page)'
],
_routePageChanged: function(page) {
this.page = page || 'view1';
},
_pageChanged: function(page) {
// Load page import on demand. Show 404 page if fails
var resolvedPageUrl = this.resolveUrl('my-' + page + '.html');
this.importHref(resolvedPageUrl, null, this._showPage404, true);
},
_showPage404: function() {
this.page = 'view404';
}
In my-view1.html, I make use of google-client-loader element to load the client for my app engine endpoints api.
Here's how I defined static-files in appengine-web.xml:-
<static-files>
<include path="/service-worker.js"/>
<include path="/bower_components/**.js"/>
<include path="/*.json"/>
<include path="/index.html"/>
<include path="/src/**.html"/>
<include path="/bower_components/**.html"/>
<include path="/bower_components/**.css"/>
<include path="/images/*.png"/>
<include path="/**.ico"/>
</static-files>
I have the following in my web.xml:-
<servlet>
<servlet-name>SystemServiceServlet</servlet-name>
<servlet-class>com.google.api.server.spi.SystemServiceServlet</servlet-class>
<init-param>
<param-name>services</param-name>
<param-value>(values removed here)</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SystemServiceServlet</servlet-name>
<url-pattern>/_ah/spi/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
While I want index.html to be loaded for all requests, I don't want any request to load the client library intercepted by my client side routing. Please let me know how I can solve the above issues. Also, what is the correct practice to use client side routing (app-route) with app engine endpoints?

ASP.NET Webforms and AngularJS

I'm still struggling to get my first ASP.NET WebApi / AngularJS app up and running...
I'm trying to query a WebAPI service (which I've written and verified using Fiddler that it works just fine) from Angular, and I'm trying to show the data returned on my ASP.NET Webforms page. I studied a great many tutorials and Pluralsight courses, and really thought I knew how to do it - but Angular doesn't agree with me :-(
I have my Angular app/controller here:
var app = angular.module('MyApp', []);
app.controller('MyCtrl', function ($scope, $http) {
$scope.model = [];
//Call to web API
var Url = 'http://localhost:13811/api/v1/mydata';
$http({
method: 'GET',
url: Url
}).success(function (MyList) {
$scope.model = MyList;
}).error(function () {
});
});
My (very limited) JS/Angular understanding is that this defines an Angular app and a controller, and that if I add this controller to a DOM element on my ASPX page, the controller will be invoked, will make that call out to my WebAPI service (and I do see that this is happening), and then stores the results (a list of some data objects from the database) into the $scope.model variable.
So I was assuming that I would be able to integrate this into a blank ASPX something like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoAngular.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Angular Demo</title>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/app/plz-controller.js"></script>
</head>
<body ng-app="MyApp">
<form id="form1" runat="server">
<div ng-controller="MyCtrl">
<span>Angular says: {{1+2}} </span>
<div class="list-group" data-ng-repeat="x in model">
<div class="list-group-item">
<span>{{x.Field1}}</span><br/>
<span>{{x.Field2}}</span><br/>
</div>
</div>
</div>
</form>
</body>
</html>
I was assuming that adding the ng-app="MyApp" directive to the <body> tag would link the ASPX page to the Angular app, and adding the ng-controller="MyCtrl" to that <div> would then instantiate the Angular controller (and thus make the WebAPI call - this it does, I see that in the F12 developer tools).
I was also expecting that by using the data-ng-repeat="x in model" directive, I would be able to iterate over the list of data elements returned from the WebAPI call, and using the {{....}} syntax, I was hoping to be able to access the individual fields of those objects and display them.
ALAS: I do see Angular says: 3 at the top of my page, so Angular appears to be "there" and active, and I do see the WebAPI call in the F12 developer tools (and I can verify that the expected number of data elements is being returned) - yet no matter what I try, I cannot find any way to actually SHOW that data having been retrieved from WebAPI on my ASPX page......
Any ideas? What am I missing? Must be something really stupid - I'm sure - but I just don't see the forest for the trees anymore........
Fire up the debugger and put a breakpoint on the $scope.model = MyList line. Chances are that you're getting an http response object back here and you need to change it to something like $scope.model = MyList.data. Examining the object in the debugger will tell you for sure if this is the case.

Spring MVC4 + AngularJS - Resolve css/js and JSP

I'm trying to integrate Spring MVC4 + Angular JS but i have some problems to load template from AngularJS side. On the net there are a lot of resources, but IMHO a bit confused.
Right now i've setup a simple controller that render a page under webapp/WEB-INF/jsp. This works fine but when in this page i try to load js (angular library) i got error (resource unavailable).
I've added this to my view.jsp and resource is not loaded:
<script src="resources/js/angular/angular.js"></script>
I'm my dispatcher-servlet.xml i have the follow configuration:
<mvc:annotation-driven />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
To load correctly my angular library, i have to use c tag library, why ?
<script src="<c:url value="/resources/js/angular/angular.js" />"></script>
Next on it, i have created a template under webapp/WEB-INF/jsp/templates/main.jsp and i'm trying to load it using $routeProvider (i've tried to load main.jsp too, but the error is the same - resource not found)
angular.module('MyApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/main'
});
});
My answer is:
How i can load "library" without using c taglib ?
What i have to add to my configuration to load templates from AngularJs ? (using templateUrl) ?
Thanks a lot!

Resources