Hi sir,
I have written the following application for calling servlet from javascript. but servlet is not able to get request from javascript
package com.nt.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
// TODO Auto-generated constructor stub
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
resp.sendRedirect("hello-world.jsp");
resp.getOutputStream().print("Get Method-"+req.getParameter("uname"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
resp.getOutputStream().print("Post Method-"+req.getParameter("uname"));
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<title>Calling servlet from javascript
function callServlet(methodType)
{
document.getElementById("helloWorldForm").action="/ah";
document.getElementById("helloWorldForm").method = methodType;
document.getElementById("helloWorldForm").submit;
alert("hi");
/* var xhttp;
xhttp = new XMLHttpRequest();
xhttp.open(methodType, "ah", true);
xhttp.send();
} */
Name:
doGet
doPost
What I have tried:
Name: <input type="text" name="uname" width="20">
<button type="button" onclick="callServlet('get')">doGet</button>
<button type="button" onclick="callServlet('post')" >doPost</button>
</form>