display the post data in the angular js jsp page - angularjs

i have a form designed with angular js, upon submit it post the data to the spring controller, which intern processes the data to be displayed in the new jsp page.
part 1: form submit through angular js to the spring controller (Completed)
part 2: Spring controller to process the post data and return the json string object (completed)
part 3: The data received in the success part of the spring controller and displaying the data in the new jsp page (yet to completed, need help).
Problem here is that i can post the json data , but could not able to display the json date in the jsp page (AuditDisplayResultPage.jsp), basically i cannot accomplish the part3.
part 1 source code
AuditDisplayPage.jsp
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="/LDODashBoard/js/scripts.js" language="JavaScript" type="text/javascript"></script>
<script src="/LDODashBoard/js/AuditDisplayPage.js" language="JavaScript" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>
<link rel="stylesheet" type="text/css" href="/LDODashBoard/css/mystyle.css" />
<link rel="stylesheet" type="text/css" href="/LDODashBoard/css/AuditDisplayPage.css" />
<body>
<div ng-app="myApp" ng-controller="myCtrl" style="color:white" div align="left">
<br/><br/>
<form name = "audit" novalidate>
<label for="marketArraySel" >Market:</label>
<select id="marketArraySel" ng-model="marketArraySel" ng-options="market as getMarketFullName(market) for market in marketArray | orderBy:'name' track by market.id" ng-change="updateChanges()" ng-selected="selectedExpression()">
<option value="">[NO SELECTION]</option>
</select>
<label for="accountText" >Account:</label>
<input type="text" id="accountText" ng-model="accountName" ng-change="onAccountTextChange()"></input>
<br/>
<label for="marketNameType" >Type the Market:</label>
<input type="text" id="marketNameType" ng-model="marketNameType" ng-change="selectmarketByName(marketNameType)" />
<br/><br/>
<label for="textareavalue" ng-show="marketArraySel.id && accountName">Selected Details:</label>
<textarea id="textareavalue" ng-model="textareavalue" style="color:blue" disabled ng-show="marketArraySel.id && accountName">{{textareavalue}}</textarea>
<br />
<!--
<span size=10><STRONG> Selected Market: {{marketArraySel.name}} </STRONG> </span>
<span id="tab"></span>
<span id="tab"></span>
<span id="tab"></span>
<span id="tab"><STRONG> Selected Account: {{accountName}} </STRONG></span>
-->
<br/> <br/>
<input type="reset" ng-click="reset()" value="RESET"></input>
<input type="button" ng-click="submitfunction()" value="SUBMIT" ng-disabled="!marketArraySel.id && !accountName"></input>
</form>
<br><br>
<span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span><span id="tab"></span>
<c:url value="/L1OutputDisplayPage?gcmmLink2=true" var="messageUrl2" />
Click Here
to Close
</div>
</body>
</html>
AuditDisplayPage.js
$scope.submitfunction = function() {
var dataObj = {
name : getById($scope.marketArray,$scope.marketArraySel.id),
account : $scope.accountName,
database : getDatabaseById($scope.marketArray,$scope.marketArraySel.id)
};
$http({
'url' : '/LDODashBoard/AuditDisplayPost',
'method' : 'POST',
'headers': {'Content-Type' : 'application/json'},
'data' : dataObj
})
.success(function(data, status, headers,config,ele) {
window.alert('Success4');
$scope.message = data;
//covert the json object to string
//var message1 = JSON.stringify($scope.message);
window.alert('message1:' + message1);
//window.location("/LDODashBoard/AuditDisplayPostResponse?argument1=" + "hello");
window.location("/LDODashBoard/AuditDisplayPostResponse?argument1=" + message);
/*
Message value
{"cvAuditClassList":[{"db_seq":13084,"operator":"cricha19","action":"I","cv_table":12,"id":3006538,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":31244,"operator":"cricha19","action":"I","cv_table":12,"id":3014027,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":40739,"operator":"gdennis2","action":"U","cv_table":5,"id":3014027,"comments":"Clair:AAKASH AGARWAL;"},{"db_seq":56740,"operator":"mzak1","action":"I","cv_table":12,"id":3043260,"comments":"Acc:YP3CW;Firm:L;Off:;Sungard:;"},{"db_seq":56748,"operator":"mzak1","action":"I","cv_table":12,"id":3043264,"comments":"Acc:YP3CW;Firm:L;Off:;Sungard:;"},{"db_seq":52647,"operator":"bkamins11","action":"I","cv_table":12,"id":3041524,"comments":"Acc:YP3CW;Firm:L;Off:;Sungard:;"},{"db_seq":76771,"operator":"rmarczak","action":"I","cv_table":12,"id":3053777,"comments":"Acc:YP3CW;Firm:L;Off:;Sungard:;"},{"db_seq":76772,"operator":"rmarczak","action":"I","cv_table":13,"id":3053777,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":74719,"operator":"iteppel","action":"I","cv_table":13,"id":3043264,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":74749,"operator":"iteppel","action":"I","cv_table":13,"id":3043260,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":79437,"operator":"aimierow","action":"I","cv_table":12,"id":3054314,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":79438,"operator":"aimierow","action":"I","cv_table":13,"id":3054314,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":113297,"operator":"iteppel","action":"I","cv_table":12,"id":3106380,"comments":"Acc:B825M;Firm:L;Off:;Sungard:;"},{"db_seq":113298,"operator":"iteppel","action":"I","cv_table":13,"id":3106380,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":113299,"operator":"iteppel","action":"U","cv_table":5,"id":3106380,"comments":"Clair:cs;"},{"db_seq":113300,"operator":"iteppel","action":"I","cv_table":9,"id":3006538,"comments":"Name:%GI-YP2MD%;Broker:%;Ctr:%;CbType:0;AccOptFut:47;CtrType:;"},{"db_seq":113301,"operator":"iteppel","action":"D","cv_table":9,"id":3006538},{"db_seq":113302,"operator":"iteppel","action":"I","cv_table":9,"id":3006538,"comments":"Name:%GI-YP2MD%;Broker:CSBLO;Ctr:%;CbType:0;AccOptFut:47;CtrType:;"},{"db_seq":113303,"operator":"iteppel","action":"D","cv_table":9,"id":3006538},{"db_seq":113304,"operator":"iteppel","action":"I","cv_table":9,"id":3006538,"comments":"Name:%GI-YP2MD%;Broker:CSILO;Ctr:%;CbType:0;AccOptFut:47;CtrType:;"},{"db_seq":109823,"operator":"mskiba","action":"I","cv_table":12,"id":3082104,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":109824,"operator":"mskiba","action":"I","cv_table":13,"id":3082104,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":125379,"operator":"mpeitsc1","action":"I","cv_table":12,"id":3118253,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":125380,"operator":"mpeitsc1","action":"I","cv_table":13,"id":3118253,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":125382,"operator":"mpeitsc1","action":"I","cv_table":12,"id":3118254,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":125383,"operator":"mpeitsc1","action":"I","cv_table":13,"id":3118254,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":125385,"operator":"mpeitsc1","action":"I","cv_table":12,"id":3118255,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":125386,"operator":"mpeitsc1","action":"I","cv_table":13,"id":3118255,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"},{"db_seq":125388,"operator":"mpeitsc1","action":"I","cv_table":12,"id":3118256,"comments":"Acc:YP2MD;Firm:L;Off:;Sungard:;"},{"db_seq":125389,"operator":"mpeitsc1","action":"I","cv_table":13,"id":3118256,"comments":"Idcp1:CREDIT SUISSE;Idcp2:;Idcp3:;"}]}
*/
})
.error(function(data, status, headers, config) {
window.alert('Error2');
$scope.message1 = data;
});
window.alert("alert4");
};
part 2 source code
DatabaseController.java
#RequestMapping(value = "/AuditDisplayPost", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String auditDisplayPost(
#RequestBody AuditDisplayPostClass postClass, UriComponentsBuilder ucb) {
QueryExecutionResults execResults = null;
log.info("inisde AuditDisplayPost method");
log.info("auditdisplaypostclass name:" + postClass.getName());
log.info("auditdisplaypostclass account:" + postClass.getAccount());
log.info("auditdisplaypostclass database:" + postClass.getDatabase());
CVAuditDisplayResponse auditResponse = new CVAuditDisplayResponse();
CVAuditStaticUserParams cvstaticparams = new CVAuditStaticUserParams();
cvstaticparams.setNames(DBCheckoutBean.retrieveStringTokenQuery(postClass.getAccount()," "));
execResults = queryexecutorimplbean.executeQueryWrapperByQueryID(CommonConstants.CVAuditStaticUser,postClass.getDatabase(),cvstaticparams);
List <CVAuditStaticUserClass> listobject = execResults.getCvAuditStaticRowColRslt();
log.info("CVAuditStaticUser execResults list object size:" + listobject.size());
auditResponse.setCvAuditClassList(listobject);
log.info("Converting the auditresponse object to json string");
String json = new Gson().toJson(auditResponse);
log.info("printing the json:" + json);
return json;
}
part 3 source code ( NEED YOUR HELP)
DatabaseController.java
#RequestMapping(value = "/AuditDisplayPostResponse", method = RequestMethod.GET,consumes=MediaType.APPLICATION_JSON_VALUE)
public ModelAndView auditDisplayResponse(
#RequestParam(value = "argument1", required = false) String argument1){
log.info("inisde auditDisplayResponse method");
String json = "";
try {
//convert string to json
json = "[" + argument1 + "]";
log.info("argument1:" + argument1);
log.info("argument1 json:" + json);
}
catch(Exception e){
e.printStackTrace();
}
return (new ModelAndView("AuditDisplayResultPage","DisplayResponse",json));
//return (new ModelAndView("L1OutputDisplayPage","message",json));
}

umm..
log.info("inisde auditDisplayResponse method");
Map<String, String> model = new HashMap<String,String>();
try {
//convert string to json
json = "[" + argument1 + "]";
log.info("argument1:" + argument1);
log.info("argument1 json:" + json);
model.put("jsonData", json);
}
catch(Exception e){
e.printStackTrace();
}
return (new ModelAndView("AuditDisplayResultPage","DisplayResponse",model));
and client side
<html>
<body>
<h2>message : ${jsonData}</h2>
</body>
</html>

Related

WebSocket + AngularJS client

Goal: Develop a WebSocket + AngularJS client
My goal is to create a WebSocket client using AngularJS, the program is expected to send a message to the java server which replies with the same message and the date.
The server side works fine (it is shown below, (implemented using java)
I have tested it with a regular javascript web socket program)
My issue:
The client-side with AngularJS doesn't work.
Maybe I used the wrong library for this project.
Here is the WebSocket library I use for AngularJS :
https://github.com/AngularClass/angular-websocket
Client side - this doesn't work - what am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="lib/angular.min.js"></script>
<script type="text/javascript" src="lib/angular-websocket.js"></script>
<script type="text/javascript">
var app = angular.module('websocket',[]);
app.service('WebSocketWrapper', ['$log', '$websocket', '$rootScope', function($log, $websocket, $rootScope){
this.ws = null; // Attach ws to service object
this.state = 'initializing';
this.message = 'websocket initializing';
var self = this;
this.init = function(){
if(!this.ws){
this.ws = $websocket('ws://127.0.0.1:8080/WebSocketHome/echo', null, {reconnectIfNorNormalClose: true});
this.ws.onClose(function(){
console.info('close');
$rootScope.$apply(function(){
self.state = 'disconnected';
self.message = 'Websocket disconnected';
});
});
this.ws.onOpen(function(){
console.info('connected');
$rootScope.$apply(function(){
self.state = 'connected';
self.message = 'websocket connected';
});
});
this.ws.onMessage(function(message){
console.log("RECEIVED : " + message);
});
}
};
}]);
app.controller('WebSocketStateCtrl', ['$scope', 'WebSocketWrapper', function($scope, WebSocketWrapper){
$scope.websocket = WebSocketWrapper;
$scope.websocket.init();
$scope.sendMsg = function sendMsg() {
var message = textId.value;
display("Message send : " + message);
websocket.send(message);
//ws.send(message);
}
$scope.display = function display(message) {
var ligne = document.createElement("p");
ligne.innerHTML = message;
messageDiv.appendChild(ligne);
}
}]);
</script>
</head>
<body>
<div id="messageDivId"></div>
ClickMe
<!-- this div displays the status of the websocket connection -->
<div data-ng-controller="WebSocketStateCtrl">
<span data-ng-bind="websocket.message"></span>
<span class="circle" data-ng-class="{initializing: websocket.state === 'initializing',
connected : websocket.state === 'connected',
disconnected: websocket.state === 'disconnected',
reconnecting: websocket.state === 'reconnecting'}">
</span>
<div style="text-align: center;">
<form action="">
<input id="textId" name="message" value="" type="text">
<button ng-click="sendMsg()">SEND</button>
</form>
</div>
</div>
</body>
</html>
Server side - This works fine:
package org.example.websocket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class DeviceWebSocketServer {
#OnMessage
public String echo(String message){
System.out.println("Message reçu : " + message);
return ThreadSafeFormatter.getDateFormatter().format(new Date()) + " " + message;
}
}
class ThreadSafeFormatter {
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
#Override
protected SimpleDateFormat initialValue(){
return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
}
};
public static DateFormat getDateFormatter(){
return formatter.get();
}
}
HTML Page Code
The html page in regular javascript which shows the server side works fine :
<!DOCTYPE html>
<html>
<head>
<title>Test WebSockets</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script language="javascript" type="text/javascript">
var wsUri = getRootUri() + "/WebSocketHome/echo";
function getRootUri() {
return "ws://"
+ (document.location.hostname == "" ? "localhost" : document.location.hostname)
+ ":"
+ (document.location.port == "" ? "8080" : document.location.port);
}
function init() {
messageDiv = document.getElementById("messageDivId");
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
}
function onOpen(evt) {
afficher("CONNECTE");
}
function onMessage(evt) {
afficher("RECU : " + evt.data);
}
function onError(evt) {
afficher('<span style="color: red;">ERREUR:</span> ' + evt.data);
}
function envoyer() {
var message = textId.value;
afficher("ENVOYE : " + message);
websocket.send(message);
}
function afficher(message) {
var ligne = document.createElement("p");
ligne.innerHTML = message;
messageDiv.appendChild(ligne);
}
window.addEventListener("load", init, false);
</script>
</head>
<body>
<h2 style="text-align: center;">Client WebSocket Echo</h2>
<div style="text-align: center;">
<form action="">
<input id="textId" name="message" value="" type="text">
<input onclick="envoyer()" value="Envoyer" type="button">
</form>
</div>
<div id="messageDivId"></div>
ClickMe
</body>
</html>

Submit button needs to be clicked twice to call onSuccess Adaptor function in IBM Mobile First

I am using AngularJS in a IBM MobileFirst Platform Foundation app. I have a login form and when I click the Login button it collects some data and passes it to adapter invoke function. If it is successful it never calls success loginSuccess function. I need to click Login button twice so that the success function is called.
Why do I need to click button twice?
app.js
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$stateProvider.state('login', {
url: '/login',
templateUrl: 'view/login.html',
controller: 'loginController'
});
});
login.js
app.controller('loginController', function($scope) {
$scope.login = function(usrName, pass) {
var usrName = angular.element('#usrName').val();
var pass = angular.element('#pass').val();
console.log("Variable values: " + usrName + " : " + pass);
$scope.loginProcedure = {
adapter: 'SQL',
procedure: 'login',
parameters: [usrName, pass]
};
WL.Client.invokeProcedure($scope.loginProcedure, {
onSuccess: $scope.loginSuccess,
onFailure: $scope.loginFailure
});
$scope.loginSuccess = function(data) {
$scope.data = data;
$scope.resultSet = data.resultSet;
console.log('success: ' + JSON.stringify($scope.data + " : " + $scope.resultSet));
};
$scope.loginFailure = function() {
console.log('failed');
};
}
});
SQL-impl.js
/*
* Licensed Materials - Property of IBM
* 5725-I43 (C) Copyright IBM Corp. 2011, 2013. All Rights Reserved.
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*/
/************************************************************************
* Implementation code for procedure - 'procedure1'
*
*
* #return - invocationResult
*/
var loginStatement = WL.Server.createSQLStatement("select usrname,password from jay1 where usrname = ? and password=? ");
function login(usr, pass) {
return WL.Server.invokeSQLStatement({
preparedStatement: loginStatement,
parameters: [usr, pass]
});
}
/************************************************************************
* Implementation code for procedure - 'procedure2'
*
*
* #return - invocationResult
*/
function procedure2(param) {
return WL.Server.invokeSQLStoredProcedure({
procedure: "storedProcedure2",
parameters: [param]
});
}
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>AB</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/bootstrap-responsive.min.css" />
<script>
window.$ = window.jQuery = WLJQ;
</script>
</head>
<body ng-app="myApp">
<!--application UI goes here-->
<div id="view" ui-view></div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
<script src="library/jquery.min.js"></script>
<script src="library/angular.1.4.9.js"></script>
<script src="library/angular-ui-router.min.js"></script>
<script src="library/bootstrap.min.js"></script>
<script src="controller/app.js"></script>
<script src="controller/login.js"></script>
</body>
</html>
login.html
<div ng-controller="loginController" class="col-xs-12 col-sm-6 col-md-4 center-block" id="lgBlock">
<!-- Login Box Start -->
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-body">
<form class="form-group" name="lgForm">
<input type="text" class="form-control" id="usrName" required />
<input type="password" class="form-control" id="pass" required />
<input type="submit" class="btn btn-primary btn-block" id="submit" value="Login" ng-click="login()" />
</form>
</div>
</div>
<!-- Login Box End -->
<!-- error Modal start -->
<div class="modal" role="modal" id="errorPopup">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">Error</div>
<div class="modal-body"></div>
</div>
</div>
</div>
<!-- error Modal End -->
</div>
Which is correct way to parse JSON data using angularJS $scope?
1) $scope.data = data; $scope.resultSet = data.resultSet;
2) $scope.data = data; $scope.resultSet = $scope.data.resultSet;
You should take advantage of AngularJS two-way binding an update your login controller as follows:
login.js
app.controller('loginController', function($scope) {
$scope.login = function() {
// TODO: if block to validate user input i.e., username and password
$scope.loginProcedure = {
adapter: 'SQL',
procedure: 'login',
parameters: [$scope.username, $scope.password]
};
WL.Client.invokeProcedure($scope.loginProcedure, {
onSuccess: $scope.loginSuccess,
onFailure: $scope.loginFailure
});
console.log($scope.loginProcedure);
$scope.loginSuccess = function(data) {
$scope.data = data;
// resultSet is part of data so you don't need to refrences
// you can use $scope.data.resultSet to access resultSet
console.log('success: ' + JSON.stringify($scope.data + " : " + $scope.data.resultSet));
};
$scope.loginFailure = function() {
console.log('failed');
};
}
});
You should also update your view to declare the binding for username and password
login.html
<div ng-controller="loginController" class="col-xs-12 col-sm-6 col-md-4 center-block" id="lgBlock">
<!-- Login Box Start -->
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-body">
<form class="form-group" name="lgForm">
<input type="text" class="form-control" id="usrName" ng-model="username" required />
<input type="password" class="form-control" id="pass" ng-model="password" required />
<input type="submit" class="btn btn-primary btn-block" id="submit" value="Login" ng-click="login()" />
</form>
</div>
</div>
<!-- Login Box End -->
<!-- error Modal start -->
<div class="modal" role="modal" id="errorPopup">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">Error</div>
<div class="modal-body"></div>
</div>
</div>
</div>
<!-- error Modal End -->
</div>
The way you pass data to the $scope is totally up to you and your needs. My suggestion is to determine what you need and only bind that to the $scope for example if you only need data.resultSet then you should do $scope.resultSet. On the other hand, if you need complete access to the data object then you should bind data to the $scope and the you can still access the resultSet from there i.e., $scope.data.resultSet
Suggestions:
Only bind the things you need to reference in the view to the $scope for example you don't need access to the loginSuccess nor loginFailure in the view and you are only using those two functions once, so I recommend you update your loginController as follows:
app.controller('loginController', function($scope) {
$scope.login = function() {
// TODO: if block to validate user input i.e., username and password
$scope.loginProcedure = {
adapter: 'SQL',
procedure: 'login',
parameters: [$scope.username, $scope.password]
};
WL.Client.invokeProcedure($scope.loginProcedure, {
onSuccess: function(data) {
$scope.data = data;
// resultSet is part of data so you don't need to refrences
// you can use $scope.data.resultSet to access resultSet
console.log('success: ' + JSON.stringify($scope.data + " : " + $scope.data.resultSet));
},
onFailure: function() {
console.log('failed');
}
});
}
});

#RestController VS #Controller in Spring MVC with AngularJs

I want to create an application with Spring MVC Rest Web services and angularJs.
So my probleme is when i put in my controller #Controller everythings works (I have my page home1.jsp) but when i use #RestController my browser display a String ("home1").
Can you please help to understand my probleme, Thanks.
Here is my code:
*AppController
#RestController
#RequestMapping("/service")
public class AppController {
#Autowired
MyService myService;
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/home1", 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 "home1";
}
// GET ALL
#RequestMapping(value="/allProfiles",method = RequestMethod.GET,headers="Accept=application/json")
public List<Profil> getProfils()
{
System.out.println("RestControllern methode initialized");
return myService.getAllProfiles();
}
#RequestMapping(value="/allPatterns",method = RequestMethod.GET,headers="Accept=application/json")
public #ResponseBody List<Pattern> getPatterns()
{
logger.info("Welcome home! allPatterns {}.");
System.out.println("RestControllern methode initialized");
Pattern p = new Pattern();
p.setId(5);
p.setValue("moiuuyyt");
return myService.getAllPattern();
}
#RequestMapping(value="/allComponents",method = RequestMethod.GET,headers="Accept=application/json")
public List<Component> getComponents()
{
return myService.getAllComponent();
}
//GET ONE
#RequestMapping(value="/components/{id}",method = RequestMethod.GET,headers="Accept=application/json")
public Component getComponent(#PathVariable int id)
{
return myService.getComponentById(id);
}
#RequestMapping(value="/profiles/{id}",method = RequestMethod.GET,headers="Accept=application/json")
public Profil getProfil(#PathVariable int id)
{
return myService.getProfilById(id);
}
#RequestMapping(value="/patterns/{id}",method = RequestMethod.GET,headers="Accept=application/json")
public Pattern getPattern(#PathVariable int id)
{
return myService.getPatternById(id);
}
//SAVE
#RequestMapping(value="/addpattern/{value}",method= RequestMethod.POST, headers="Accept=application/json")
public String addPattern(#PathVariable String value)
{
Pattern pat = new Pattern();
pat.setValue(value);
myService.addPattern(pat);
return "redirect:/service/allPatterns";
}
#RequestMapping(value="/addprofil",method = RequestMethod.POST,headers="Accept=application/json")
public void addProfil()
{
Profil pr = new Profil();
pr.setProfilName("Profil1");
myService.addProfil(pr);
}
#RequestMapping(value="/addcomponent",method = RequestMethod.POST,headers="Accept=application/json")
public void addComponent(Component cp)
{
myService.addComponent(cp);
}
public MyService getMyService() {
return myService;
}
public void setMyService(MyService myService) {
this.myService = myService;
}
/**
* #return The page of all Patterns after we have updated one of them to test the method
*/
#RequestMapping(value="/updatepattern/{i}/{value}",method= RequestMethod.PUT, headers="Accept=application/json")
public String updatePattern(#PathVariable int i,#PathVariable String value)
{
/*List<Pattern> liste = myService.getAllPattern();
Pattern p = liste.get(0);
p.setValue("^/[0-9]Pattern has been updated");
myService.updatePattern(p);*/
Pattern p = myService.getPatternById(i);
p.setValue(value);
myService.updatePattern(p);
return "redirect:/service/home1";
}
/**
* #return The page of all Patterns after we have deleted one of them to test the method
*/
#RequestMapping(value="/deletepattern/{id}",method= RequestMethod.DELETE, headers="Accept=application/json")
public String DeletePattern(#PathVariable int id)
{
/*List<Pattern> liste = myService.getAllPattern();
Pattern p = liste.get(3);*/
Pattern p = myService.getPatternById(id);
myService.deletePattern(p);
return "redirect:/service/home1";
}
}
***Home1.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<!Doctype html>
<html data-ng-app="myTest" lang="en">
<head>
<title>Home</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body >
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
<hr/>
<div data-ng-controller="myController" style="margin-left: 100px">
<div>
<p>ALL PATTERNS</p>
<button class="btn btn-default" data-ng-click = "listPattern()">All Patterns</button>
<br/><br/>
<table class="table" data-ng-hide="state" style="width: 600px">
<tr>
<th>Id_Pattern</th>
<th>Pattern</th>
</tr>
<tr data-ng-repeat="p in patterns">
<td>{{p.id}}</td>
<td>{{p.value}}</td>
</tr>
</table>
</div>
<br/><br/><hr/>
<div>
<h3>ADD PATTERN</h3>
<form class="form-inline">
<div class="form-group">
<input type ="text" class="form-control" placeholder="Pattern value" data-ng-model="value"/>
<button class="btn btn-default" data-ng-click = "addPattern()">New Pattern</button>
</div>
</form>
</div>
<br/><br/><hr/>
<div>
<h3>UPDATE PATTERN</h3>
<form class="form-inline">
<div class="form-group">
<input type ="text" class="form-control" placeholder="PATTERN_ID" data-ng-model="selectedPattern"/>
<input type ="text" class="form-control" placeholder="new Pattern value" data-ng-model="newvalue"/>
<button class="btn btn-default" data-ng-click = "updatePattern()">Update</button>
</div>
</form>
</div>
<br/><br/><hr/>
<div>
<h3>DELETE PATTERN</h3>
<form class="form-inline">
<div class="form-group">
<input type ="text" class="form-control" placeholder="PATTERN ID" data-ng-model="id_pattern"/>
<button class="btn btn-default" data-ng-click = "deletePattern()">Delete</button>
</div>
</form>
</div>
</div>
<script>
var module = angular.module('myTest',[]);
module.controller('myController',function($scope,$http){
//function to get Patterns Lists
$scope.state = true;
$scope.listPattern = function() {
$http({method: 'GET', url: 'allPatterns'}).
success(function(data) {
$scope.patterns = data;
$scope.state = !$scope.state;
});
};
/*Function to add pattern
#param the pattern value
#return pattern lists
*/
$scope.addPattern = function(){
if($scope.value == "" )
{
alert("You must Enter all specified fields");
}
else
{
$http({method:'POST', url:'addpattern/'+$scope.value}).
success(function (data){
$scope.patterns = data;
$scope.state = false;
});
}
};
/*Function to update pattern
#param the pattern value
#return pattern lists
*/
$scope.updatePattern = function(){
if($scope.newvalue == "" || $scope.selectedPattern == "")
{
alert("You must Enter all specified fields");
}
else
{
$http({method:'PUT', url:'updatepattern/'+$scope.selectedPattern+'/'+$scope.newvalue}).
success(function (data){
$scope.patterns = data;
$scope.state = false;
});
}
$scope.newvalue="";
$scope.selectedPattern="";
};
/*Function to update pattern
#param the pattern value
#return pattern lists
*/
$scope.deletePattern = function(){
if($scope.id_pattern == "" )
{
alert("You must Enter all specified fields");
}
else
{
$http({method:'DELETE', url:'deletepattern/'+$scope.id_pattern}).
success(function (data){
$scope.patterns = data;
$scope.state = false;
});
}
$scope.id_pattern="";
};
$scope.value="";
$scope.state = true;
});
</script>
</body>
</html>
web.xml
contextConfigLocation
/WEB-INF/spring/root-context.xml
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/home1.jsp</welcome-file>
</welcome-file-list>
***dispatcher****
<?xml version="1.0" encoding="UTF-8"?>
<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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- Enable annotation-based Spring MVC controllers (eg: #Controller annotation) -->
<mvc:annotation-driven/>
<context:annotation-config/>
<!-- Classpath scanning of #Component, #Service, etc annotated class -->
<context:component-scan base-package="com.demo.projet1.controllers" />
<context:component-scan base-package="com.demo.projet1.services" />
<context:component-scan base-package="com.demo.projet1.repositories" />
<jpa:repositories base-package="com.demo.projet1.repositories"/>
<!-- Resolve view name into jsp file located on /WEB-INF -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
When using #RestController annotation, all #RequestMapping methods assume #ResponseBody semantics by default. That's why home1 is being returned as String. If you are mixing a JSP view and Responsebody, then i would suggest to go with #Controller annotation.

How do i get multiple values from a popup window then insert it in the database

im new here so could anyone help me. im trying to make a document tracking system and im having problems in getting multiple values from a popup window then inserting them in the database table so that the only people who could access those documents are those on the inserted list. can anyone help me please?? >_< newbie
Here is part of my code -- when i click it it selects from a listbox in a popupwindow.
<html>
<input id = 'input2' type="button" value="Select Route" onclick="SelectName()" />
<script type="text/javascript">
var popup;
function SelectName() {
popup = window.open("offices.php", "Popup", "width=500,height=500");
popup.focus();
}
</script>
</html>
here is the Popup_info--
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<html>
<head>
<title>Select offices</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script type="text/javascript">
function select(){
var str='';
for (i=0;i<s1.length;i++) {
if(s1[i].selected){
str +=s1[i].value+ " ";
}
}
document.getElementById("msg3").innerHTML=str;
return true;
}
function select_all(){
var str='';
for (i=0;i<s1.length;i++) {
s1[i].selected=true
{
str +=s1[i].value+ " ";
}
}
document.getElementById("msg3").innerHTML=str;
}
function deselect_all(){
var str='';
for (i=0;i<s1.length;i++) {
s1[i].selected=false
{
str ="";
}
}
document.getElementById("msg3").innerHTML=str;
}
</script>
</head>
<body>
<br>
<br>
<center>
<p> Select the Document Route.</p>
<p> Hold ctrl for multiple Selection.</p>
<?php include ('db.php');
$data = mysql_query("select office from office_table");
echo "<select name = no_year id= s1 onChange='select()'; required multiple size= 10 value ='' width='200' style='width: 200px' > ";
while($row=mysql_fetch_assoc($data))
{
echo "<option> ".$row['office']."
</option>";
}
echo "</select>";
?>
<div id='msg3' width = 300> <table ></table></div>
</body>
<br><br><br><br>
<input type='button' value='Select All' onclick='select_all();' id = 'input2' />
<input type='button' value='Clear' onclick='deselect_all();' id = 'input2' />
<input type="button" value="Submit" onclick="Set_select();" id = 'input2' />
<script type="text/javascript">
function Set_select() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("txtName");
txtName.value = document.getElementById("msg3").innerHTML;
}
window.close();
}
</script>
</html>
I'm just new on php and i want to insert the data i get here into the table specifically. i mean by each click its a separated data when inserted. please help.

Mobile webpage contact form not working

I am using mRova template to build a contact form
<!DOCTYPE html>
<!--
Design by mRova Solutions
http://www.mrova.com
Released for free under a Creative Commons Attribution 2.5 License
-->
<html>
<head>
<title>Free Mobile Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0;" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/photoswipe.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
<script type="text/javascript" src="js/klass.min.js"></script>
<script type="text/javascript" src="js/code.photoswipe.jquery-3.0.4.min.js"></script>
<script type="text/javascript" src="js/custom.js"></script>
</head>
<body>
<div data-role="page" data-add-back-btn="true">
<div data-role="header" id="header">
<h1>Mobile Template</h1>
</div><!-- /header -->
<div data-role="content">
<div class="ui-body ui-body-b ui-corner-all">
<div class="contact-thankyou" style="display: none;">
Thank you. Your message has been sent. We will get back to you as soon as we can.
</div>
<div class="contact-form">
<p class="mandatory">
* indicates Mandatory Field
</p>
<div data-role="fieldcontain" class="text-field">
<label for="firstname">First Name*:</label>
<input type="text" name="firstname" value="" placeholder="" class="required" id="firstname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="surname">Last Name:</label>
<input type="text" name="surname" value="" placeholder="" id="surname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="email">Email Address*:</label>
<input type="email" name="email" value="" placeholder="" class="required" id="email" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="mobilephone">Mobile Number:</label>
<input type="number" name="mobilephone" value="" placeholder="" id="mobilephone" />
</div>
<div data-role="fieldcontain">
<label for="message">Message*:</label>
<textarea name="message" id="message" placeholder="" class="required"></textarea>
</div>
<div class="send">
send
</div>
</div><!-- //.contact-form -->
</div>
<p class="copyright">Copyright © mobi. Designed by mRova</p>
</div><!-- /content -->
<div data-role="footer" data-theme="a">
<div class="ui-bar">
Share
Contact
Return top
</div>
</div>
<!-- /Footer -->
</div><!-- /page -->
</body>
</html>
the custom.js is:
$('.returnTopAction').live('click', function() {
$('html, body').animate({scrollTop: '0'}, 700);
});
$('#gallery-page').live('pageshow', function () {
$myPhotoSwipe = $(".gallery a").photoSwipe({ enableMouseWheel: false , enableKeyboard: false });});
$('#send').live("click", function() {
var url = 'send.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form');
$('.required', $contactform).each(function(i) {
if($(this).val() === '') {
error++;
}
});
// each
if(error > 0) {
alert('Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk *.');
} else {
var firstname = $contactform.find('input[name="firstname"]').val();
var surname = $contactform.find('input[name="surname"]').val();
var state = $contactform.find('select[name="state"]').val();
var mobilephone = $contactform.find('input[name="mobilephone"]').val();
var email = $contactform.find('input[name="email"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type : "GET",
url : url,
data : {
firstname : firstname,
surname : surname,
state : state,
mobilephone : mobilephone,
email : email,
message : message
},
success : function(data) {
if(data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Unable to send your message. Please try again.');
}
}
});
//$.ajax
}
return false;
});
the klass.min.js is:
/**
* Klass.js - copyright #dedfat
* version 1.0
* https://github.com/ded/klass
* Follow our software http://twitter.com/dedfat :)
* MIT License
*/
!function(a,b){function j(a,b){function c(){}c[e]=this[e];var d=this,g=new c,h=f(a),j=h?a:this,k=h?{}:a,l=function(){this.initialize?this.initialize.apply(this,arguments):(b||h&&d.apply(this,arguments),j.apply(this,arguments))};l.methods=function(a){i(g,a,d),l[e]=g;return this},l.methods.call(l,k).prototype.constructor=l,l.extend=arguments.callee,l[e].implement=l.statics=function(a,b){a=typeof a=="string"?function(){var c={};c[a]=b;return c}():a,i(this,a,d);return this};return l}function i(a,b,d){for(var g in b)b.hasOwnProperty(g)&&(a[g]=f(b[g])&&f(d[e][g])&&c.test(b[g])?h(g,b[g],d):b[g])}function h(a,b,c){return function(){var d=this.supr;this.supr=c[e][a];var f=b.apply(this,arguments);this.supr=d;return f}}function g(a){return j.call(f(a)?a:d,a,1)}var c=/xyz/.test(function(){xyz})?/\bsupr\b/:/.*/,d=function(){},e="prototype",f=function(a){return typeof a===b};if(typeof module!="undefined"&&module.exports)module.exports=g;else{var k=a.klass;g.noConflict=function(){a.klass=k;return this},a.klass=g}}(this,"function")
the php is:
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["firstname"])) {
$firstname = strip_tags($_GET['firstname']);
$surname = strip_tags($_GET['surname']);
$email = strip_tags($_GET['email']);
$mobilephone = strip_tags($_GET['mobilephone']);
$state = strip_tags($_GET['state']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">rn";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'mysite#myhost.com';
$subject = 'Contact Form';
$mailbody = "
First Name: $firstname
Last Name: $surname
Email: $email
Mobile Phone: $mobilephone
State: $state
Message: $message
IP: $ip
Browser info: $httpagent
Referral: $httpref
Sent: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>
When I test this in a pc it works perfect, however when using a blackberry or a cellphone it just does nothing when the send button is clicked...
I tested a single script to test mail function and it works...
<?php
$ADDR = "mysite#my.com";
if (mail($ADDR,"Testing","This is a test"))
echo "Mail function succeeded<br />";
else
echo "Mail function FAILED<br />";
?>
Where is the error, I do not understand why is not working on phones, but when tested on a pc it does?
You can try with $_POST instead of $_GET and try one by one. That would work

Resources