Reputation:
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>
Upvotes: 1
Views: 1356
Reputation: 17731
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);
});
Upvotes: 1