Angular-Route with Spring MVC - angularjs

I am new to angular-js.I am creating a sample application to understand the usage of Angular-route.My Webapp is a Spring Web-MVC Application.
I have home page with following two tabs:
Add Record
View Record
find below its code snippet: home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Home</title>
<jsp:include page="taskAppCommonJs.jsp"/>
</head>
<body ng-app="taskApp">
<form id="taskForm" name="taskForm">
<table width="100%" bgcolor="black" border="0">
<tr>
<td>
<div class="main_menu">
<ul>
<li> Add Record</li>
<li> View Record</li>
</ul>
</div>
</td>
</tr>
</table>
<div ng-view></div>
</form>
</body>
</html>
taskAppCommonJs.jsp
<%
final String ctxPath = request.getContextPath();
%>
<script type="text/javascript" src="<%=ctxPath%>/resources/js/jquery-3.1.1-min.js"></script>
<script type="text/javascript" src="<%=ctxPath%>/resources/js/jquery-1.12.1-ui.js"></script>
<script type="text/javascript" src="<%=ctxPath%>/resources/js/angular-1.4.8-min.js"></script>
<script type="text/javascript" src="<%=ctxPath%>/resources/js/angular-route.js"></script>
<script type="text/javascript" src="<%=ctxPath%>/resources/js/taskAppAngular.js"></script>
<link rel="stylesheet" type="text/css" href="<%=ctxPath%>/resources/css/jquery-ui.css"/>
<link rel="stylesheet" type="text/css" href="<%=ctxPath%>/resources/css/menu_style.css"/>
taskAppAngular.js
var customerApp = angular.module('taskApp', [ 'ngRoute' ]);
customerApp.config(function($routeProvider) {
$routeProvider
.when('view', {
templateUrl : 'viewTask.html',
controller : 'activityController'
})
.when('add', {
templateUrl : 'createTask.html',
controller : 'activityController'
});
});
customerApp.controller('activityController',function($scope){
$scope.createInfo="create page";
$scope.viewInfo="view page";
});
Spring Controller Class:
#Controller
public class TaskController implements Serializable{
#RequestMapping(value = "/createTask.html", method = RequestMethod.GET)
public String createTask() {
System.out.println("createTask invoked");
return "createTask";
}
#RequestMapping(value = "/viewTask.html", method = RequestMethod.GET)
public String viewTask() {
System.out.println("viewTask invoked");
return "viewTask";
}
}
viewConfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
My createTask.jsp and viewTask.jsp is inside /WEB-INF/view/ folder.
createTask.jsp
<p ng-bind="createInfo"></p>
viewTask.jsp
<p ng-bind="viewInfo"></p>
My problem is angular router is not working.
Can anyone provide any solution to this????

You are missing / before view and add:
it should read:
.when('/view',....
.when('/add',....

Your states in the config should be,
$routeProvider
.when('/view', {
templateUrl : 'viewTask.html',
controller : 'activityController'
})
.when('/add', {
templateUrl : 'createTask.html',
controller : 'activityController'
});
});

Related

Spring Boot ngRoute

I'm trying to make a single page application with a Spring back end and an AngularJS front end. I've followed tutorials and looked up similar questions but ngRoute just doesn't seem to work with a Spring back end (I got it to work with a NodeJS back end).
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Spring Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="../static/index.js"></script>
</head>
<body ng-app="index" ng-controller="indexController">
test
<div ng-view=""></div>
</body>
</html>
test.html
<div>
Template loaded
</div>
index.js
'use strict';
const indexModule = angular.module('index', ['ngRoute']);
indexModule.controller("indexController", function indexController($scope) {
});
indexModule.config(function($routeProvider) {
$routeProvider.when('/test', {templateUrl: 'test.html'});
});
SringDemoController.java
package com.springdemo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SpringDemoController {
#RequestMapping({ "/" })
public String getIndexTemplate() {
return "index";
}
}
I get this error when I click the link and the URL changes to http://localhost:8080/test
Here is the solution.
The Index page :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test title</title>
</head>
<body ng-app="TestApp">
<div>
<h1>The Index</h1>
<ul>
<li>
<a ng-href="#!/test"> Temp One</a>
</li>
</ul>
<div ng-view=""></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-route.js"></script>
<script src="js/config.js"></script>
<script src="js/controller/main.js"></script>
<script src="js/controller/test.js"></script>
</body>
</html>
The Router config (its called config.js)
'use strict'
angular.module('TestApp' , ["ngRoute"])
.config(function($routeProvider){
$routeProvider
.when('/' , {
templateUrl : "view/main.html",
controller : 'MainController',
controllerAs : 'main'
})
.when('/test' , {
templateUrl : "view/test.html",
controller : 'TestController',
controllerAs : 'test'
})
.otherwise({
redirectTo: '/'
});
});
And the server-side controller for the route :
package com.testApp;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class ServerController {
#RequestMapping(value = "/test")
public String getTestTemp() {
return "static/test";
}
}
UPDATE :
actually, the method inside the ServerController is not needed. It can be written as follows
package com.testApp;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping(value = "/test")
public class ServerController {
}
So if you write any REST method in this controller, the endpoint from both client and server side will be /test/{the Name of your endPoint }
Here is the Project Structure
If you add more templates, make sure you create the routeon the client side and also the server side

AngularJS: Load resources from one project into another

I have two Spring Boot projects, Project1 and Project2. I have angular code in both the projects under 'static' folder. I am trying to route to the resources in Project2 from Project1 as below,
src/main/resources/static/index.html (in Project1)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="app.js">
</script>
</head>
<body>
<a ui-sref="spendCar">Click here to go to Spend Cat of Project2</a>
</body>
</html>
src/main/resources/static/app.js (in Project1)
var proj1 = angular.module('proj1', ['ui.router']);
proj1.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'partial-home.html'
})
.state('spendcat', {
url: '/spendcat',
templateUrl : 'http://localhost:8090/spendcat' //calling Project2's end point
});
});
In Project2 I have a controller as below,
#Controller
#RequestMapping("/spendcat")
#CrossOrigin
public class SpendCatController {
#RequestMapping(value = "", method = RequestMethod.GET)
public String getSpendCatPage() {
return "spendcatpage"; //spendcatpage.html is under 'static' folder.
}
}
src/main/resources/static/spendcatpage.html (in Project2)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="sc.js">
</script>
</head>
<body>
<div>Welcome to spend category page</div>
<input type="button" onclick="doClick()" value="Click Here">
</body>
</html>
I get error when "Click Here" button is clicked. If the javascript function doClick() is directly included in html file, then it works. Please suggest me how to load all resources of project2 in project1.

Unable to map angular UI with spring mvc

Dispatcher:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.nt.beans" />
<mvc:resources mapping="/resources/**" location="/" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value></value>
</property>
</bean>
</beans>
Controller class:
#Controller
public class IndexController {//Serves main index.html
#RequestMapping("/**")
public String getIndexPage() {
return "/";
}
}
UI-Router:
myApp.config(function ($stateProvider, $locationProvider, $urlRouterProvider) {
// For any unmatched url, redirect to /login
$urlRouterProvider.otherwise("/Login");
// Now set up the states
$stateProvider
.state('Login', {
url: "/Login",
views: {
header: header,
content: {
templateUrl: 'views/Login.html',
controller: function () {
}
},
footer: footer
}
});
$locationProvider.html5Mode({
enabled: false,
requireBase: true
});
});
index jsp page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>BulkSMS - HTML</title>
<base href="/BulkSMS2/">
<!-- Bootstrap core CSS -->
<link href="resources/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<!--font-awesome-->
<link href="resources/bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<!--Bootstrap social-->
<link href="resources/bower_components/bootstrap-social/bootstrap-social.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="wrap">
<!--main content-->
<div ui-view="content"></div>
</div>
<!--Bootstrap core JavaScript-->
<script src="resources/bower_components/bootstrap/dist/js/bootstrap.min.js" type="text/javascript"></script>
<!--angular related scripts-->
<script src="resources/bower_components/angular/angular.min.js" type="text/javascript"></script>
<script src="resources/bower_components/angular-ui/build/angular-ui.min.js" type="text/javascript"></script>
<script src="resources/bower_components/angular-ui-router/release/angular-ui-router.min.js" type="text/javascript"></script>
<script src="resources/js/angular_module.js" type="text/javascript"></script>
<script src="resources/js/controllers/StateProvider.js" type="text/javascript"></script>
<script src="resources/js/controllers/LoginController.js" type="text/javascript"></script>
</body>
</html>
When I run the app, it is supposed to load login.html but it showing error in console like:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8084/BulkSMS2/resources/bower_components/bootstrap-social/bootstrap-social.css"
The prefix in dispatcher.xml is WEB-INF/views so the login.html page inside it should load and also in the controller I am returning the path as / so any unmatched url pattern should load login page according to state provider.

angular js , spring MVC angular JS code is not working in spring

snippet of my spring MVC is
#RequestMapping(value = "/list2", method = RequestMethod.GET,headers="Accept=*/*",produces = "application/json")
public ResponseEntity<List<Employe>> listAllUsers() {
List<Employe> users = dataService.getList();
if(users.isEmpty()){
return new ResponseEntity<List<Employe>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Employe>>(users, HttpStatus.OK);
}
my angular js controller is like below
'use strict';
var app = angular.module('app',[]);
app.controller('EmpController', function($scope, httpq) {
httpq.get('http://localhost:8080/SpringHibernate/list2')
.then(function(data) {
$scope.users = data;
})
.catch(function(data, status) {
console.error('Gists error', response.status, response.data);
})
.finally(function() {
console.log("finally finished gists");
});
});
my index.jsp is
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head ng-app="app" >
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859- 1">
<title>SpringHibernate</title>
</head>
<body >
<h1>Welcome to Spring Hibernate Project!!!</h1>
Please Click this Link To Proceed
Please Click this Link To Proceed
<div ng-controller="EmpController">
<!--Body content-->
<input ng-model="query"> Type to Search</input>
<ul>
<li ng-repeat="user in users | filter:query | orderBy:orderProp">
<p>{{user.firstName}}
<p>{{user.lastName}}
<p>{{user.email}}
<p>{{user.phone}}
</li>
</ul>
</div>
<script src="<c:url value="/resources/js/angular.min.js" />" type="text/javascript"></script>
<script src="<c:url value="/resources/js/app.js" />" type="text/javascript"></script>
</body>
</html>
after launching the code i am neither getting any log in my browser it looks like angular is not executing at all. please let me know what other details would be required. I have used the same URL in Postman it successfully generates the JSON response.
You put the ng-app attribute on the <head> element. So, only the head is handled by angular. The rest is purely static html, that angular doesn't care about.
Put in on <html> or on <body>.
Note that the error would be much easier to spot, by yourself, if your html code was correctly indented.

backbone router Implementation not working

Below is my HTML file RouterExample.html. I am trying to create a router. But it is not working.
Have i imported all necessaries?
When i try to run the code i get the html page as designed. When i click on any of the HREF objects, the object's name is getting appended to the URL but getting JBOSS, which is my server home page.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.1/underscore-min.js"></script>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.1/backbone-min.js"></script>
<script src="scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script src="scripts/underscore.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="backbone.js"></script>
<script type="text/javascript" src="router.js"></script>
</head>
<body>
One
Two
Three
One
Two
Three
<table>
<tr>
<td id="one">1</td>
<td id="two">2</td>
</tr>
<tr>
<td id="three">3</td>
<td id="four">4</td>
</tr>
</table>
<script>
$(function(){
var AppRouter = Backbone.Router.extend({
routes: {
'RouterExample.html': 'home',
'one' : 'oneFun'
},
home : function()
{
alert("Home");
},
oneFun: function()
{
alert("One Function");
}
});
var fovView = new AppRouter();
Backbone.history.start();
});
</script>
</body>
</html>
Your anchor tags are linking to another document because the href values start with /. Try this:
One
Two
Three
One
Two
Three

Resources