Listen to input field using a spring controller - spring-boot

Is it possible, in our controller, to get realtime input from a user writing in a html textfield? I know its possible to do via eg. jquery/js, but we are students and want a java'ish solution.

only using java is impossible because java need communication with the HTML page, you can perform that but you need to use java-script too. for example you can write a controller and call it using Ajax in a event java-script method like keyup.
#RestController
#RequestMapping("/info/")
public class Controller {
#RequestMapping(value="/get/",
method=RequestMethod.POST,
produces=MediaType.APPLICATION_JSON_VALUE,
consumes=MediaType.APPLICATION_JSON_VALUE)
public Map<String,Object> getInputData(#RequestBody Map<String, Object> data){
String inputData = data.get("inputValue").toString();
//TODO
return data;
}
}
from java-script build your Json response and call /info/get/ rest URL.
for example using axios.
axios.post('/info/get/', {
inputValue: 'your input form data'
})
.then(function (response) {
//todo
})
.catch(function (error) {
// if has errors
});
but otherwise can't be

Related

Redirection in ASP.NET MVC to a controller method after the post AJAX call

Present set up -
url: configMap.sitePath + "api/Quiz/" + quizResponse.quizId,
data: JSON.stringify(quizResponse),
success: function (data) {
// Display the data on UI
}
the above post is to a .NET api controller which returns quizResponse.
[ValidateModelState, HttpPost]
public HttpResponseMessage Post(int id, QuizResponse value)
Now as per a new requirement , Once the api has the response I should redirect to another page(a MVC controller and then view). How do I achieve this -
public ActionResult ScptResult()
{
return View();
}
I also thought of redirect after ajax success but not sure if its a correct way.
Also, How do I pass data to the scptresult controller method after post?
In the success function of your JQuery, redirect the page to your MVC page:
window.location = '{controller}/{action}/{quizid}';
Assuming you use the standard MVC routing, and assuming you change your ScptResult function to accept a parameter, so you can pass data to it.
public ActionResult ScptResult(int quizid)
{
return View();
}
Use in java-script after complete your work in success method or anywhere
window.location = '#Url.Action("ScptResult", "YourControllerName")';
I should warn, I'm not very familiar with ajax responses but hopefully this gets close.
API
[ValidateModelState, HttpPost]
public HttpResponseMessage Post(int id, QuizResponse value)
{
//Other stuff...
var redirect = string.Format(#"/controller/ScptResult/{0}", id);
return new HttpResponseMessage()
{
Content = new StringContent(redirect)
};
}
Javascript
url: configMap.sitePath + "api/Quiz/" + quizResponse.quizId,
data: JSON.stringify(quizResponse),
success: function (data) {
window.location = data;
}
Controller
// This follows the default route.
// "/{controller}/{action}/{id}" where id is optional.
// window.location = "/ControllerName/ScptResult/OtherData"
public ActionResult ScptResult(string id)
{
return View();
}

How to map Bootstrap Modal to Spring MVC controller

I have a form in Bootstrap Modal and I want my Spring MVC controller to listen that. My problem is that the modal doesn't generate href because it's inside current page so I can't map just the modal in my Spring MVC controller.
I need it, because I want to show errors from bindingresult object. How can I do this?
This is my modal: http://www.bootply.com/zerZIYpNAF Let's say it's located in index.jsp so imaginary path would be /index#myModal.jsp or something like that.
#RequestMapping(value="/send", method = RequestMethod.GET)
public String get(Dummybean bean){
return "??"; //index#myModal
}
#RequestMapping(value="/send", method = RequestMethod.POST)
public String post(#Valid #ModelAttribute("dummy") DummyBean bean, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "??"; //index#myModal
}
//do something
}
public class DummyBean{
#NotNull
private String name;
public String getName() {
return username;
}
public void setName(String name) {
this.name = name;
}
You can't directly call the bootstrap modal to pop up by using controller. There for you will not able to bind form with Spring. But you can Achieve it using Ajax. You have to use form like normal Html form without using spring tags.
function searchAjax() {
var data = {}
data["query"] = $("#query").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "${home}search/api/getSearchResult",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
This is an example ajax for you to get an idea. You have to HttpServletRequest to retrieve data from controller side. Above example is taken from http://www.mkyong.com/spring-mvc/spring-4-mvc-ajax-hello-world-example/
1) create new function just for validation
2) create js function using prefer to use jquery and send ajax request to function in step one.
3) depend on validation status will handle errors or send form completely.
please read this article it's fully answered your question
javacodegeeks.com

How To Pass formdata parameters into ASP.NET WebAPI without creating a record structure

I have data coming into my form that looks like the image below (sessionsId: 1367,1368).
I've create c# in my webapi controller that works as below. when I've tried ot just make use SessionIds as the parameter (or sessionIds) by saying something like PostChargeForSessions(string SessionIds) either null gets passed in or I get a 404.
What is the proper way to catch a form parameter like in my request without declaring a structure.
(the code below works, but I'm not happy with it)
public class ChargeForSessionRec
{
public string SessionIds { get; set; }
}
[HttpPost]
[ActionName("ChargeForSessions")]
public HttpResponseMessage PostChargeForSessions(ChargeForSessionRec rec)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new ShirtSizeReturn()
{
Success = true,
//Data = shirtSizeRecs
});
return response;
}
You can declare the action method like this.
public HttpResponseMessage Post(string[] sessionIds) { }
If you don't want to define a class, the above code is the way to go. Having said that, the above code will not work with the request body you have. It must be like this.
=1381&=1380

What I am supposed to return from a server-side method called by ajax?

I have the following jQuery script:
$(document).ready(function() {
$("#resendActivationEmailLink").bind("click", function(event) {
$.get($(this).attr("href"), function() {
$("#emailNotActivated").html("<span>not yet activated. email sent!</span>");
}, "html");
event.preventDefault();
});
});
Basically, when a user clicks a link the following server-side method is invoked:
#RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody
String resendActivationEmail(#PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
return "dummy";
}
and some business logic is executed on the server but there is no real outcome from the server to be used on the client/browser side apart from an ajax success or an ajax failure.
Now what I am really not sure about is what my server-side method is supposed to return!
Currently it just returns the string dummy but of course this is only temporary. Should I go for no return type (void) or null or something else??
Note that I can change the datatype parameter of the jQuery get method.
EDIT:
I have altered my server-side method as follows:
#RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET)
public #ResponseBody void resendActivationEmail(#PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
}
#ResponseBody is required because this is an ajax call.
There is no point in returning a dummy value in this case. If you are not doing anything with the return value, then you can just do something like this:
#RequestMapping(value="/resendActivationEmail/{token}", method=RequestMethod.GET)
#ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
public void resendActivationEmail(#PathVariable String token) {
preferencesService.resendActivationEmail(token);
}
There will be a 204 response code instead of a 200 but that should be fine.
I'm assuming you are returning JSON from the server (from your server code: produces = "application/json").
Since you don't care about what gets returned, i.e. you are not handling the return value in your callback function, after $.get, then you can just return "{}", or if you want to handle the response you can go with something like:
{ "success": true }
// or
{ "error": "Error messages here" }

ajax call from view to controller in Play framework

I am newbie to MVC and Play framework (Java). Instead of using Groovy for dynamic HTML, I made our own page with static HTML, I mean we haven't any Groovy expressions. Here, I have a controller "Customer", generates JSON object which has to be sent to an ajax call in view. I tried with render() method, seems I haven't used correctly. can you give me some idea to forward from here. thanks.
public static void customer(){
WordAPI objWordAPI=new WordAPI();
List<WordInfo> listObjWord= objWordAPI.MakeAPIObject(nSurveyId);
JSONSerializer modelSerializer=new JSONSerializer().exclude("NSpontanity","NWordRepresentativity","NWordValue","NWordFrequency","class").rootName("Words");
render("Application/wordcloud.html",modelSerializer.serialize(listObjWord));
}
and ajax call in view "wordcloud.html"
$.ajax({
url: "/customer",
dataType : 'json',
success: function (data) {
alert(data);
}
})
I believe this should work:
public static void customer(){
WordAPI objWordAPI=new WordAPI();
List<WordInfo> listObjWord= objWordAPI.MakeAPIObject(nSurveyId);
JSONSerializer modelSerializer=new JSONSerializer().exclude("NSpontanity","NWordRepresentativity","NWordValue","NWordFrequency","class").rootName("Words");
renderJSON(modelSerializer.serialize(listObjWord));
}
I've never used rootName before, I usually just do something more like this:
public static void refreshNotifications()
{
JSONSerializer notifySerializer = new JSONSerializer().include("message","notifyId","class").exclude("*");
List<Notification> notificationList = user.getNotifications();
renderJSON(notifySerializer.serialize(notificationList));
}
Side Note: With refreshNotifications I have a Security method I run before which verifies and populates the user object.

Resources