I am trying to implement the below scenario in Spring MVC.But I am facing issues and not able to decide about the right Approach.
I am Using jsonRequest/jsonResone(Restful Webservices)
1.I have a SignUP.jsp Form which contains few field which need to be submitted to controller.
<form method="POST" onsubmit="javascript:signupObj.signup()">
<table>
<tr>
<td>Username : </td>
<td><input id="username"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input id="password"/></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
2.onSubmit of form it will invoke signup javascript function mentioned below
var signupObj = {
showSignup : function() {
//There are Two Ways to Declare Function The Other Way is function showSignup().Checkout the reasons
$.ajax({
type: "GET",
url: "showSignup",
success: function(response) {
$("#signupView").html( response );
}
});
},
signup : function() {
alert("In Signup function");
var input = '{';
input += '"username":"'+$('#username').val()+'",';
input += '"password":"'+$('#password').val()+'"';
input += '}';
alert(input);
$.ajax({
type: "POST",
url : "signup",
contentType: "application/json; charset=utf-8",
data: input,
dataFilter: function (response) {
return response;
},
// crossDomain: true,
async:false,
success: (function(data) {
alert("In ajax Sucess");
alert(data.profileID);
signupObj.redirectview("success",data);
}),
error : function(data,textStatus,error){
alert("In ajax Failure");
alert(error);
signupObj.redirectview("failure",data);
},
dataType: "json"
});
alert("ajax finished");
},
redirectview : function(message,data) {
alert("inside redirect view");
if(message == "success"){
url = "success";
}
else{
url = "error";
}
$.ajax({
type: "POST",
url : "success",
contentType: "application/json; charset=utf-8",
data: data,
async:false,
dataType: "json",
dataFilter: function (response) {
return response;
},
// crossDomain: true,
success: (function(data) {
alert("data");
}),
error : function(data,textStatus,error){
alert("In ajax Failure redirect");
alert(error);
},
});
}
};
3.The Above javascript function does the ajax call to the controller(input is jsonRequest)
#RequestMapping(value="/signup",method=RequestMethod.POST)
#ResponseBody
public ProfileDTO signup(#RequestBody LoginDTO loginDTO) {
ProfileDTO profileDto = new ProfileDTO();
//In case no errors in backend logic
profileDto.setError(null);
profileDto.setProfileID("profileID");
profileDto.setProfileName("profileName");
System.out.println("Submitting SignUP Form Will Return ProfileID");
return profileDto;
}
//Below method is for success view
#RequestMapping(value="/success",method=RequestMethod.POST)
#ResponseBody
public String checkSignup(#RequestBody ProfileDTO profileDto,HttpServletRequest httprequest,HttpServletResponse httpResponse
) {
//model.addAttribute(loginDTO);
System.out.println("In loginSuccess");
return "loginSucess";
}
4.The Controller gives the JSON Response of profileDTO. Now based on the profileDTO.getErrors I have to call either loginSuccess.jsp or loginFailure.jsp
Now My Question is:
1) How I can use jsonResponse in ajax call to redirect to loginSuccess.jsp or loginFailure.jsp and how will pass my profileDTO data to the loginSuccess view.
2.)Please Suggest me the Best Practice Which should be Followed.
1.) First of all you can reduce your code in javascript like below, Directly serialize the form object.
var signupObj = {
signup : function() {
alert("In Signup function");
$.ajax({
type: "POST",
url : "signup",
data: $('#myForm').serialize(),// add "myForm" as the form id
async:false,
success: (function(data) {
alert("data"+data);
redirectView("success",data);
})
error : function(data, textStatus, errorThrown) {
alert(error_occured);
redirectView("error",data);
}
});
}
};
<script
function redirectView(message,data){
var url = "";
if(message == "success"){
url = "/success";
}else{
url = "/error";
}
$.ajax({
type: "POST",
url : url,
data: data
async:false,
success: (function(data) {
alert("data"+data);
})
error : function(data, textStatus, errorThrown) {
alert(error_occured);
}
});
}
</script>
2.) Redirect the success or failure view from the controller itself.
3.) Pass my profileDTO data to the loginSuccess view.
Spring MVC, from version 3, allows you to return objects directly converted into JSON using the #ResponseBody annotation in a Controller as shown here
#RequestMapping(value="/signup",method=RequestMethod.POST)
#ResponseBody
public ProfileDTO signup(#ModelAttribute("LoginDTO") LoginDTO loginDTO,BindingResult bindingResult) {
ProfileDTO profileDto = new ProfileDTO();
//In case no errors in backend logic
profileDto.setError(null);
profileDto.setProfileID("profileID");
profileDto.setProfileName("profileName");
System.out.println("Submitting SignUP Form Will Return ProfileID");
return profileDto;
}
If Forward from controller
With a prefix of forward, Spring will get a RequestDispatcher for the specified path and forward to it. Part of that process will include taking the Model from the ModelAndView created for that request handling cycle and putting all its attributes into the HttpServletRequest attributes.
The Servlet container will take the RequestDispatcher#forward(..) and again use your DispatcherServlet to handle it. Your DispatcherServlet will create a new ModelAndView with a new Model for this handling cycle. Therefore this Model doesn't contain any of the attributes from before but the HttpServletRequest attributes do.
In your case, this
modelMap.put("key", "value");
will end up being in
HttpServletRequest request = ...;
request.getAttribute("key");
Related
I created code where pass data to spring rest but don't work correctly see my code below:
#PutMapping("/notification/save/{id}")
public #ResponseBody String update(#PathVariable("id") long id, #RequestBody AccountNotification accountNotification){
String result="ok";
ServiceAccount serviceAccount = new ServiceAccount();
serviceAccount.setId(id);
//accountNotification.setServiceAccount( serviceAccount );
//result =notificationsService.update(id,accountNotification);
JSONObject jObject = new JSONObject();
try
{
JSONArray jArray = new JSONArray();
JSONObject accountNotificationJSON = new JSONObject();
if(result.equals("ok")) {
accountNotificationJSON.put("success", "true");
accountNotificationJSON.put("messages", "Successfully Saved");
}
else {
accountNotificationJSON.put("success", "false");
accountNotificationJSON.put("messages", "NOT Successfully Saved");
}
jArray.put(accountNotificationJSON);
jObject.put("data", jArray);
} catch (JSONException jse) {
logger.error( jse.getMessage());
}
return jObject.toString();
}
my javascrit has:
$("#saveChanges").on('click',function(){
var params1={
proxy:$(proxy).val() ,
port:$(port).val(),
uri:$(uri).val(),
actived:$(actived).val()=="on"?true:false
};
$.ajax({
url: 'notification/save/'+id,
params: params1,
type: 'post',
success:function(response) {
if(response.data[0].success == "true") {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.data[0].messages+
'</div>');
// close the modal
$("#editMember").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.data[0].messages+
'</div>');
}
},
error: function(x, e) {
alert(x);
}
});
in this situation ajax code return 400. Any body knows why? thanks if withdraw #RequestBody annotation the rest has been called but the parameter accountNotifications is initialized but without valeus passed.
there is a put mapping #PutMapping("/notification/save/{id}") in your Rest code, but in your js called by post method type: 'post', so it returns 400 Bad Request, you should use type: put which is equals to your Rest method.
#PutMapping("/notification/save/{id}")
public #ResponseBody String update(#PathVariable("id") long id,
#RequestParam AccountNotification accountNotification){
.....
}
$.ajax({
url: 'notification/save/'+id,
params: params1,
type: 'put',
success:function(){
}})
I resolved this mode:
#RequestMapping(value={"/notification/save/{id}"}, method = {RequestMethod.GET, RequestMethod.POST},
produces = "application/json"
)
public #ResponseBody String update(#PathVariable("id") long id, AccountNotification accountNotification){
String result="ok";
JavaScript:
$("#saveChanges").on('click',function(){
var params1={
proxy:$(proxy).val() ,
port:$(port).val(),
uri:$(uri).val(),
actived:$(actived).is(':checked')
};
$.ajax({
url: 'notification/save/'+id,
data: params1,
type: 'post',
success:function(response) {
I replaced into js param with data
I received empty data from spring controller, even if it returned data the ajax success function received it empty. I tried to return string directly from controller like this:
#ResponseBody
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(#RequestParam("posImsi") String posImsi,#RequestParam("posMsisdn") String posMsisdn){
return "success";
}
and the ajax is:
$.ajax({
url : "test",
type : "POST",
data : formData,
beforeSend : function(){
$("#overlay").show();
},
success : function(ajaxResult){
console.log(ajaxResult);
},
complete : function(status) {
},
error : function(jqXHR, status, errorThrown) {
alert(jqXHR);
alert(status);
alert(errorThrown);
}
});
The problem is solved by using the XMLHttpRequest object to do ajax request, I really don't know what is the difference but here is what I used:
var x = new XMLHttpRequest();
x.open("POST","test",true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.send(formData);
x.onload = function () {
console.log(this.responseText);
};
for more information about XMLHttpRequest object: http://www.w3schools.com/xml/dom_http.asp
I'm trying to post a JSON Object, with Ajax, to an Rest Spring MVC Controller, but I met some troubles.
Let's present you my code:
Controller
#RequestMapping(value = "/register/checkUsername.html", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody JsonResponse checkUsername(#RequestBody JsonUsername username) {
String usernameString = username.getUsername();
JsonResponse response = new JsonResponse();
response.setMessage(usernameString + "Available");
return response;
}
Ajax Function
function displayUsernamError(data) {
var json = "<h4>Eroare</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#usernameError').html(json);
}
function checkUsername(){
var username = document.getElementById("username");
var search = {
"username" : username.value
}
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url : "http://localhost:8080/skill-assessment/register/checkUsername.html",
data : JSON.stringify(search),
success : function(result) {
console.log("SUCCESS: ", data);
displayUsernamError(result);
},
error: function(e){
console.log("ERROR: ", e);
displayUsernamError(e);
},
done : function(e) {
console.log("DONE");
}
});
}
And finally the html form:
<form:form modelAttribute="user" method="POST" enctype="utf8">
<tr>
<td><label>Username</label></td>
<td><form:input path="name" id="username" /></td>
<td>
<p id="usernameError">
</p>
</td>
</tr>
<button type="button" onClick="checkUsername()">Register</button>
</form:form>
So, I'm calling the checkUsername method when I press click on the Register button, only for test.
The ajax function is called and this send the JSON to the controller. I used the debug and the controller seems to get the JSON Object.
The problem is with the controller Response, because in the error div from my html page, I get this error:
HTTP Status 406
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request \"accept\" headers.
Where is the problem? Who can give me an idea?
You need to specify the below code inside of the request mapping annotation
#RequestMapping(value = "/register/checkUsername.html", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
you no need to specify the produces attribute because #Responsebody will produce the content based on the request object content type[optional]. if you want other then it then only you have to mention it.
; charset=utf-8 is the default one in Ajax call. you no need mention it separately. try do these changes.
use #ResponseBody need object to json,
seems missing some jar file
(jackson-mapper-asl.jar and jackson-core-asl.jar)
try to import it
First check if your controller is returning a JSON. You can use any REST client and see what is the return header. If not then add the Jackson mapper bean.
Also, try setting the Accept header in the ajax call.
$.ajax({
headers: {
Accept : "application/json",
Content-Type: "application/json"
},
data: "data",
...
})
in .js(java script)
ajax function
var variable="test";
$.ajax({
url: baseUrl + "nameController/test1",
async: false,
data: {val: variable},
dataType: 'html',
success: function (dat) {
console.log(dat);
}
});
you create nameController.java
controller
#RequestMapping(value = "test1", method = RequestMethod.POST)
public #ResponseBody
String checkRoomStatusReservation(#RequestParam(value = "val", required = true) String parse) {
System.out.println("parse"+parse);
//value from parse=test
return parse;
}
you can try this
I'm trying to make a simple ajax request using Java (JSP + Servlet) and Ajax (jQuery). The Ajax request is working as expected, and the servlet code is reached.
The problem is that I can't get the values of the parameters sent by the request. I get null values.
This is the code in the servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
String perfilId = request.getParameter("perfilId"); //Null value
String perfilNombre = request.getParameter("perfilNombre"); //Null value
try (PrintWriter out = response.getWriter()) {
Gson gson = new Gson();
JsonObject obj = new JsonObject();
obj.addProperty("mensaje", "Algún mensaje. Id: " + perfilId + ", Nombre: " + perfilNombre);
out.print(gson.toJson(obj));
out.flush();
}
}
Ajax request inside a JSP:
$.ajax({
type: "POST",
url: 'srvl_def',
cache: false,
contentType: "application/json;",
dataType: "json",
data: {
perfilId: $('#perfilId').val(),
perfilNombre: $('#perfilNombre').val()
},
success: function (data) {
alert(data.mensaje);
}
});
The request data looks like this:
perfilId=1&perfilNombre=nuevo
Perhaps I'm missing something?
EDIT
This is the HTML
<input type="text" id="perfilId" />
<input type="text" id="perfilNombre" />
<button type="button" id="btnGuardar">Enviar</button>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$('#btnGuardar').click(function (){
//ajax call
});
</script>
Following this answer, #ShaunakD referenced this in a comment (see question), I was able to obtain the values sent by the ajax call.
The call looks like this:
var perfilId = $('#perfilId').val();
var perfilNombre = $('#perfilNombre').val();
$.ajax({
type: "POST",
url: 'srvl_def',
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8;",
dataType: "json",
data: {
perfilId: perfilId,
perfilNombre: perfilNombre
},
success: function (data) {
alert(data.mensaje);
}
});
if your ajax call is inside some function try this :
var perfilId = $('#perfilId').val();
var perfilNombre = $('#perfilNombre').val();
$.ajax({
type: "POST",
url: 'srvl_def',
cache: false,
contentType: "application/json;",
dataType: "json",
data: {
perfilId: perfilId ,
perfilNombre: perfilNombre
},
success: function (data) {
alert(data.mensaje);
}
});
Hi I'm trying to simply send a string once a button is pressed in my website using ajax to my java code in Play framework. I can't find a simple tutorial which simply explains how to do this. They are all using templates.
Lets say my java method is:
public static Result upload() { }
and my button is calling a javascript method which gets a String from another input when clicked:
<input id="submit" type="submit" onclick="send();">
I didn't test, but something like this should work.
Application controller
public static Result upload() {
JsonNode node = request().body().asJson().get("stringField");
String inputString = node.getTextValue();"
System.out.println(inputString) // prints the string from the form field
return ok();
}
Routes
POST /uploadfoostring controllers.Application.upload()
Template
<input type="text" id="string-field">
<input id="submit" type="submit" onclick="send();">
<script type = "text/javascript" >
$('#submit').click(function(evt) {
var inputString = $('#string-field').val();
var obj = {
stringField: inputString;
};
$.ajax({
url: "#routes.Application.upload()",
data: JSON.stringify(obj),
headers: {
'Content-Type': 'application/json'
},
type: 'POST',
success: function(res) {
if (res) {
console.log("Success!");
} else {
console.log("Failed...");
}
}
});
}
</script>
POST /home/testPost controllers.Application.testPost
//Server Side.
def testPost = Action { request =>
println("testPost Called");
println(request.body.asFormUrlEncoded.get("name").head);
Ok("Succeeded");
}
Client Side:
public static testPost(){
$.ajax({
url:"/dialog/testPost",
type:"POST",
data:{
name:"Varadharajan R"
},
success:function(response){
alert(response);
}
});
}