I am sending a json object via ajax call.
When I try to print the json's values I am getting nulls.
What am I doing wrong?
Servlet:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"PARENT\":\"2\",\"VAL\":\"X7280\"},{\"PARENT\":\"2\",\"VAL\":\"X8338\"}]");
}
javascript:
function handleIt() {
var url = "myservlet";
var parameters = "method=method";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
var ddl3 = http.responseText;
for(var key in ddl3){
var id = ddl3[key].PARENT;
var lbl = ddl3[key].VAL;
alert (lbl);
}
}
}
http.send(parameters);
}
Related
Here I deployed the Get request with Id to pass from the client-side to the server-side to download excel file according to the Id.
client-side js file
$scope.getAUGFile = function () {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var params = JSON.stringify({ articleId: articleId });
var url = RESOURCES.USERS_DOMAIN + '/AUGFile/excelDownload/'
xhr.open("GET", url+"?"+params);
xhr.setRequestHeader("authorization", getJwtToken());
xhr.responseType = 'blob';
xhr.onload = function () {
if (this.status === 200) {
saveAs(xhr.response, "mvvAUGExcelTemplate.xls");
}
};
xhr.send(null);
};
server-side js file(spring boot)
#RequestMapping(value = "/AUGFile/excelDownload/{articleId}", method = RequestMethod.GET)
public ResponseWrapper excelGenerateAUG(HttpServletRequest request, HttpServletResponse response,#PathVariable Long articleId){
try{
fileService.downloadAUGFile(request,response,articleId);
return ResponseWrapper.successWithMessage(messageSource.getMessage("success_code",null, Locale.ENGLISH));
} catch (Exception e){
lOG.error(">> Excel file Download error", e);
return ResponseWrapper.failWithMessage(messageSource.getMessage("fail_code", null, Locale.ENGLISH));
}
}
When I execute the client-side function, In the serverside take the articleId value as NULL. How can I fix it? Any advice, help, pointers welcome!
first
console.log(articleId) inside your function to see if its defined and accessible to xhr to send
& try this this instead xhr.open("GET", url+articleId);
or try this
xhr.open("GET", url+"?articleId="+articleId);
I got the correct way of this! It is working now.
client-side js file
$scope.getAUGFile = function () {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var url = RESOURCES.USERS_DOMAIN + "/AUGFile/excelDownload/"+articleId;
xhr.open("GET", url);
xhr.setRequestHeader("authorization", getJwtToken());
xhr.responseType = 'blob';
xhr.onload = function () {
if (this.status === 200) {
saveAs(xhr.response, "mvvAUGExcelTemplate.xls");
}
};
xhr.send(null);
};
server-side js file
#RequestMapping(value = "/AUGFile/excelDownload/{articleId}", method = RequestMethod.GET)
public ResponseWrapper excelGenerateAUG(HttpServletRequest request, HttpServletResponse response,#PathVariable("articleId") String articleId){
try{
fileService.downloadAUGFile(request,response,articleId);
return ResponseWrapper.successWithMessage(messageSource.getMessage("success_code",null, Locale.ENGLISH));
} catch (Exception e){
lOG.error(">> Excel file Download error", e);
return ResponseWrapper.failWithMessage(messageSource.getMessage("fail_code", null, Locale.ENGLISH));
}
}
I am trying to add parameter and redirect to a page that only accepts request in post method. I am using this code in my servlet and it is not forwarding me to the url.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "http://www.thisone.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("User", "xyz");
method.addParameter("Name", "abc");
int statusCode = client.executeMethod(method);
System.out.println(statusCode);
if (statusCode != -1) {
response.sendRedirect(response.encodeRedirectURL(url));
in = method.getResponseBodyAsStream();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I don't think it's possible to redirect with post method using this approach. what you can do is get the response to the client and therefore set the location header in response. Implementation for the same is given below:
Once your condition is satisfied:
response.setStatus(307);
response.addHeader("Location", "<url>");
also check out the significance of 307 status code.
Here is the javascript code, which starts with an ajax request and hit a servlet to fetch the desired URL, once it receives the URL, creates a HTML form object, sets values and submits the form...
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callURL(this.responseText);
}
};
xhttp.open("GET", "TestServlet", true);
xhttp.send();
function callURL(url){
var form = document.createElement("form");
form.setAttribute('method', 'POST');
form.setAttribute('action', url);
form.setAttribute('id', 'frmProduct');
form.style.display = 'none';
var i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'name');
i.setAttribute('value', 'Neeraj');
form.appendChild(i);
document.getElementsByTagName('body')[0].appendChild(form);
form.submit();
}
</script>
Below is the implementation of my Testservlet
#WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "http://www.thisone.com";
PrintWriter out = response.getWriter();
out.print(url);
}
}
You can make use of automatic form submit using POST method to do the same.
Please find below sample code:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
private void sendPOSTRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
String postURL = "url to send data";
String value1 = "value for name1";
String value2 = "value for name2";
String content = "<html><body onload='document.forms[0].submit()'><form action=\"" + postURL + "\" method=\"POST\">"
+ "<INPUT TYPE=\"hidden\" NAME=\"name1\" VALUE=\"" + value1 + "\"/>"
+ "<INPUT TYPE=\"hidden\" NAME=\"name2\" VALUE=\"" + value2 + "\"/>"
+ "</form></body></html>";
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.write(content);
}
I have a jsp file with google map, place autocomplete and few buttons. The submit Button click calls a method in Javascript which inturn passes the jsp page 'input' data to callServlet() method as 'params'. I want to call a servlet page MyServlet and pass the params to it. However my callServlet() executes perfectly but doesn't pass on the control/params to MyServlet.
Also How to read params in MyServlet?
Please help me solve it.
JS code:
function callServlet(params) {
var xmlhttp = new XMLHttpRequest();
var url = "./mapServlet";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
console.log(url);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
console.log("Its perfect");
} else {
alert(xmlhttp.status);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
// params is of json format with key value pairs
xmlhttp.send(params);
}
Servlet code: (Made no changes to this page. Its a simple servlet template)
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.print("aaas");
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
web.xml
<servlet>
<servlet-name>mapServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mapServlet</servlet-name>
<url-pattern>/mapServlet</url-pattern>
</servlet-mapping>
Is there a specific reason you're not using jQuery for that?
Basically, xmlhttp.send(params) expects to receive key=value string, not a Json. If you intend to use bare XMLHttpRequest, you'll need to create this string on your own.
Also, this mapping: var url = "./mapServlet"; may be wrong, as usually you serve code from root, and your JS files are served from resource directory such as /js. Using `var url = "/mapServlet" would be better.
Finally, after you reach your servlet, you can read your parameters using request.getParameter("parameter_name")
To call your server using jQuery start with using jQuery.post() method:
https://api.jquery.com/jquery.post/
$.post( "./mapServlet", params)
.done(function( data ) {
console.log("Got ", data);
});
I have a JSP page which I use to submit some data to a HTTPServelet. I need to show an alert after successfully completing task in servlet so I have a JavaScript AJAX function which executes in onSubmit event of JSP Page. but when I click submit button AJAX function does not execute with it.
Here is my Javascript function:
function alerts(servlet) {
var xhr = new XMLHttpRequest();
xhr.open("POST", servlet, true);
console.log("connected to "+servlet);
xhr.send(null);
xhr.onreadystatechange = function() { //this function does not execute
if (xhr.readyState === 4) {
if (xhr.status === 200) {
content = xhr.responseText;
var objects = JSON.parse(content);
console.log(objects);
var elemant = document.getElementById("tblObjects");
var child = elemant.children;
var childLength = child.length;
if (0 < child.length) {
for (i = 0; i < childLength; i++) {
deleteElamant("tblObj");
}
}
}
}
};
}
And my Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
//Do somethings inside Servlet
response.getWriter().write("my alert messege to JavaScript");
RequestDispatcher rd = request.getRequestDispatcher("/NextServlet");
rd.forward(request, response);
} catch (Exception ex) {
}
}
When I try to call Jena using AJAX in my servlet I get this error:
java.lang.ClassNotFoundException: com.hp.hpl.jena.sparql.core.Prologue
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
at fr.objective.blogomatic.semantic.web.ServletAjax.doGet(ServletAjax.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
This is my Jena code:
class classUsingJena {
public void execute(){
String queryString = PREFIXES
+ " Select ?label "
+ " where {"
+ " ?description j.5:entity-label ?label ." + " } ";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out,results, query);
qe.close();}
}
It's running fine, but when I call this function using servlet I get the error described previously.
This is my servlet code:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String service = req.getParameter("service");
classUsingJena jena= new classUsingJena() //bug
return;}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
#Override
public void init() throws ServletException {
ServletConfig config = getServletConfig();
urlAjax = config.getInitParameter("urlAjax");
}
My java script code that runs fine:
$("#Analyser").click(function(){
var article = $("#TxtArea").val();
ajaxFunction("acteur",article);
console.log(article);
});
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction(valeur,txt) {
if(xmlhttp) {
xmlhttp.open("GET","ajax?service=ajax&valeur="+valeur+"&text="+txt,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
$("#J").text("");
parseXml(xmlhttp.responseXML);
}
else {
//alert("Error during AJAX call. Please try again");
}
}
}
function parseXml(xml)
{
$(xml).find("nom").each(function()
{
$("#J").append($(this).text() + "<br />");
});
}
In the pom I had declared the old version of Arq 1.8.7 instead of 2.8.7. Now it's running fine.