how to get servlet response message in javascript variable is there any possible way to get response message in java script?
Html:
<form method="post" id="importForm">
Name<input type="text" name="name"/>
<input type="submit" onclick="importScenarioFromServer();">
</form>
javascript:
function importScenarioFromServer(){
var result = document.forms["importForm"].submit();
}
servlet:
int numberOfRecs = db.setDBValue(dMap);
if (numberOfRecs == 1) {
String result = "success";
response.getWriter().print(result);
}
This can be implemented using ajax either in javascript or by using jquery.
we can serialise form in ajax hit and then can get response data from servlet in success event callback function. below is example...
function getData()
{
var client;
var data;
var url_action="/temp/getData";
if(window.XMLHttpRequest)
{
client=new XMLHttpRequest();
}
else
{
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function()
{
if (client.readyState==4 && client.status==200)
{
document.getElementById("response").innerHTML=client.responseText;
}
};
data="name="+document.getElementById("name").value+"&file="+document.getElementById("filname").value;
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(data);
}
Servlet post method
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
log.info("Good");
out.println("Good to go");
}
Related
I have controller method that handles “Download ” button click on my page. This method makes call to our Service, where query is made.
My problem is that it takes around 20-30 sec for Service to execute the query before it will be returned to controller and put to outputStream to return back to user. So user is blocked and cannot do anything for this 30 sec until actual download start.
How can I resolve this issue? I don’t want my user wait. I am new to spring mvc and async programming. So please, explain me how can I do it asynchronously ?
#RequestMapping(value = "/download")
public void downloadCSV(#RequestParam(“vendorId”), #RequestParam(“startDateString”),#RequestParam(“startDateString”),
HttpServletResponse response) throws IOException
{
List<Objects> listFromService = getListFromService();
String fileName = vendorId + "_metrics.csv";
response.setHeader("Content-disposition", "attachment;filename="+fileName);
ServletOutputStream outputStream = response.getOutputStream();
listFromService.stream().forEach(item -> {
try {
processListItem(item, outputStream);
} catch (IOException e) {
e.printStackTrace();
}
});
outputStream.flush();
}
You could use AJAX call from your view(JSP) to the controller as follows.
JSP Form:
<FORM NAME="form1" METHOD="POST">
<INPUT TYPE="BUTTON" VALUE="Download" ONCLICK="downloadCSV()">
</FORM>
Ajax functions:
<script type="text/javascript">
function downloadCSV() {
console.log("Download called..");
$.ajax({
type : "GET",
url : '${home}/download',
dataType : "json",
crossDomain : true,
success : function(data) {
processResponse(data);
},
error : function(data) {
}
});
}
function processResponse() {
console.log("Your response processing goes here..");
}
</script>
I want make simle jersey form example. i have login form , servlet andweb service. in servlet - post request data in json. web service control login and password and return OK or UNAUTORIZED as a Response.
Login page
<form method="POST" action="login">
Login <input type="text" name="login"/>
Password <input type="password" name="password"/>
<input type="submit" value="enter"/>
</form>
Login servlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
name = request.getParameter("login");
password = request.getParameter("password");
isUser(name, password);
}
public void isLogin(String log, String pass) {
Client cl = Client.create();
String json = "{\"login:\""+"\""+log+"\",\"password\":"+"\""+pass+"\"}";
JSONObject obj = new JSONObject(json);
WebResource wr = cl.resource("http://mywebservice/login");
ClientResponse clr = wr.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,obj.toString());
System.out.println(clr.getStatus() + " ---- ");
}
Service
#POST
#Path("/login")
#Consumes(MediaType.APPLICATION_JSON)
public Response isUser(String login) {
//return super.find(id);
JSONObject pb = new JSONObject(login);
if (pb.get("login").equals("admin")) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
But don't work.Always return status 500.Where is my mistakes
Try this..
if (((String)pb.get("login")).equals("admin")) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
OR (any of these two as per your convenience) .
if (pb.getString("login").equals("admin")) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
Instead of
if (pb.get("login").equals("admin")) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
Reason :- get("") function of JSONObject returns Object Class Object so, equals() will belongs to Object Class not to the String Class. So, Change your Code re-Compile the code and see the difference.
Another Change what you should do to your method is add a #RequestBody to your Parameter. Probably it will resolve.
public Response isUser(#RequestBody String login);
Thanks :)
i am trying to get response from servlet page and displaying alert on success. but its show me error always. i am not able to figure it out.
My ajax code:
$(document).ready(function() {
$("#srch").click(function() {
var txt1 = $("#store-qsearch").val();
alert(txt1)
$.ajax({
url : 'http://localhost:8080/searchengine/SearchDataServlet',
data : 'val='+txt1,
type : 'GET',
success : function(response) {
alert("Success");
// create an empty div in your page with some id
},
error: function(){ alert("error");
}
});
});
});
My servlet code:
public class SerachDataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String searchkey = request.getParameter("val").toString();
SearchInput searchinput = new SearchInput();
searchinput.searchkeys = searchkey;
System.out.println(searchkey);
SearchParser searchparser = new SearchParser();
searchparser.searchData(searchkey);
PrintWriter output = response.getWriter();
output.println("successs");
}
}
change this line data : 'val='+txt1, to data: { val: txt1},
see this for example
I am very new to ajax concept,I want to submit a form without refresh the page
ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Listservlet",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.fname.message.innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
JSP
<form name="fname" action="Listservlet" method="post">
<input type="text" name="txtname" id="txtname" />
<input type="button" value="Submit" onclick="ajaxFunction();" />
<div id="message"></div>
</form>
servlet
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
String name = null;
PrintWriter out = response.getWriter();
if(request.getParameter("txtname") != null) {
name = request.getParameter("txtname");
}
else {
name = "";
}
out.println("You have successfully made Ajax Call:" + name);
}
This ajax idea I got from google, bt it is not working,
While clicking on the button,nothing it showing.
Please help me.
replace
document.fname.message.innerHTML=xmlhttp.responseText;
by
document.getElementById("message").innerHTML=xmlhttp.responseText;
General Steps to find out where goes wrong:
use browser debugger to tell if ajax request was successfully sent;
debug your receiving Servlet, to tell if request was actually delivered to your Servlet;
use browser debugger to tell if the response text is desired one;
for your issue I think you need to
change
document.fname.message.innerHTML=xmlhttp.responseText;
to
document.getElementById("message").innerHTML = xmlhttp.responseText;
Also remember Close your ouputstream
I have an Ajax request coming from client side after a key press. The servlet returns a string.
How should I grab this string on the client side? It should be split on "," on the client side and display the list. We are using Velocity for rendering the HTML.
Servlet code:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String acInfo = request.getQueryString();
SomeDAO dao = new SomeDAO();
ArrayList<String> results = dao.acResults(acInfo);
StringBuilder sb = new StringBuilder();
int count = 0;
for (String acResult : results) {
sb.append(acResult);
count++;
if (count == results.size()) {
break;
}
sb.append(',');
}
out.println(sb);
out.close();
}
Dont use "async: false" or it will lose all the AJAX meaning.
Do all the stuff you want in the success method. To split by ',', just use split() and to easily iterate arrays use $.each()
$.ajax({ type: "GET",
url: "/YourServletURL",
success : function(text)
{
var list = text.split(',');
$.each(list, function(index, value) {
alert(index + ': ' + value);
});
// This will show the values. Change "alert" for $('div#mydiv').html(value) or so
}
});
If you are not using Jquery then you can use following:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","YOUR_SERVLET_RELATIVE_URL",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
Sounds like a simple jQuery ajax response scenario - can't you handle the response with code of following nature ?
var responseText = '';
$.ajax({ type: "GET",
url: "/YourServletURL",
success : function(text)
{
responseText = text;
}
});
//alert response or process it or display somewhere
alert(responseText);