Valid AJAX request with Spring MVC - java

I'm trying to send an AJAX jQuery request to my Spring MVC Servlet and got some problems. I read some articles already but they didn't help me :(
So I have this ajax request:
$.ajax({
url : "add_news",
type : "POST",
dataType : 'json',
contentType : 'application/json',
mimeType : 'application/json',
data : JSON.stringify({"category": categoryName, "name": newsName, "data": newsData}),
success : function(data) {
$("#list_news").append(
data.id + " : " +
data.name + " - " +
data.created + " ; " +
data.data + "<br>");
}
});
Controller is:
#RequestMapping (value = "/add_news", method = RequestMethod.POST)
public #ResponseBody News addNews(#RequestParam String category, #RequestParam String name, #RequestParam String data) {
System.out.println("category " + category);
System.out.println("name " + name);
System.out.println("data " + data);
NewsCategoryDict c = new NewsCategoryDict();
c.setId(66);
c.setName("misc");
News response = new News();
response.setCategory(c);
response.setId(60);
response.setName(name);
response.setData(data);
response.setCreated(new java.util.Date());
return response;
}
I don't even get System out - so my first problem is with url. "add_news" is not a jsp - just a logic to get a record from server.
Second problem (if I undestand it right) in entry params. I have to use #RequestBody to get data from the client as Java POJO and send this POJO back with some additional info. But I don't understand how to write JSON body in AJAX.data right to make it valid.
Please help me.
EDIT
Ok. I find a moment. If I use GET in $.ajax AND set RequestMethod.GET in controller handler method - method is invoked (with POST - no actions). So why POST is not working ??

Remove JSON.stringify() from post data:
$.ajax({
url : "add_news",
type : "POST",
dataType : 'json',
contentType : 'application/json',
mimeType : 'application/json',
data : {"category": categoryName, "name": newsName, "data": newsData},
success : function(data) {
$("#list_news").append(
data.id + " : " +
data.name + " - " +
data.created + " ; " +
data.data + "<br>");
}
});

Related

Send anonymous object - Rest controller - Spring boot

How would be the class that matches the following json :
'''{
"id1" : {
"apiToCall" : ["200", "400", "500"],
"apiToCall2" : ["100"],
"apiToCall5" : ["600", "300"]
},
"id2" : {
"apiToCall10" : ["300"],
"apiToCall8" : ["600", "700", "500"]
},
"id3" : {
"apiToCall80" : ["200", "400", "500"]
}
}'''
I want to send this object in POST method using spring rest, but my issue is that i have dynamic attributes.
So i don't know how to create the class that manages this case.
HttpEntity<String> entity = new HttpEntity(reqJsonStr, headers);
KeyPoint : "HttpEntity<String>" means type of request(reqJsonStr) is string.
RestTemplate restTemplate = new RestTemplate();
String reqURL = \"https://www.request_url.com/restapi/\";
String reqJsonStr = \"{"
+ " "\"id1\" : {"
+ " \"apiToCall\" : [\"200\", \"400\", \"500\"],"
+ " \"apiToCall2\" : [\"100\"],"
+ " \"apiToCall5\" : [\"600\", \"300\"]"
+ " },"
+ " \"id2\" : {"
+ " \"apiToCall10\" : [\"300\"],"
+ " \"apiToCall8\" : [\"600\", \"700\", \"500\"]"
+ " },"
+ " \"id3\" : {"
+ " \"apiToCall80\" : [\"200\", \"400\", \"500\"]"
+ " }"
+ "}";
headers headers = new headers();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr, headers);
String responseStr = restTemplate.exchange(reqURL, reqJsonStr, HttpMethod.POST, String.class);
I am not sure if it will work or not but it can be
Map<String, Map<String, List<String>>

I get error "400 Bad request" when trying to post a new issue into a GitHub repository

I'm building a web with spring that will allow the user to see the repositories, their issues and add new issues if they want. The problem appears when the user wants to create a new issue. I get "Error 400 Bad Request" and I can not underestand why.
I've tried to send the request through URL parameters but it didn't work either. I've also tried to automatically create the body with an ObjectMapper but I got the same result. So I'm building the body by myself but... same result again.
At the line with the comment "XXX" is where the software fails and in the web shows me the mentioned error.
#PostMapping("newIssue/{user}/{repo}/{fullName}")
public String registerUser(#PathVariable String user, #PathVariable String repo, #PathVariable String fullName, #Valid NewIssue newissue, Errors errors, Model model, OAuth2AuthenticationToken authentication) throws JsonProcessingException {
//To debug
System.out.println("### Registering issue");
//Check errors
List<String> errorsStrings = new ArrayList<>();
errors.getAllErrors().forEach(e->errorsStrings.add(e.getDefaultMessage()));
model.addAttribute("errors", errorsStrings);
model.addAttribute("newissue", newissue);
if(errors.hasErrors()) {
//To debug
System.out.println("### HAS ERRORS");
for (String err: errorsStrings )
System.out.println(" " + err);
//If has errors show again the page
return "newIssue";
}
//To debug
System.out.println("### Does not have ERRORS");
//Create the client variable
OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient( authentication.getAuthorizedClientRegistrationId(), authentication.getName() );
//Construct the necessary headers
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "token " + client.getAccessToken().getTokenValue());
headers.add(HttpHeaders.ACCEPT, "application/vnd.github.v3+json");
//Construct the html petition's body
ObjectMapper mapper = new ObjectMapper();
//String body = mapper.writeValueAsString(newissue);
String body =
"{\n" +
" \"title\": \"" + newissue.getTitle() + "\",\n" +
" \"body\": \"" + newissue.getBody() + "\",\n" +
" \"assignees\": [],\n" +
" \"milestone\": none,\n" +
" \"labels\": []\n" +
"}"
;
//Merge the header and the body
HttpEntity<String> request = new HttpEntity<String>(body, headers);
//To debug
System.out.println("### Going to send post: ");
System.out.println(body);
//Send the issue to the api
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("https://api.github.com/repos/" + user + "/" + repo + "/issues", HttpMethod.POST, request, String.class); //XXX
//To debug
System.out.println("### Post sent");
//To debug
System.out.println("### RESPONSE: " + response);
//Go to the repos' issues webpage
return "redirect:issues/"+user+"/"+repo+"/"+fullName;
}
I expected this method to create the new issue in the repository and then redirect to the repository's list of issues.
I've checked the body and it seems to be correct to me:
{
"title": "TestTitle",
"body": "TestBody",
"assignees": [],
"milestone": none,
"labels": []
}
I did it all consulting the GitHub api documentation: https://developer.github.com/v3/issues/#create-an-issue
According to the documentation you provided under 'Create an issue', the value for "milestone" should be an Integer. Therefore, looking at your request, none is not an integer. I'm not sure what int you would supply in the request but I don't believe 'none' would work.
String body =
"{\n" +
" \"title\": \"" + newissue.getTitle() + "\",\n" +
" \"body\": \"" + newissue.getBody() + "\",\n" +
" \"assignees\": [],\n" +
" \"milestone\": 0,\n" +
" \"labels\": []\n" +
"}"
;
This would create the following body:
{
"title": "TestTitle",
"body": "TestBody",
"assignees": [],
"milestone": 0,
"labels": []
}
In addition, looking at the 'List issues for a repository' section, it appears they mention to only use "none" as a String.
As Brandon and NeplatnyUdaj said the issue was probably related with the "milestone line" because it was mandatory to be an integer. I put "none" because I did not want to add any milestone and it is the keyword used if you want to remove the milestones after the creation of the issue.
Thanks to the people that answered me I figured out that you could remove the "milestone line" due there is no way to telling the API that "there are no milestones" in the creation of the issue (despite you can remove all the milestones after the creation according to the documentation).
Than you all!

Ajax - API Endpoint - Is this the right way to do?

I'm having a encoding issue when I send a AJAX request to an API Endpoint.
I have this Endpoint in the code below using Java Spring:
#Autowired
ApiKeyRepository apiKeyRepository;
#RequestMapping(value= "/weather/{cityName}/{fuCity}/now", method = {RequestMethod.GET}, produces="application/json" )
public ResponseEntity<Weather> getWeatherNowByCityName(#PathVariable(value = "cityName") String cityName, #PathVariable(value = "fuCity") State fuCity) throws JSONException, ParseException, java.text.ParseException {
String newCityName = cityName.toLowerCase();
try {
newCityName = URLDecoder.decode(newCityName , "UTF-8").replace(" ", "%20");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String weatherEndpoint = "/api/v1/locale/city?name=" + newCityName + "&state=" + fuCity.toString();
String appToken = apiKeyRepository.getByservice("climaTempo");
URL weatherDomain = new URL("http://apiadvisor.climatempo.com.br" + weatherEndpoint + "&token=" + appToken);
/// From here I send a JSON Request to the 'weatherDomain' to get the Weather from the city and her state that I get from the EndPoint Parameters
}
And I send this jQuery Ajax request to the Endpoint:
var uf = $("#colWeather #selectState").val();
var city = $("#colWeather #selectCity").val();
$.ajax({
url: host + '/weather/' + city + '/' + uf + '/now',
type: 'GET',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async: true
}).done(function (JSONReturn) {
//Actions with JSONReturn
});
But here in Brazil we have some cities with accents and cedilla like "Avaí" from "SP", "Mairiporã" from "SP" and "Missão Velha" from "CE".
If I send to the Endpoint an URL like "/weather/Americana/SP/now" or "/weather/Piracicaba/SP/now" the Endpoint gets the JSON return without problems.
But if I send to the Endpoint an URL like "/weather/Mairiporã/SP/now" or "/weather/Avaí/SP/now" the ClimaTempo API returns a null JSON and I get a NullPointerException.
I'm thinking that is a problem with the accents, but I can't send just "/weather/Mairipora/SP/now" without the accents because the ClimaTempo API demands that the city name must go with the accents, otherwise it returns a null JSON...
What am I doing wrong?
You need to encode and decode your characters.
Encode in JavaScript
Instead of url: host + '/weather/' + city + '/' + uf + '/now', go for
url: host + '/weather/' + encodeURIComponent(city) + '/' + uf + '/now'
Decode in Java
Instead of String newCityName = cityName.toLowerCase();, go for
String newCityName = URLDecoder.decode(cityName, Charsets.UTF_8.name()).toLowerCase();

How can we show the result in same page using ajax?

Here is my calculatioform.jsp which accept two number.
when I press submit button it will display the result which contains addition, subtraction, multiplication and division in the same calculationFrom.jsp using ajax and jquery.
the jquery and ajax I am using to get the response is.
<script type="text/javascript" >
$(document).ready(function(){
$(".button").click(function() {
var str = $("form").serialize();
var str = $("form").serialize();
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
var msg = data.val1 + " + " + data.val2 + " = " + data.sum;
alert(msg);
}
});
return false;
This is my calulator.jsp page on clicking submit button the request go to this
page.It will take two parameter from form and do calculation.The input value is
store in Val1 and Val2. based on this i calculate the result.
String result = "({";
result += " val1 : " + val1 + ",";
result += " val2 : " + val2 + ",";
result += " sum : " + (val1 + val2) + ",";
But this code is not working. what I need to do so that the code will work.
you are not defining data in your success callback function definition
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
success: function(data) { //you need data defined
Depending on what data is being returned you might need to specify the return type by using dataType option
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
//access properties through data
var msg = data.val1 + " + " + data.val2 + " = " + data.sum + '\n';
Additional Edit
Also it looks like you have the click event attached to the submit button which is probably causing the script to submit to itself or whatever page you have set in the action attribute, you need to have it cancel the default action by using preventDefault
$(".button").click(function(e) { //e will hold the event object
e.preventDefault() //prevents the default action of the event,
//in this case the form submission
var str = $("form").serialize();
you may also be getting a parse error, you can set an error callback as well
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
var msg = data.val1 + " + " + data.val2 + " = " + data.sum;
alert(msg);
},
error:function(xhr,errormsg) {
alert(errormsg);
}
});
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
var marks1=$("#marks1").val();
var marks2=$("#marks2").val();
var option=$("input:radio:checked").val();
var str = $("form").serialize();
$.ajax({
type: 'GET',
url: 'Operation',
data:{ marks1:marks1,
marks2:marks2,
option:option
},
success: function(data){
//Do something
}
});
});
});
You can get a response by your web method
$(function(){
$(".button").click(function() {
var str = $("form").serialize();
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
success: function(response) {
}
});
});

PlayFramework and jquery chart

i'm trying to use https://github.com/thegrubbsian/jquery.ganttView
in play 1.2.4
already check JQuery GanttChart - Apply Data
but my problem is how to renderJSON to the view,
i have try a simple one that is renderJSON("Hello"); and capture in the view, the problem is that i only manage to download a file like 4fporLKs.part1 that have inside Hello :(
can some one explain me how to do it
thanks
other guy is working in the same as i, but haven't got it
<script type="text/javascript">
$(function ()
{
$("#ganttChart").ganttView({
data : 'dataUrl: "data.json"',
slideWidth: 900,
behavior: {
onClick: function (data) {
var msg = "You clicked on an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
$("#eventMessage").text(msg);
},
onResize: function (data) {
var msg = "You resized an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
$("#eventMessage").text(msg);
},
onDrag: function (data) {
var msg = "You dragged an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
$("#eventMessage").text(msg);
}
}
});
//$("#ganttChart").ganttView("setSlideWidth", 600);
});
</script>
"hello" is not well formated json string, try:
renderJSON("{\"hello\":\"world\"}");
Also check Play's documentation for controllers to see how render ie. json from List (paragraph: Return a JSON String)

Categories