Submit AJAX and Springboot values - java

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>

Related

#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)

Spring dont see angular

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.

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.

Unsupported Media Type error in browser console when sending json using angularjs to spring controller

Here is my controller function
#RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"})
public #ResponseBody String logInCheckerFn(#RequestBody UserLogData userLogData){
Integer userAuthFlag = goAnalyserModel.checkUserAuth(userLogData);
return userAuthFlag.toString();
}
My Bean class
public class UserLogData {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My html file with angularjs function
<!DOCTYPE html>
<html lang="en" ng-app="nameAppIndexPage">
<head>
<meta charset="utf-8">
<title>Go Analyser - Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 60px;
padding-bottom: 40px;
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
</head>
<body ng-controller="nameController">
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="#">Go Analyser</a>
</div>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class=" margin_alignment"></div>
<div class="span4"></div>
<div class="span4">
<form class="form-signin">
<label for="exampleInputEmail1">Email address</label>
<input type="text" class="input-block-level" placeholder="Email address" ng-model="userName">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="input-block-level" placeholder="Password" ng-model="password">
<!-- <center><button class="btn btn-large" type="submit">Login</button></center>-->
<button type="submit" ng-click='checkLogin()'>login</button>
</form>
</div>
<div class="span4"></div>
</div>
<div class="hr_space"></div>
<footer>
</footer>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/angular.js"></script>
<script>
var myApp = angular.module('nameAppIndexPage',[]);
myApp.controller('nameController',function($http,$scope){
$scope.checkLogin = function(){
alert("inside checklogin()");
var userName = $scope.userName;
var password = $scope.password;
var dataToSend = {
"userName" : userName,
"password" : password
};
console.log(dataToSend);
alert("after data to send");
$http.post('logInChecker',dataToSend).success(function(data){
if(data == 1){
alert("inside loginSuccess");
}else{
alert("username and password mismatch");
//write function to show incorrect password
}
}).error(function(data){
alert("error in post" + JSON.stringify({data: data}));
});
}
});
</script>
</body>
</html>
I keep getting unsupported media error in browser console. The angularjs function is not getting the request through to the spring controller. But every thing seems to be fine.
This message happens either when the request cannot be converted to a java object, or when a java object cannot be converted to response.
As you've explained, you have the former case. Few things that you should check:
check that you have the <mvc:annotation-driven /> in your servlet configuration
check that you have jackson dependencies on your classpath, for spring 4.x you should have the jackson 2.x version, for spring 3.x you should use jackson 1.9
to ensure that your response is also properly converted you should, besides having the proper dependencies, ensure that
Either an Accept header is sent with your request with the value application/json or that the RequestMapping annotation of your handler method has the attribute produces = {"application/json"}
Add #JsonProperty("**") (**Name of the property) to your bean class. Check in the browser's developer tool type of JSON post messages.

how can get response from <form target="IFrame">

There is a simple web page which sends request, handles & manipulated by a servlet class and send back the response text.while i want ajax type handleing the request at client side that is why i am giving the response target to a invsible iframe. *but i want to print success on the page after iframe gets the response *
<html> <body>
<form action="test" method="post" target="IFrame"> /*response target is iframe*/
<input type="text" name="logic" />
<input type="submit" value="Submit" />
</form>
<iframe name="IFrame" style="width:0; height:0"> </iframe>
</body> </html>
i think this can be done using javascript or jquery, please guid me if you have any idea.
In the page which loads in the iframe, you will need to invoke a parent function.
<!-- This is the Parent. Call it JSTest1.html -->
<html>
<head>
</head>
<body>
<script type="text/javascript">
function parentAlert() {
alert('hey there from the parent');
}
</script>
I'm the parent
<iframe src="/JSTest2.html"></iframe>
</body>
<!-- this is the iframe html loaded. Call it JSTest2.html-->
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function() {
window.parent.parentAlert();
});
</script>
In the Iframe.
</body>
To send a message from Iframe to Parent window page:
<script type="text/javascript">
$(document).ready( function() {
//Message part is two parts Event name and Data you want to send
// Example message = "my_action,my_data"
message = "my_action,my_data"
parent.postMessage(message, "*");
});
</script>
At the parent window you can do the following to listen to this message and capture it:
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// Youe message which you send is captured here in e.data will split it on ',' to get the event and the data
message = e.data.split(',')[0]
value = e.data.split(',')[1]
if ( message === "my_action" ) {
myParentFunction(value)
}
},false);

Categories