REST #FormParam is null - java

I have the following being passed from browser to server
Status Code:204 No Content
Request Method:POST
Content-Type:application/x-www-form-urlencoded
Form Data
json:{"clientName":"PACK","status":"success","message":"successful!"}
and in jsp code
var loginData = {
clientName: cList,
status: "success",
message: "successful!"
};
$.ajax({
url: subUrl,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
data: {
json: JSON.stringify(loginData)
},
success: function (data) {
handleLoginResult(data);
}
});
And in Java code I have
#POST
public Object persistResetPasswordLogs(#FormParam("clientName")
String clientName) {
try {
log.info("in rest method ??? "+clientName);
.......
.......
In server I am getting clientName as null.
What could be the reason for this and how can I resolve this?

AFAIK, there is no Jersey (JAX-RS) mechanism to parse JSON into form data. Form data should be in the form of something like
firstName=Stack&lastName=Overflow (or in your case clientName=someName)
where firstName and lastName are generally then name attribute value in the form input elements. You can use jQuery to easily serialize the field values, with a single serialize() method.
So you might have something that looks more along the lines of something like
<form id="post-form" action="/path/to/resource">
Client Name: <input type="text" name="clientName"/>
</form>
<input id="submit" type="button" value="Submit"/>
<script>
$("#submit").click(function(e) {
$.ajax({
url: $("form").attr("action"),
data: $("form").serialize(),
type: "post",
success: processResponse,
contentType: "application/x-www-form-urlencoded"
});
});
function processResponse(data) {
alert(data);
}
</script>

Have you defined the Requestmapping like this:
#POST
#Path("/submitclient") // your request mapping for 'subUrl'
public Object persistResetPasswordLogs(#FormParam("clientName") String clientName)
and html:
<form action="submitclient" method="post">
...
</form>
Also look at your json object. I believe you should send something like this:
var loginData = {
clientName: "dit" // get it from input
};
?

Related

Spring boot + Thymeleaf + ajax cannot send VO or DTO Controller

I try to send form data through thymeleaf + ajax to Java Controller.
But at ReplyDto, can't receive data.
This is my code.
Themeleaf, Ajax .html
function insertReply() {
$.ajax({
type: 'POST',
url: '/reply/insertReply',
data: $("#replyForm").serialize(),
contentType: "application/json",
success: function(data) {
alert("test");
},
error: function(request, status, error) {
alert("Error : " + error + "\nStatus : " + status + "\nRequest : " + request);
}
});
}
<form id="replyForm" th:object="${replyDto}" th:method="post">
<input type="hidden" th:field="${post.postNo}" th:value="${post.postNo}">
<input class="form-control" type="text" th:field="*{replyTitle}" placeholder="replyTitle">
<textarea class="form-control" th:field="*{replyContent}" placeholder="insert" id="replyContentData" style="height: 100px"></textarea>
<button class="btn btn-primary" id="replyInsertButton" type="button" onclick='insertReply()'>댓글 입력</button>
</form>
ReplyDto.java
private int replyNo;
private String replyTitle;
private String replyContent;
private int postNo;
ReplyContoller.java
#PostMapping("/insertReply")
public int insertReply(ReplyDto replyDto) {
System.out.println(replyDto.getPostNo());
System.out.println(replyDto.getReplyTitle());
System.out.println(replyDto.getReplyContent());
return replyService.insertReply(replyDto);
}
Controller has annotation #RestController.
At console, log 0, null, null each postNo, replyTitle, replyContent.
How can I get form data to Controller?
Please help!
Your are missing #RequestBody
public int insertReply(#RequestBody ReplyDto replyDto) { ...
$("#replyForm").serialize() turns form into query string. You need valid JSON
You should probably go for a solution like this: Spring RestController POST accepting a basic HTML form
If you insist on proceeding with your current solution:
Start with verifying controller in Postman when fixed missing #RequestBody.
Converting form to JSON:
https://www.learnwithjason.dev/blog/get-form-values-as-json/
https://medium.com/#mwakatumbula_/code-15ecdb18c2ef
https://css-tricks.com/snippets/jquery/serialize-form-to-json/

Ajax request is not calling Spring boot controller

I'm trying to call my Spring controller using Ajax and submitting a form.
Function always retrieves the error window. I tried changing the URL parameter to "/profile", "profile" or "PrivateAreaController/profile", but I keep getting the same error.
My main.js file and controller are placed in the following order:
-->Mainfolder
-->src
-->java
-->controller
-->PrivateAreaController.java
-->resources
-->static
-->js
-->main.js
My controller is called PrivateAreaController
Ajax Code
$('#sampleForm').submit(
function(event) {
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var data = 'firstname='
+ encodeURIComponent(firstname)
+ '&lastname='
+ encodeURIComponent(lastname);
$.ajax({
type : "POST",
dataType: "json",
url : '#Url.Action("callingcontroller","PrivateAreaController")',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
return false;
});
Spring code
#RequestMapping(value = "/profile", method = RequestMethod.POST)
public #ResponseBody
String processAJAXRequest(
#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname ) {
String response = "";
System.out.println("working");
return response;
}
HTML form
<form id="sampleForm" method="post" action="/profile">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<button type="submit" name="submit">Submit</button>
</form>
EDIT:
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
This worked for me using springboot with thymeleaf, made small modification to one of the answers on this post How do you get the contextPath from JavaScript, the right way?
In the HTML
<html>
<head>
<link id="contextPathHolder" th:data-contextPath="#{/}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
THEN IN JS
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + 'action_url', function() {});
What is error you are getting, Press F12 and go to Network tab and the press submit button now see the url, try adding url:"../your service URL..
Well. I never seen this part before.
#Url.Action("callingcontroller","PrivateAreaController")
I normally do like as below:
$.ajax({
type : "POST",
dataType: "json",
url : '/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
But it can have a problem with the contextPath.
So, What I do is adding 'request.getContextPath()/' as below:
$.ajax({
type : "POST",
dataType: "json",
url : '${request.getContextPath()}/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
The contextPath has the URL of your start page.
For instance, 'www.google.com' or 'www.naver.com'
But in general, Since I personally use the contextPath a lot, I make a value and keep it.
var context = ${request.getContextPath()};
Then, your code will look neat and easy to reuse.
And also you can figure it out with the error attribute.
error : function(err) {
console.log("not working. ERROR: "+JSON.stringify(err));
}
I hope this works out.

Sending Cyrillic string from jsp to java class trough ajax with correct encoding

I am having a few input fields in my jsp page that get a Cyrillic input which I am then upon pressing a button trying to send to this java method using ajax. The strings in the java method end up being gibberish.
The fields in the jsp page:
<div class="span1">
<form:label cssClass="control-label" path="">
<spring:message code="web.messages.someMessage" />
</form:label>
<form:input cssClass="input-block-level" path="" id="articleId" />
</div>
<div class="span1">
<label> </label>
<button type="button" id="search-btn" class="btn" >
<spring:message code="web.messages.buttonMessage" />
</button>
</div>
The ajax in the script:
$("#search-btn").on("click", function(e) {
e.preventDefault();
showDialog("${pageContext.request.contextPath}");
});
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
if (article) {
article = "?article=" + article;
}
$.ajax({
type : "GET",
url : "${pageContext.request.contextPath}/sync/getFilter"
+ article,
success : function(data) {
onClickTable();
}
});
}
This is part of the java method, where the value turns into gibberish:
#RequestMapping(value = "/getFilter", method = RequestMethod.GET)
public #ResponseBody ModelAndView getFilter(HttpServletRequest request) {
String article = (String) request.getParameter("article");
.
.
Fixed the problem by putting the information in a JSON and sending it like that.
The changed made:
The ajax in the script part of the jsp:
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
var data = {
"article": $('#articleId').val().replace(/\s+/g, ""),
// other keys and values
"lastKey": $('#lastValueId').val().replace(/\s+/g, "")
}
$.ajax({
type : "POST",
url : "${pageContext.request.contextPath}/sync/getFilter",
data: data,
success : function(data) {
onClickTable();
}
});
}
The java method handling the data:
#RequestMapping(value = "/getFilter", method = RequestMethod.POST)
public #ResponseBody ModelAndView getFilter(SomeObject receivedData) {
String article = receivedData.getArticle();
// rest of the method
Where SomeObject is an object containing the values that we receive in the data with proper set and get methods for them.

REST #FormParam values are null

I have the following in html
<form name="myform" method="POST">
<input type="text" id="products" name="products" />
</form>
function myForm() {
var url = 'rest/products/details/';
var formData = $("#myform").serializeArray();
$.ajax({
url: url,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
dataType: 'json',
data: formData,
success: function (data) {
//callfunc(data);
}
});
}
In Java server side I have the following
#POST
#Path("/details")
public List<Product> findProducts(#FormParam("products") String products) {
.....
.....
log.info("prod "+products); --> getting null
For some reason products is null even though I am passing correct values from html. What could be the reason for this?
function myForm() {
var url = 'rest/products/details/';
var formData = "products=asasa" ;
$.ajax({
url: url,
type: 'POST',
contentType : "application/x-www-form-urlencoded",
dataType: 'json',
data: formData,
success: function (data) {
//callfunc(data);
}
});
}
try this and remove #consumes annotation. the problem is in the $("#myform").serializeArray() function from jquery.
Try Consumes annotation
#POST
#Path("/details")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public List<Product> findProducts(#FormParam("products") String products) {
.....
.....
Issue is rather silly,I was using name instead of id and that resulted in getting null in server side for all form elements. I have changed to
<form id="myform" method="POST">
it works well
However
<form name="myform" method="POST"> doesn't work.

jQuery setting input field value

I have a form to edit user and i would like to insert user data from database into forms' fields. What i do is
Link
Edit
Script
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
}
Form
<div id="edit-form" title="Edit user">
<p class="validateTips">All form fields are required.</p>
<form:form>
<fieldset>
<label for="elogin">Login</label>
<input type="text" name="elogin" id="elogin" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form:form>
</div>
My Spring controller returns following(in wrapper i have field login)
#RequestMapping(value="/edit/{userLogin}", method=RequestMethod.POST)
#ResponseBody
public Wrapper edit(#PathVariable String userLogin) {
return wrapper.wrap(userService.findByLogin(userLogin));
}
But the form is empty. I also tried to set manual values but still no use. Please help me set input field value.
You should send your form data with your post request.
$.ajax({
url: url,
type: "POST",
data:$('form').serialize(),
success: function (resp) {
$('input[name="elogin"]').val(resp.login);
}
})
function editUser(url) {
$( "#edit-form" ).dialog( "open" );
$.ajax({
url: url,
type: "POST",
success: function (resp) {
$('#elogin').val(resp.login);
}
})
}
Should work just fine, as you've set an ID for the input.
Not quite sure you have the order right, surely you would make the ajax call first and then open up the jQuery dialog?
Either way, you could supply data into the dialog as follows;
//call ajax method to get value you want to show.
var somevariable = etc.....
var dto = {
loginName: somevariable
}
$( "#edit-form" ).data('params', dto).dialog( 'open' );
Then in your dialog use the open() method.
$("#edit-form").dialog({
bgiframe: true,
autoOpen: false,
height: 280,
width: 320,
draggable: false,
resizable: false,
modal: true,
open: function () {
//so values set in dialog remain available in postback form
$(this).parent().appendTo("form");
//get any data params that may have been supplied.
if ($(this).data('params') !== undefined) {
//stuff your data into the field
$("#elogin").val($(this).data('params').loginName);
}
}
});

Categories

Resources