415 Error while calling controller using ajax - java

This is my jsp page home.jp
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#sampleForm').click(
function(event) {
var firstname = "Chethan";
var age = 12;
var json = {
"name":firstname,
"age":age
}
alert(json)
$.ajax({
url : "/com/testAjacCall",
data: JSON.stringify(json),
type : "POST",
mimeType: 'application/json',
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success : function(response) {
alert("SUCCESS--->"+ response );
},
error : function(error) {
alert("error---->"+error);
}
});
return false;
});
});
</script>
This is my controller HomeController.java
#RequestMapping(value = "/testAjacCall", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String processAJAXRequest(#RequestBody Person person ,HttpServletResponse response) {
String jQresponse = "Hello";
System.out.println("IAMWORKING");
// Process the request
// Prepare the response string
return jQresponse;
}
and this is my POJO Person.java
public class Person {
String name;
int age;
public Person(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Getting
HTTP Status 415 -message-description-The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
I tried many solutions but i am not able to find my mistake. please do help me where i am going wrong.

Related

I tried to fetch my database content and display using Ajax but I see this error

ERROR:
The resource identified by this request is only capable of generating
responses with characteristics not acceptable according to the request
"accept" headers.
Here is my Ajax code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* function new_element(){ */
$(document).ready(function(){
$("#search").click(function(){
console.log("fetched list");
$.ajax({
url: "http://localhost:8080/SpringMvcJdbcTemplate/listContact",
type : "GET",
dataType : 'json',
/* contentType : "application/json", */
accept : "application/json",
success : function(data) {
alert(this.getResponseHeader("Content-Type"));
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
}
});
});
});
function display(data) {
console.log("inside func list");
var json = "<h4>Ajax Response</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#feedback').html(json);
}
</script>
The controller class
#JsonView(Views.Public.class)
#RequestMapping(value = "/listContact",
method = RequestMethod.GET,
produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public AjaxResponseBody listContact(ModelAndView model) throws IOException {
List<Contact> listContact = contactDAO.list();
System.out.println("listContact");
List<Contactdup> listContdup = new ArrayList<Contactdup>();
Contactdup contactdup = null ;
AjaxResponseBody result = new AjaxResponseBody();
for(Contact contact:listContact) {
contactdup = new Contactdup();
contactdup.setFname(contact.getFname());
System.out.println("inside for");
System.out.println(contact.getFname());
listContdup.add(contactdup);
}
result.setResult(listContdup);
result.setCode("200");
result.setMsg("");
return result;
}
AjaxResponseBody:
package ajaxrespose;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonView;
import net.codejava.spring.model.Contactdup;
import net.codejava.spring.model.Views;
public class AjaxResponseBody {
public List<Contactdup> getResult() {
return result;
}
public void setResult(List<Contactdup> result) {
this.result = result;
}
#JsonView(Views.Public.class)
String msg;
#JsonView(Views.Public.class)
String code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#JsonView(Views.Public.class)
List<Contactdup> result;
}
The route you are calling is probably not returning content-type "application/json".

Expected a string but was BEGIN_OBJECT at line 3 column 4 path $.SUCCESS

I made a post request method with Retrofit2 but I encountered this problem on my response.
Expected a string but was BEGIN_OBJECT at line 3 column 4 path $.SUCCESS
The response should be
{
"SUCCESS" :
{
"200" : "access granted",
"ra" : "approved",
"la" : "approved",
"ch" : "approved"
}
}
I uses this code for the post request
#POST("login")
Call<Post> createPost(#Body Post post);
And for the POJO class
public class Post {
private String anthony;
private String SUCCESS;
public Post(String name) {
this.anthony = name;
}
public String getSUCCESS() {
return SUCCESS;
}
}
For the method I use the following code
private void createPost() {
Post post = new Post("mypassword");
Call<Post> call = jsonPlaceHolderApi.createPost(post);
call.enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (!response.isSuccessful()) {
textViewResult.setText("Code: " + response.code());
return;
}
Post postResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "S" + postResponse.getSUCCESS();
textViewResult.setText(content);
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
Does anyone know what's wrong with my code? I expected to get the response inside the "SUCCESS" json object.
You expect SUCCESS to be an object in your wanted response but you have defined it as a String in your Post class. You should use an object for SUCCESS instead.
public class Post {
private String anthony;
private PostSuccess SUCCESS;
public Post(String name) {
this.anthony = name;
}
public PostSuccess getSUCCESS() {
return SUCCESS;
}
}
public class PostSuccess {
#JsonProperty("200")
private String _200;
private String ra;
private String la;
private String ch;
}

How to send JSON object data using JQuery+Ajax which will consume by RestFulServices?

I have to send JSON object data using JQuery+Ajax which will consume by RestFulWebServices. In backend I am using hibernate(ver 4)+Maven(ver 3)+spring(ver 4), MySql data base and ApacheTopcat server(ver 7). But my JqueryAjax code index.html client is not sending data over server.Please help me I am searching But their is no error in my Jquery Ajax part. If any other apart you need for tell me I will past here.
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
alert("1");
$("button").click(function(){
alert("2");
var custName = $('#custName').val();
var custMobile = $('#custMobile').value;
var custEmail = $('#custEmail').value;
var custAddress = $('#custAddress').value;
var JSONObject={"custName":custName, "custMobile": custMobile, "custEmail":custEmail,"custAddress":custAddress};
/*
var jsonData=JSON.stringify({
"custName": "Navin1",
"custMobile": "876532468",
"custEmail": "abc#gmal.com",
"custAddress": "BAnaore"
});
*/
var jsonData = JSON.stringify( JSONObject );
$.ajax({
url: "http://localhost:8080/HomeServiceProvider/customer/saveCustomer",
type: "POST",
dataType: "json",
data: jsonData,
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
processData:false,
success: function(response){
alert("scucess");
alert(JSON.stringify(response));
},
error: function(err){
alert("Fail");
alert(JSON.stringify(err));
}
});
});
});
</script>
</head>
<body>
<form>
<fieldset style="text-align:right; width:300px">
<legend><b>Registration Form</b></legend>
Name <input type="text" id="custName" name="custName"/><br/>
Mobile No <input type="text" id="custMobile" name="custMobile"/><br/>
Email <input type="text" id="custEmail" name="custEmail"/><br/>
Address <input type="text" id="custAddress" name="custAddress"/><br/>
<button>Save Data</button>
</fieldset>
</form>
</body>
</html>
my server url is
http://localhost:8080/HomeServiceProvider/customer/saveCustomer
My customer rest controller is
CustomerRestController
#RestController
#RequestMapping("/customer")
public class CustomerRestController {
private static Logger log = LogManager.getLogger(CustomerRestController.class);
#Value("${msg.customeradded}")
private String message;
#Value("${msg.successcode}")
private int code;
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/saveCustomer", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Status saveCustomer(#RequestBody Customer customer){
try {
customerService.saveCustomer(customer);
return new Status(code, message);
} catch (Exception e) {
return new Status(0, e.toString());
}
}
#RequestMapping(value="/getAllCustomer",method=RequestMethod.GET, headers="Accept=application/json")
public #ResponseBody List<Customer> getAllCustomer(){
List<Customer> customers = null;
try {
customers = customerService.getAllCustomer();
log.info("Size:"+customers.size());
log.info("customers:"+customers);
} catch(Exception e) {
e.printStackTrace();
}
return customers;
}
}
MyCustomer class Customer.Java for making table through Hibernate
#Entity
#Table(name = "customer", catalog = "service4homes")
public class Customer implements java.io.Serializable {
private Integer CId;
private String custName;
private String custMobile;
private String custEmail;
private String custAddress;
public Customer() {
}
public Customer(String custName, String custMobile, String custAddress) {
this.custName = custName;
this.custMobile = custMobile;
this.custAddress = custAddress;
}
public Customer(String custName, String custMobile, String custEmail,
String custAddress) {
this.custName = custName;
this.custMobile = custMobile;
this.custEmail = custEmail;
this.custAddress = custAddress;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "c_id", unique = true, nullable = false)
public Integer getCId() {
return this.CId;
}
public void setCId(Integer CId) {
this.CId = CId;
}
#Column(name = "cust_name", nullable = false, length = 50)
public String getCustName() {
return this.custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
#Column(name = "cust_mobile", nullable = false, length = 13)
public String getCustMobile() {
return this.custMobile;
}
public void setCustMobile(String custMobile) {
this.custMobile = custMobile;
}
#Column(name = "cust_email", length = 100)
public String getCustEmail() {
return this.custEmail;
}
public void setCustEmail(String custEmail) {
this.custEmail = custEmail;
}
#Column(name = "cust_address", nullable = false, length = 300)
public String getCustAddress() {
return this.custAddress;
}
public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
}
}
When I run code What I am getting
form.index data
After click Button
$.ajax({
url:urlName,
type:"POST",
contentType: "application/json; charset=utf-8",
data: jsonString, //Stringified Json Object
async: false, //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
cache: false, //This will force requested pages not to be cached by the browser
processData:false, //To avoid making query String instead of JSON
success: function(resposeJsonObject){
}});
In Controller,
#RequestMapping(value = "/saveCustomer", method = RequestMethod.POST, consumes = "application/json")
public #ResponseBody Status saveCustomer(#RequestBody String jsonString){
//check whether u r receiving some data over here
System.out.println("received :" + jsonString);
try {
customerService.saveCustomer(customer);
return new Status(code, message);
} catch (Exception e) {
return new Status(0, e.toString());
}
}

Receiving null values in REST Resource

I keep receiving null values while sending these two parameters thru a POST with ajax (tried with Poster as well):
#POST
#Path("/update")
#Produces(MediaType.APPLICATION_JSON)
public void update(String Path, String Content) {
updateURI(Path,Content);
}
Path: http://essam.ldm.io/stor...amblog/ChannelList/ch1/post2
Content: <http://essam.ldm.io/storage/essamblog/ChannelList/ch1/post2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://crosscloud/mblog/Post>. <http://essam.ldm.io/storage/essamblog/ChannelList/ch1/post2> <http://crosscloud/mblog/owner> <https://essam.ldm.io></https:>. <http://essam.ldm.io/storage/essamblog/ChannelList/ch1/post2> <http://purl.org/dc/terms/created> <2013-03-06T16:41:18+0300^^http://www.w3.org/2001/XMLSchema#dateTime>. <http://essam.ldm.io/storage/essamblog/ChannelList/ch1/post2> <http://rdfs.org/sioc/ns#content>.
Obviously I cannot send them as #QueryParam or #PathParam due to the format.
It is irrilevant putting the jQuery code since it deosnt wotk with Poster neither, but here it is:
function doUpdate(path, rdf)
{
var obj1 = {"path": path, "rdf": rdf};
var sUrl = "http://localhost:8080/browsing/services/RDF/update";
$.ajax({
type: "POST",
url: sUrl,
contentType: "application/json; charset=utf-8",
data: obj1,
//dataType: "json",
async: false,
success: function (resp, status, xhr) {
$("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
$("#message").hide();
$("#login_message").html("<font color='green'><b>Record succesfully updated</b></font>d");
},
error: function(resp, status, xhr){
$("#message").html("ERROR: " + resp.status + " " + resp.statusText + "\n" + xhr);
$("#message").show();
}
});
}
Anything I am doing wrong?
Thanks,
You can encode it (i.e. base64) before you send it and decode it on server or you can use JSON as request param.
Using JSON, for example;
#POST
#Path("/update")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void update(PathContext ctx) {
updateURI(ctx.getPath(),ctx.getContent());
}
#XmlRootElement
public class PathContext {
private String path;
private String content;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Your JSON will look like;
{"path": somePath, "content": someContent}
Hope it helps.

spring Model is not filling automatically with json data

I have written some sort of code to send data from client to spring model. and want that json data should automatically fill the java class. but not able to do this.
Jquery looks like this
$('#login-form').submit(function(event){
var username = $('#id_username').val();
var password = $('#id_password').val();
alert(username + password)
var json = { "loginId" : username, "password" : password};
$.ajax({
type: "POST",
url: $("#login-form").attr("action"),
data: JSON.stringify(json),
beforeSend: function(xhr){
var mess = validateForm();
if(mess.length != 0){
$('#error-mes').show();
$('#error-mes').html(mess);
event.preventDefault();
return false;
}
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
return true;
},
success: function(response){
$('#error-mes').html(response);
$('#error-mes').show();
},
error: function(e){
alert('Error: ' + e);
}
});
event.preventDefault();
$('#userName').hide();
$('#spn_password').hide();
});
Spring code like this
#RequestMapping(value = "/signin", method = RequestMethod.POST )
public #ResponseBody String submitCustSignInForm(HttpServletRequest request, #ModelAttribute("model") Person model,
HttpSession sess) {
String response = "";
Person person = null;
if (sess.getAttribute("USER_INFO") == null) {
person = tsService.login(model);
if (person == null) {
response = "User name or password does not match.";
} else {
response = "success";
sess.setAttribute("USER_INFO", person);
}
}
return response;
}
Person model has same loginId and password attribute and setter and getter in class.
can some body tell me how can it achieved.

Categories

Resources