#RestController VS #Controller in Spring MVC with AngularJs - 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.

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');
}
});
}
});

display the post data in the angular js jsp page

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>

how to send image and text values using multipart form in angular js and spring mvc

I have tried the following code so far where i have been appending text and file values to the form data in angular js and sending it to the controller but when i submit the form i get 415 unsupported content type error in my console
html
<html>
<head>
<script src="extensions/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="testcontrol">
<input type="text" ng-model="A.username" placeholder="Enter Username" required>
<input type="password" ng-model="A.password" placeholder="Enter Password" required>
<input type="file" placeholder="Browse image" name="file" id="test" required>
<input type="button" value="Send" ng-click="setValues()" />
<script>
var app = angular.module('myApp', []);
app.controller('testcontrol', function($scope, $http) {
$scope.setValues = function() {
var formData = new FormData();
var file = '#test';
var json = $scope.A;
formData.append("file", file);
formData.append("asd",JSON.stringify(json));
$http({
method : 'POST',
url : 'form/upload',
headers : {
'Content-Type' : 'undefined'
},
data : formData
}).success(function(data) {
alert(JSON.stringify(data));
});
};
});
</script>
</body>
</html>
Controller code
#Controller
#RequestMapping(value="/form")
public class Form {
#RequestMapping(value = "/upload", method = RequestMethod.POST,consumes = {"multipart/form-data"})
public #ResponseBody
void storeAd(#RequestPart("asd") String adString, #RequestPart("file") MultipartFile file) throws IOException {
logger.info("entered controller");
TestDto1 jsonAd = new ObjectMapper().readValue(adString, TestDto1.class);
//do whatever you want with your file and jsonAd
}
I have finally found a solution to add multiple images after struggling for one day.Praise be to God and my friend who have helped me.
html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="extensions/angular.min.js"></script>
<script>
'use strict';
var mainApp = angular.module('mainApp', []);
mainApp.controller('FileUploadController', function($scope, $http) {
$scope.document = {};
$scope.setTitle = function(fileInput) {
var file = fileInput.value;
var filename = file.replace(/^.*[\\\/]/, '');
var title = filename.substr(0, filename.lastIndexOf('.'));
};
$scope.uploadFile = function() {
var form = document.getElementById('a');
var formData = new FormData(form);
$scope.dataform = {};
formData.append('formdata', JSON.stringify($scope.document));
$http.post('form/up', formData, {
transformRequest : function(data, headersGetterFunction) {
return data;
},
headers : {
'Content-Type' : undefined
}
}).success(function(data, status) {
alert("Success ... " + status);
}).error(function(data, status) {
alert("Error ... " + status);
});
};
});
</script>
</head>
<body ng-app="mainApp" ng-controller="FileUploadController">
<form ng-submit="uploadFile()" class="form-horizontal" enctype="multipart/form-data" id="a">
<input type="file" name="file[0]" />
<input type="file" name="file[1]" />
<br>
<input type="file" name="filea[0]" />
<input type="file" name="filea[1]" />
<br>
<input type="text" ng-model="document.title" />
<br>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</body>
</html>
This is my controller code
package com.covenant.app.controllers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
#Controller
#RequestMapping(value = "/form")
public class Form {
#RequestMapping(value = "/up", method = RequestMethod.POST, consumes = { "multipart/form-data" })
public #ResponseBody void storeAd1(MultipartHttpServletRequest request) {
logger.info("message" + request.getFileNames());
int i = 0, j = 0;
Iterator<String> it = request.getFileNames();
while (it.hasNext()) {
String s = it.next();
if (s.startsWith("filea")) {
logger.info(request.getFile("filea[" + i + "]").getSize());
i++;
} else {
logger.info(request.getFile("file[" + j + "]").getSize());
j++;
}
}
}
private static final Logger logger = Logger.getLogger(Form.class);
}

Spring Security 4 and Angular login authentication

I've a problem with seend good post to login authentication.
This is my security configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER')")
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login/authentication").successHandler(securityHandler)
.usernameParameter("s_username").passwordParameter("s_password")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
Spring controller:
#Controller
#RequestMapping("/login")
public class AuthController {
#RequestMapping(value="", method = RequestMethod.GET)
public String getLoginPage(){
return "login/layout";
}
}
My login page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="resources/css/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<script src="resources/js/angular.min.js"></script>
<script src="resources/scripts/auth/Auth.js"></script>
<script src="resources/js/angular-route.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body ng-app="appAuth">
<div class="col-md-6 col-md-offset-3" ng-controller="LoginController as login">
<h2>Login</h2>
<form name="form" ng-submit="Login()" role="form">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" ng-model="login.username" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="login.password" required />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid" class="btn btn-primary">Login</button>
</div>
</form>
</div>
</body>
</html>
And Angular Controller:
(function (angular) {
'use strict';
var App = angular.module('appAuth', ['ngRoute'])
App.controller("LoginController", function ($scope, $http, $window) {
var encode4form = function(data){
var result="";
var first = true;
for(var key in data)
{
if(first){
first=false;
}
else{
result+="&"
}
result+=(key + "=" + data[key]);
}
return result;
};
$scope.Login = function () {
var mycsrf = $("input[name='_csrf']").val();
$http(
{
url: "/login/authentication",
method:"POST",
data: encode4form({
s_username: $scope.login.username,
s_password: $scope.login.password,
_csrf: mycsrf
}),
headers:
{
"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
}
}
);
//$http({
// method: 'POST',
// url: 'http://localhost:8080/login/authentication',
// data: data,
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
// }
//$http.post('/login/authentication', loginData), {
// headers: {
// 'X-CSRF-TOKEN': $('input[name="_csrf"]').val(),
// //'Content-Type': "application/x-www-form-urlencoded"
// 'Content-Type': 'application/json'
// }
//});
};
});
})(window.angular);
Console log:
2016-02-27 11:11:27 INFO AuthController:24 - Login
2016-02-27 11:11:31 WARN PageNotFound:1136 - No mapping found for HTTP request with URI [/Access_Denied] in DispatcherServlet (When I click login)
I tried many ways but no way didn't work. When I click login button chrome show error "POST http://localhost:8080/login/authentication 404 (Not Found)". When I change login page to login.jsp (without angular) then works. Why didn't work on angular?

Resources