Return Object from controller to ajax - ajax

Code below succesfully send String from jsp via ajax to controller and returning some String.
How to send back (from controller to ajax) object which contains only getter and setter or Boolean?
ajax:
$.ajax({
type: 'get',
url : 'register/checkUsername',
data : {'typedText' : typedText},
success : function(data) {
$('#doesUsernameAvailable').text("ok " + data);
},
error: function(){
$('#doesUsernameAvailable').text('error');
}
});
controller:
#RequestMapping(value = "/checkUsername", method = RequestMethod.GET)
public #ResponseBody String checkUsername(String typedText,
HttpServletResponse response){
//some code with return Boolean or Object
return "text from controller";
}

Solution:
I does not post pom.xml. It was missing:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
And now few modification's.
ajax:
$.ajax({
type : 'get',
contentType : "application/json",
url : 'register/checkUsername',
data : {'typedText' : typedText},
dataType : 'json',
success : function(data) {
$('#doesUsernameAvailable').text("ok " + data.isAvailable);
},
error: function(){
$('#doesUsernameAvailable').text('error');
}
});
And now we can return Object from Controller via JSON.
Controller:
#Controller
#RequestMapping("/register")
public class RegisterController {
#RequestMapping(value = "/checkUsername", method = RequestMethod.GET)
public #ResponseBody CheckUsernameResponse checkUsername(
#RequestParam String typedText){
return new CheckUsernameResponse(true);
}
Object:
public class CheckUsernameResponse {
private Boolean isAvailable;
public CheckUsernameResponse(Boolean isAvailable) {
this.isAvailable = isAvailable;
}
Hope it help!

Related

Error ajax can not pass params to Spring Controller

var companyCode = [];
var data = {
'companyCode': companyCode, //array this may be problem
'actionUserGroup': usersession.userGroup,
'formType': 'IN',
'actionId': usersession.userId,
'submittedDate': [submitted_s,submitted_e] //array this may be problem
};
console.log(data);
$.ajax({
type : "POST",
data : JSON.stringify(data),
contentType: "application/json; charset=utf-8",
crossDomain: true,
cache: false,
url: appConfig.endPoint + 'search/myTask',
success: function(data){
console.log(data);
}
});
{this ajax side}
#RequestMapping(value = "/myTask", method = RequestMethod.POST)
public #ResponseBody JSONObject searchmyTask(Model model, HttpSession session,
#RequestParam (value="companyCode") String[] companyCode,
#RequestParam (value="actionUserGroup") String actionUserGroup,
#RequestParam (value="formType") String formType,
#RequestParam (value="actionId") String actionId,
#RequestParam (value="submittedDate") String[] submittedDates
) throws Exception {
/**
* if "userGroup" = 'ADMIN'
{this Spring Controller}
http://localhost:9091/gcbg/search/myTask 400 (Required String[] parameter 'companyCode' is not present) jquery.min.js:2 POST
{this one is error}
Please help me to figure out this problem. Thanks
i just did few changes to make it work, so if you modify the next options should work for yourself.
$.ajax({
method : "POST",
data : data,
crossDomain: true,
cache: false,
url: appConfig.endPoint + 'search/myTask',
success: function(data){
console.log(data);
}
});
And in your controller:
#RequestMapping(value = "/myTask", method = RequestMethod.POST)
public #ResponseBody JSONObject searchmyTask(Model model, HttpSession session,
#RequestParam (value="companyCode[]") String[] companyCode,
#RequestParam (value="actionUserGroup") String actionUserGroup,
#RequestParam (value="formType") String formType,
#RequestParam (value="actionId") String actionId,
#RequestParam (value="submittedDate[]") String[] submittedDates
) throws Exception {
Hope it helps

Spring - Stop redirection on error

I have a page to manage users and I would like to stay on the page if any error occurs when clicking save.
The only cases I found online where to do with validation.
Also my page requires the userId to be posted so I don't think returning the name of the original page in the controller would work. Also I would loose the changes made in the page.
What I am trying to achieve is stay in the same page, showing a message to the user.
Here is my controller:
#RequestMapping(method = RequestMethod.POST)
public String editUser(#RequestParam("userId") String userId, final Map<String, Object> model) {
User user = spiService.getUser(userId);
model.put("user", user);
configureRoles(model, user);
return "edituser";
}
#RequestMapping(path = "/updateUser", method = RequestMethod.POST)
public String updateUser(#RequestParam("userJson") String userRoles, #RequestParam("userId") String userId, final Map<String, Object> model) throws IOException {
User user = spiService.getUser(userId);
try {
addRoles(JsonUtil.getField(userRoles, "addedRoles"), user.getRoles(), userId);
removeRoles(JsonUtil.getField(userRoles, "removedRoles"), user.getRoles(), userId);
} catch (Exception ex) {
// What now?
}
return "users";
}
Instead of redirecting you can use Ajax calls in your controller. For that you have to create one AjaxPojoClass for exampleAjaxResponseBody as your convenience.
For example
$.ajax({
type : "POST",
contentType : "application/json",
url : "/yourUrl",
data : JSON.stringify(data),
dataType : 'json',
success : function(data) {
window.location.replace("/successUrl")
},
error : function(e) {
display(e);
},
});
AjaxController
#Controller
public class AjaxController {
#ResponseBody
#RequestMapping(value = "/yourUrl")
public AjaxResponseBody getSearchResultViaAjax(#RequestBody SearchCriteria search) {
AjaxResponseBody result = new AjaxResponseBody();
//logic
return result;
}
}
you can use ajax to submit your request.

How to call controller method from jsp using ajax

I am using spring boot, maven 3.2.5.
I am working on simple maven webapp using spring boot following mvc pattern.
i am trying to call controller method from jsp suing ajax.
this is my jsp javascript method look like , which call the ajax call to call the controller method.
function listExistingUser()
{
alert("listExistingUser");
$.ajax({
type : "GET",
url : '${home}/loginController/listExistingUser',
dataType : "json",
crossDomain:true,
success : function(data) {
//console.log(data);
//alert(data.toString());
checkValidUser(data);
},
error : function(data) {
}
});
}
Bellow is my controller class.
#Controller
#RequestMapping("/loginController")
public class LoginController {
#Autowired
LoginService loginService;
#RequestMapping(value = "/listExistingUser", method = RequestMethod.GET)
#ResponseBody
public Object getAuthentication(#ModelAttribute("studentId") int studentId,
HttpServletRequest request, HttpServletResponse response)
{
System.out.println("listExistingUser is called in controller");
}
}
when I run my application, I am able to access login.jsp from the bellow url
http://localhost:9090/seperation-management/pages/login.jsp
when i hit submit button my jsp page javascript method is also getting called that is alert("listExistingUser");
but i am not able to called my controller method.
where I am making mistake. can anyone help me.
there's some changes to be made in the contoller method
#RequestMapping(value = "/listExistingUser", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Object> getAuthentication(){
System.out.println("listExistingUser is called in controller");
return new ResponseEntity<Object>(object,HttpStatus.OK);
}
you dont need to have #modelAttribute annotation since you are not binding any object with the request. and it is a good practise to return ResponseEntity instead of returning an Object.
if you need to get an id from an incoming request
like this siteName/listExistingUser/1 then use this method.
#RequestMapping(value = "/listExistingUser/{id}", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Object> getAuthentication(#PathVariable("id") int id){}
if you want to get values from a url like this
siteName/listExistingUser?id=1 then use this method instead.
#RequestMapping(value = "/listExistingUser", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Object> getAuthentication(#RequestParam("id") int id){}
This example is working in my Application:
JSP:
<script type="text/javascript" charset="utf-8">
function getDesc() {
$.getJSON("desclist.json", {
sel1Id : $('select#COMPSNT_NM').val()
}, function(data) {
var html = '';
var len = data.length;
for (var i = 0; i < len; i++) {
html += '<option value="' + data[i] + '">'
+ data[i] + '</option>';
}
$('select#COMPSNT_DS').html(html);
});
}
$(document).ready(function() {
$('#COMPSNT_NM').change(function() {
getDesc();
});
});
</script>
Controller:
#RequestMapping(value = "desclist.json")
#ResponseStatus(HttpStatus.OK)
public #ResponseBody List<String> sectionList(#RequestParam(value = "sel1Id", required = true) String sel1Id,
ModelMap modelMap) {
List<PARAM_SEQ_2> list = new ArrayList<>();
List<String> list2 = new ArrayList<>();
list = paramSeq2Service.findByField2(sel1Id);
for (PARAM_SEQ_2 prm : list) {
list2.add(prm.getCOMPSNT_DS());
}
return list2;
}

Forwarding or Redirecting to a #ResponseBody method with GET/POST

Just written some code for redirecting and forwarding from one action to another action in spring mvc.Also done some permutations with GET and POST.
My question is how things work when we redirect/forward from one action with #RequestMapping to another action having #RequestMapping and #ResponseBody.
Below is the code snippet for controller and jsp with ajax script.Comments are mentioned on the methods which are not working with response error.
#Controller
#RequestMapping(value = "/myMvc")
public class MyMvcController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Model map, HttpServletRequest req) {
return "home";
}
#RequestMapping(value = "/action1", method = RequestMethod.POST)
public #ResponseBody String action1(Model map, HttpServletRequest req) {
return "Sending response body as POST";
}
#RequestMapping(value = "/action2", method = RequestMethod.GET)
public #ResponseBody String action2(Model map, HttpServletRequest req) {
return "sending response body as GET";
}
/*****action3 to action6 Redirect******/
//POST to GET
#RequestMapping(value = "/action3", method = RequestMethod.POST)
public String action3(Model map, HttpServletRequest req) {
return "redirect:/myMvc/action2";
}
//POST to POST
#RequestMapping(value = "/action4", method = RequestMethod.POST)
public String action4(Model map, HttpServletRequest req) {
//will not execute
//Request method 'GET' not supported
return "redirect:/myMvc/action1";
}
//GET to POST
#RequestMapping(value = "/action5", method = RequestMethod.GET)
public String action5(Model map, HttpServletRequest req) {
//will not execute
//Request method 'GET' not supported
return "redirect:/myMvc/action1";
}
//GET to GET
#RequestMapping(value = "/action6", method = RequestMethod.GET)
public String action6(Model map, HttpServletRequest req) {
return "redirect:/myMvc/action2";
}
/*****action7 to action10 Forward******/
//POST to GET
#RequestMapping(value = "/action7", method = RequestMethod.POST)
public String action7(Model map, HttpServletRequest req) {
//will not execute
//Request method 'POST' not supported
return "forward:/myMvc/action2";
}
//POST to POST
#RequestMapping(value = "/action8", method = RequestMethod.POST)
public String action8(Model map, HttpServletRequest req) {
return "forward:/myMvc/action1";
}
//GET to POST
#RequestMapping(value = "/action9", method = RequestMethod.GET)
public String action9(Model map, HttpServletRequest req) {
//will not execute
//Request method 'GET' not supported
return "forward:/myMvc/action1";
}
//GET to GET
#RequestMapping(value = "/action10", method = RequestMethod.GET)
public String action10(Model map, HttpServletRequest req) {
return "forward:/myMvc/action2";
}
}
home.jsp file
<button onclick="hitAction3()">hit action3</button><br><br>
<button onclick="hitAction4()">hit action4</button><br><br>
<button onclick="hitAction5()">hit action5</button><br><br>
<button onclick="hitAction6()">hit action6</button><br><br>
<button onclick="hitAction7()">hit action7</button><br><br>
<button onclick="hitAction8()">hit action8</button><br><br>
<button onclick="hitAction9()">hit action9</button><br><br>
<button onclick="hitAction10()">hit action10</button><br><br>
<script>
function hitAction3() {
$.ajax({
method:'POST',
url: "${pageContext.request.contextPath}/myMvc/action3",
}).done(function(data) {alert(data);});
}
function hitAction4() {
$.ajax({
method:'POST',
url: "${pageContext.request.contextPath}/myMvc/action4",
}).done(function(data) {alert(data);});
}
function hitAction5() {
$.ajax({
method:'GET',
url: "${pageContext.request.contextPath}/myMvc/action5",
}).done(function(data) {alert(data);});
}
function hitAction6() {
$.ajax({
method:'GET',
url: "${pageContext.request.contextPath}/myMvc/action6",
}).done(function(data) {alert(data);});
}
function hitAction7() {
$.ajax({
method:'POST',
url: "${pageContext.request.contextPath}/myMvc/action7",
}).done(function(data) {alert(data);});
}
function hitAction8() {
$.ajax({
method:'POST',
url: "${pageContext.request.contextPath}/myMvc/action8",
}).done(function(data) {alert(data);});
}
function hitAction9() {
$.ajax({
method:'GET',
url: "${pageContext.request.contextPath}/myMvc/action9",
}).done(function(data) {alert(data);});
}
function hitAction10() {
$.ajax({
method:'GET',
url: "${pageContext.request.contextPath}/myMvc/action10",
}).done(function(data) {alert(data);});
}
</script>
What I already know is :
In Redirect :A new request object is created.
In Forward :Same request object is forwarded to next action.
Please share some rules or information regarding this if I am missing.
A redirect will send an HTTP 302 response to the client with a Location header, so the client will perform a GET in any case.
If you want your "POST to POST" case to work, use a forward prefix.
Check out this SO question for more details on forward vs. redirect.

Post two array as json through ajax to Spring Controller

My ajax method
$.ajax(
{
type: "POST",
contentType: 'application/json;charset=utf-8',
dataType:'json',
url: 'addrequisition',
data: JSON.stringify([{ ids: val, qty: valtxt }]),
success: function(result)
{
$("#result").html(result);
}
});
});
and my arrays are val and valtxt.
I want to read those arrays in a Spring Controller help me :)
First, you need to define a class in java like this:
class MyClass{
private String ids;
private String qty;
//Setters and Getters
}
Note that the members of class MUST be same as json data.
then in your controller you need to define action like this:
#RequestMapping(value = "/addrequisition", method = RequestMethod.POST)
public String addrequisition(#RequestBody MyClass myClass) {
String result = myClass.getIds() + myClass.getQty();
return result;
}

Resources