Spring dont see angular - java

I am trying adapt my app to use angular, but currently it seems that spring cannot see/communicate with angular. Here is what i have :
Controller.java:
#Controller
public class IndexController {
#RequestMapping(value = "/login", method = RequestMethod.GET, produces = {"application/json"})
public #ResponseBody Map<String, Object> getIndexPage() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello Worl123321");
return model;
}
}
index.html:
<!doctype html>
<html>
<head>
<title>Title</title>
<!--<link href="css/angular-bootstrap.css" rel="stylesheet">
<link rel="stylesheet" href="css/app.css"/>-->
<style type="text/css">
[ng\:cloak],
[ng-cloak],
.ng-cloak {
display: none !important;
}
</style>
<script src="js/angular-bootstrap.js" type="text/javascript"></script>>
<script src="app/app.js"></script>
<script src="app/listView/listView.js"></script>
</head>
<body ng-app="myApp">
<!-- Application content -->
<div ng-include="'app/app.html'"></div>
</body>
</html>
app.html:
<div class="container">
<div ng-controller="appCtrl" ng-cloak class="ng-cloak">
{{greeting.content}}
</div>
</div>
app.js:
angular.module('myApp', [])
.controller('appCtrl', function($scope, $http) {
$http.get('/login/').success(function(data) {
$scope.greeting = data;
});
});
I just get an output like this :
{"id":"01cdab29-e0ce-45ee-abb9-64b2640859ca","content":"Hello
Worl123321"}
and there seems that no angular scripts has been loaded...

What do you use to serialise as JSON ?
This is maybe because of the Map<> that you have an extra field 'content' between your object and your data try.
$scope.greeting = data.content;
I've already heard of some problem like this with Jackson adding a "content" though it was for a hibernate problem.
If you don't want that extra field : create a wrapper class having an id and content field and use it.

Related

How to get data from data model via constant

I am using Spring boot and Thymeleaf as a template framework. I set a couple constants on the backend and I need to get data on the frontend via that constants.
I have the backend look like the following:
public class Constant {
public static final String MY_VAR = "test";
}
#Controller
public class MyController {
#GetMapping("/")
public String home(Model model) {
List<String> data = new ArrayList<>();
data.add("item1");
model.addAttribute(Constant.MY_VAR, data);
return "home";
}
}
and on the frontend I want to do like this:
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<div class="container-fluid p-0">
<div th:unless="${not #lists.isEmpty(Constant.MY_VAR)}">
</div>
</div>
</body>
</html>
how can I get access to model data via constant from the backend?
You can use **ModelAndView ** to solve this problem
backend
#GetMapping("/")
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("home");
List<String> data = new ArrayList<>();
data.add("item1");
modelAndView.addObject("test", data);
return modelAndView;
}
frontend
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<div class="container-fluid p-0">
<div th:if="${test.size() > 0}">
<li th:each="item:${test}">
<span th:text="${item}"></span>
</li>
</div>
</div>
</body>
</html>
if u want get static attribute in your view。
you can do that
${T(packageName.Constant).MY_VAR}
so u can change your code
${not #lists.isEmpty(Constant.MY_VAR)}
to
${not #lists.isEmpty(#ctx.getVariable(T(packageName.Constant).MY_VAR))}

Submit AJAX and Springboot values

I want to send the URI value to the database using AJAX and the request is written in #Controller. But when I hit submit there's nothing in the database.
For example I have the address:
http://localhost:8080/post/view/2
As above I want to save value 2 to my database every time I click submit. I have tried but nothing
#Controller
#RequestMapping(value="post/view/{id}", method= RequestMethod.POST, produces = "apllication/json")
public #ResponseBody Comment newComment (#RequestParam(name="id") Long id) {
Comment comment = new Comment();
Post postView = postService.findById(id);
comment.setPoster(postView);
commentService.create(comment);
return comment;
}
And my code HTML
view.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head >
<script type="text/javascript" language="javascript"
src="https://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript"
src="https://www.technicalkeeda.com/js/javascripts/plugin/json2.js">
</script>
<title th:text="${postView.title}">View Post</title>
<script >
function madeAjaxCall(){
$.ajax({
type: "post",
url: "http://localhost:3313/post/view/{id}"
}
</script>
</head>
<body>
<div>
<form method="post" >
<main id="posts">
<article>
<h2 class="title" th:text="${postView.title}">Post Title</h2>
<div class="date">
<i>Posted on</i>
<span th:if="${postView.author}" th:remove="tag">
<i>by</i>
<span th:text="${ postView.author.lastName}">Svetlin Nakov</span>
</span>
</div>
</article>
<input type="button" value="Ajax Submit" onclick="madeAjaxCall();"/>
</main>
</form>
</div>
</body>
</html>
I think I was wrong or missing something at AJAX or #Controller. Thank you
try using #PathVariable instead of #RequestParam
I noticed several things that are wrong in your code:
https://www.technicalkeeda.com/js/javascripts/plugin/jquery.js this link is invalid. Try using jQuery from the official site: https://code.jquery.com/jquery-3.5.1.js
This might not be your server url url: "http://localhost:3313/post/view/{id}". Please confirm the port is 3313 and provide a valid value for {id}. Also, you don't need to use the port and url at all. See my code below:
produces = "apllication/json" you have typo here. Just change it to produces = MediaType.APPLICATION_JSON_VALUE
You are using #RequestParam but your request has the id parameter in path. Lookup the difference between the #RequestParam and #PathParam.
(#RequestParam(name="id") Long id) { You should be using #PathVariable
Here's a working code:
Backend controller:
#PostMapping(value = "/post/view/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
void newComment(#PathVariable Long id) {
System.out.println("Requested with id = " + id);
}
Frontend:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<body>
<script>
function madeAjaxCall() {
$.ajax({
type: "post",
url: "/post/view/5"
})
}
</script>
<input type="button" value="Ajax Submit" onclick="madeAjaxCall();"/>
</body>
</html>

#RequestMapping(headers),#RequestBody not working

I have a problem configuring the header attribute in the #RequestMapping annotation.Here is my code:
HTML page :
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" th:src="#{/css/url_rearch_params.js}"/>
</head>
<body>
<div id="app">
<h1>TEST FORM</h1>
<form action="" method="post">
<p>Type description: <input type="text" v-model="type.description"/></p>
<p><button v-on:click="addType()"> Send </button><input type="reset" value="Reset" /></p>
</form>
</div>
<script src="http://cdn.jsdelivr.net/vue/1.0.10/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
Vue.prototype.$http = axios;
new Vue({
el:'#app',
data:{
type:{description:''}
},
methods:{
addType(){
const config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/x-www-form-urlencoded'
}
};
let newType = {description:this.type.description};
console.log(newType);
this.$http.post('/types/insert',newType,config).then(response => {
console.log(response);
});
}
}
});
</script>
</body>
</html>
And my java code:
#RequestMapping(value = "/insert",method = RequestMethod.POST, headers = {"Accept=application/x-www-form-urlencoded","Content-Type = application/x-www-form-urlencoded"},consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public #ResponseBody void createType(#RequestBody Type type) {
System.out.println(type);
typeService.createType(type);
}
The problem if I try to execute the method I have the following message:
There was an unexpected error (type=Not Found, status=404).
If I remove :
headers = {“Accept=application/x-www-form-urlencoded”,“Content-Type =
application/x-www-form-urlencoded”}
of the #requestpost parameter I have the following error :
There was an unexpected error (type=Unsupported Media Type,
status=415). Content type
‘application/x-www-form-urlencoded;charset=UTF-8’ not supported
N.B : I already visited this post but it does not solve my problem
Thank you in advance for your help.
Instead of headers, try consumes
#RequestMapping(value = "/insert",method = RequestMethod.POST, consumes="application/x-www-form-urlencoded","Content-Type = application/x-www-form-urlencoded"},consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)

Why page is not loaded in Java Spring boot Angularjs

I have a problem with load a simple page where will be display all messages. I using algular for front-end and spring boot app in back-end. When i try to load page (localhost:8080/messages), page is blank and give me to download JSON with messages. Any idea? Ps. in ViewAllMessages.html i write constant text to check when page is running.
MessageController:
#RestController
#RequestMapping("/api/message")
public class MessageController {
private final Logger LOG = LoggerFactory.getLogger(MessageController.class);
#Autowired
private MessageService messageService;
#RequestMapping(value = "/all", method = GET)
public List<MessageDTO> findAll() {
LOG.info("Received request to all messages.");
return messageService.findAll();
}
}
main.js
var chatApp = angular.module('chat', ['ngRoute']);
chatApp.config(function ($routeProvider) {
$routeProvider
.when('/messages',
{
controller: 'AllMessagesController',
templateURL: '/partials/ViewAllMessages.html'
})
.otherwise( {redirectTo: '/'});
});
chatApp.service('messageService', function(){
var message = {};
var addMessage = function (v) {
message = v;
};
var getMessage = function(){
return message;
};
return {
addMessage: addMessage,
getMessage: getMessage
};
});
chatApp.controller('AllMessagesController', function($scope, $window, $http){
$scope.transfer = {};
$scope.error = false;
$http
.get('/api/message/all')
.then(function(response) {
$scope.messages = response.data;
log.console(response.data);
});
});
index.html
<!doctype html>
<html>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/simple-sidebar.css" rel="stylesheet">
<link href="css/bootstrap-datetimepicker.css" rel="stylesheet">
<link href="css/office.css" rel="stylesheet">
<style type="text/css"> </style>
<body>
<script src="js/angular-route.min.js" type="text/javascript"></script>
<script src="js/angular-resource.min.js" type="text/javascript"></script>
<script src="js/main.js"></script>
<script src="js/angular.min.js" type="text/javascript"></script>
</body>
</html>
ViewAllMessages.html
<div class="container">
<div class="col-md-6">
<div class="row">
<div class="col-md-2">
<h2>Wiadomosci</h2>
</div>
</div>
</div>>
<div class="section">
<h3>{{headingTitle}}</h3>
<div>
<ul type="square">
<li>Luke</li>
<li>Darth</li>
<li>Anakin</li>
<li>Leia</li>
</ul>
</div>
</div>
<div class="panel panel-default" ng-repeat="message in messages">
<div class="row">
<div class="col-md-2">
<div class="panel-default"> {{message.id}}</div>
</div>
<div class="col-md-2">
<div class="panel-default"> {{message.message}}</div>
</div>
</div>>
</div>
</div>
page didn't show because you didn't import $routeParams dependency into your controller in index.js. After setting it, page shows up.

Cannot call Play Framework static method from view

I have server and I should make request on button pressed also I have to call this method and when it is works I should parse json but my doesn't see controller method only main method is available
How to call
<input type="submit" onclick="#routes.Login.resp()" value="LOGIN" >
because it is not worrking Cannot resolve symbol
GET /login controllers.Login.main()
My controller:
package controllers;
import play.libs.F;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.Result;
public class Login extends Controller {
public static Result main() {
return ok(views.html.login.render());
}
public static F.Promise<Result> resp() {
String feedUrl="http://validate.jsontest.com/?json=%7B%22key%22:%22value%22%7D";
final F.Promise<Result> resultPromise = WS.url(feedUrl).get().flatMap(
new F.Function<WS.Response, F.Promise<Result>>() {
public F.Promise<Result> apply(WS.Response response) {
return WS.url(response.asJson().findPath("empty").asText()).get().map(
new F.Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("size" + response.asJson().findPath("count").asInt());
}
}
);
}
}
);
return resultPromise;
}
}
view:
<!--
Author: W3layouts
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/stylelogin.css")">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfonts-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:600italic,400,300,600,700' rel='stylesheet' type='text/css'>
<!--//webfonts-->
</head>
<body>
<!-----start-main---->
<div class="main">
<div class="login-form">
<h1>Member Login</h1>
<div class="head">
<img src="#routes.Assets.at("images/user.png")" alt=""/>
</div>
<form>
<input type="text" class="text" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'USERNAME';}" >
<input type="password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}">
<div class="submit">
<input type="submit" onclick="#routes.Login.main()" value="LOGIN" >
</div>
</form>
</div>
<!--//End-login-form-->
<!-----start-copyright---->
<!-----//end-copyright---->
</div>
<!-----//end-main---->
</body>
</html>
I am not sure if I also parse json properly,how to make proper GET,POST requests and parse it
As far as I know with the onclick attribute you always call a function in your JavaScript. If you want to specify an URL you need to put it into your form tag with an action attribute like <form action="#routes.Login.main()">.
The default for the HTML form tag is to send a GET. If you want to send a POST you have to specify it via an additional method="post" like <form action="#routes.Login.main()" method="post">. But then you have to change your routing too: POST /login controllers.Login.main(). If you want to post login data I'd strongly recommend to use POST because with GET your data including the password turns up in the query string of your URL.
Additionally your #routes.Login.main() method just returns the login view return ok(views.html.login.render());. Instead it should evaluate the form data you are sending.

Categories