I am currently trying to call an ajax request from a JavaScript onchange handler to call a Spring MVC controller. I believe the way I am currently calling the URL in my view is wrong since I get an 404 error on the browser when the event is triggered and call for url. Can anyone shine some light if I have everything setup correctly?
Here is my code:
#Controller
public class DataTableController
{
#RequestMapping(value = "/table", method = RequestMethod.GET)
public String home(Model model) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> gpnList = new ArrayList<GPN>();
gpnList.add("GPN-1"); gpnList.add("GPN-2"); gpnList.add("GPN-3");
model.addAttribute("gpnList", mapper.writeValueAsString(gpnList));
return "index"; //name of my view
}
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(sectors);
}
}
Jquery Code:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
var filters = { "market" : market }
filters = JSON.stringify(filters);
$.ajax({
url: "/getsector",
type: "POST",
dataType : 'json',
contentType : "application/json",
data: JSON.stringify(filters),
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
The main thing I want to achieve is being able to call my controllers via ajax calls. Any other tips on Spring Controller Mapping and conventions will be appreciated.
If your a requesting information you should use GET requests, not POST.
You are mixing #RequestParam with a json payload. If you want to receive your filter as a request param it has to go at the url, not as a json payload, using something like:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
$.ajax({
url: "/getsector?market="+market,
type: "GET",
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
#RequestMapping(value = "/getsector", method = RequestMethod.GET)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
.... your logic.
}
On the other hand, if you really want to use POST requests with a json payload, you need to use #RequestBody at the controller and bind the json object to a bean with the same properties.
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestBody Market market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
return sectors;
}
public class Market
{
String market;
//getter and setter...
}
Bear in mind your javascript is wrong as well, you are using JSON.stringify twice.
If you use #ResponseBody and spring is configured fine it will make the serialisation for you when returning the response, so you do not have to do it manually.
This code has not been tested, it is just for you to get an idea.
Related
I've an application using Spring Boot + Bootstrap + Thymeleaf. I am trying to make an AJAX call to fill a combox use the jquery. In the Chrome workes well. In the Firefox gives me the 404 message. What could be happend?
The Firefox console.log message:
enter image description here
My AJAX code:
function carregaComboAtivoAjax(url) {
var Id = document.getElementById('idUo').value;
$.ajax({
url: url,
dataType: 'html',
data: { Id: Id },
success: function(data) {
if (data != null) {
$("body").html(data);
}
}
});
}
My Controller Code:
#RequestMapping(value = "/carregaComboAtivoCadastraCampo", method = RequestMethod.GET)
private String carregaComboAtivo(#RequestParam UUID Id, Model model) {
...
}
Best,
If you have the same problem, that is the solution:
In the spring boot controller method you need write like this:
#RequestMapping(value = "/carregaComboAtivoCadastraCampo", method = RequestMethod.GET, produces = { MediaType.TEXT_HTML_VALUE })
#ResponseBody
public ModelAndView carregaComboAtivo(#RequestParam UUID uoId, Model model) {
...
}
You need to set the media type produces.
I want to get data about my user from ajax request. But it never logs anything, which means it never reaches to success part of ajax request.
This is my controller
#Controller
#RequestMapping(value = "/api/profile")
public class ProfilController {
#Autowired
public UserService userService;
#RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(#PathVariable String username) {
User u = userService.findByUsername(username);
if(!userService.findAll().contains(u))
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
}
}
And this is my java script file.
$(document).ready(function() {
console.log(localStorage.getItem('loggedIn'));
var usrnm = localStorage.getItem('loggedIn');
$.ajax({
url: "http://localhost:8080/api/user/login/check/"+usrnm,
type: "GET",
headers: {"Authorization": localStorage.jwt},
success: function(data) {
console.log('success');
}
})
$.ajax({
url: "http://localhost:8080/api/profile/show/"+usrnm,
type: "GET",
success: function(data) {
console.log('This part is not executed');
}
})
});
I am new to Spring, actually I am new to programming so sorry if this question is not well formatted
You may have an error in the showData function. You should do the following:
#PathVariable("username") String username
Try to remove this.
#Controller
#RequestMapping("/api/profile") // fixed this!!! remove `value = `
public class ProfilController {
#Autowired
public UserService userService;
#RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(#PathVariable String username) {
User u = userService.findByUsername(username);
if(!userService.findAll().contains(u))
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
}
}
Hi I am a newbie in servlet and trying to send object from javascript to servlet using ajax. javascript code looks like this:
$.ajax({
url:'GetUserServlet',
contentType: "application/json",
data: JSON.stringify(response),
type:'post',
cache:false,
success:function(data){
//alert(data);
$('#somediv').text("user info sent successfully");
},
error:function(){
$('#somediv').text("some error occured");
}
}
);
Here response is object received from facebook api. It is:
reponse={ first_name: "Jhon", last_name: "Doe", id: "19862217575855" }
The doPost method of GetUserServlet is defined as:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
User user = gson.fromJson(request.getParameter(response), User.class);
System.out.println(user);
}
User.class is another class containing getter and setter for first_name, last_name and id
But the program is not getting compiled. I have used many syntax changes but cannot find the correct value. How can i get the response object inside servlet?
// 1. get received JSON data from request
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String json = "";
if(br != null){
json = br.readLine();
}
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to User
User user = mapper.readValue(json, User.class);
// 4. Set response type to JSON
response.setContentType("application/json");
System.out.println("..user.." + user);
i want to get a value through ajax call this is how i have done,
<input type="text" id="CIMtrek_CI_CER" name="CIMtrek_CI_CER" onblur="getProjectInfo()"/>
and this is what is my script,
function getProjectInfo(){
var cerNo = document.getElementById('CIMtrek_CI_CER').value;
$.ajax({
type: "POST",
url: "CIMtrek_Project_Information",
data: {
cerNo: cerNo
},
success: function (msg) {
alert("msg : "+msg);
document.getElementById('div_CIMtrek_CI_Used_By_ProjNo').innerHTML=msg;
}
});
}
and this is what is my spring method :
#RequestMapping(value = "/CIMtrek_Project_Information", method = RequestMethod.POST)
public String getProjectInfotmation(#RequestParam("cerNo") String cerNo,HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("cerNo : "+cerNo);
return cerNo;
}
controll goes to this method and prints the value also but it does not replicate in call back where i have assigned the value.
success: function (msg) {
alert("msg : "+msg);
document.getElementById('div_CIMtrek_CI_Used_By_ProjNo').innerHTML=msg;
}
when i have used firebug the response is HTTP Status 404 - /ProjectCapexMonitoring/WEB-INF/views/81723.jsp
81723 is the input i gave with this input .jsp is added and gives this exception.
Please help me to fine what is the and resolve.
Best Regards.
If you are expecting json response and
have jackson jars in your classpath
add #ResponseBody to your method
change
#RequestMapping(value = "/CIMtrek_Project_Information", method = RequestMethod.POST)
public String getProjectInfotmation(#RequestParam("cerNo") String cerNo,HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("cerNo : "+cerNo);
return cerNo;
}
to
#RequestMapping(value = "/CIMtrek_Project_Information", method = RequestMethod.POST)
public #ResponseBody String getProjectInfotmation(#RequestParam("cerNo") String cerNo,HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("cerNo : "+cerNo);
return cerNo;
}
I am using the following JQuery\JavaScript code to communicate with a WCF 4 REST service.
<script>
var serviceUrl = "http://services.xiine.com/Xiine/Live/AccountService/rest/json/Login";
var userInfo = {
"IsNotEncrypted":true,
"Password":null,
"UserName":null
};
var loginSuccess = function(data, textStatus, jqXHR){
console.log("yay");
};
var loginError = function(){
console.log("oh no");
};
$.post(serviceUrl , userInfo, loginSuccess);
$.post(serviceUrl , loginSuccess);
</script>
I am trying to establish why it is that the service will correctly return a false value when I do not pass the user data:
$.post(serviceUrl , loginSuccess);
As opposed to when I do pass user data, at which point it gives a POST 400 (Bad Request) error.
$.post(serviceUrl , userInfo, loginSuccess);
I am sure it has to do with how the JSON object, userInfo, is being built or interpreted, and I can post Fiddler 2 or WireShark dumps, if that will help. Just let me know...
I don't really have access to changing the WCF side of the service, so hopefully there is something I can do on my end to make this work.
Thanks!
Edit
I got a little more information... Apparently, the problem is that the server is responding with the following error:
The server encountered an error processing the request. The exception message is 'The incoming message >has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', >'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the >documentation of WebContentTypeMapper for more details.'. See server logs for more details. The >exception stack trace is:
at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
So I am thinking I need to figure out how to get the object to go across the wire as a JSON object via a JQuery.post() method.
More information --- Again...
ok... There is no app.config or web.config, as such.
Here is what I can get as far as the contracts and code and what-not.
[ServiceContract]
public interface IAccount
{
[OperationContract]
bool Login(UserInformation user);
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AccountService : IAccount
{
public bool Login(UserInformation user)
{
//stuff...
}
}
[DataContract]
public class UserInformation
{
[DataMember(IsRequired = true)]
public string UserName;
[DataMember(IsRequired = true)]
public string Password;
[DataMember(IsRequired = true)]
public bool IsNotEncrypted;
}
public interface IUserInformation
{
UserInformation UserInformation { get; set; }
}
So, I found the answer to my question.
Someone attempted to point me in the right direction with a mention of the JSON.stringify() method, but it took me a little effort to get it implemented correctly.
In the end, I used WireShark to sniff out the http request, see what was actually being sent and received, and observe that not only did I need to stingify the data, but I also needed to specify the content type.
Here is the final code.
// This is the URL that is used for the service.
var serviceUrl = "http://services.xiine.com/Xiine/Live/AccountService/rest/json/Login";
// This is the JSON object passed to the service
var userInfo = {
"UserName": null,
"Password": null,
"IsNotEncrypted": true
};
// $.ajax is the longhand ajax call in JQuery
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/json; charset=utf-8",
// Stringify the userInfo to send a string representation of the JSON Object
data: JSON.stringify(userInfo),
dataType: "json",
success: function(msg) {
console.log(msg);
}});
in the interface for your service, you need to have the OperationalContract attribute and in that attribute, you need to set the RequestFormat. Here is an example of what it might look like.
[OperationContract, WebInvoke(UriTemplate = "/runGenericMethodJSON", Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]