Issue
I Want To Send Data From Html Web Page to My Server Using Servlet.
<form method="post" name="customerForum" action="addCustomer">
<button class="btn btn-success" id="addCustomerBTN"
type="submit" value="addCustomer">Add Customer
</button>
</form>
This Is My Servlet Class
@WebServlet(urlPatterns = "/addCustomer")
public class PSystemServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String customerID = req.getParameter("custID");
String customerName = req.getParameter("custName");
}
}
If I Press The Button WebPage Redirect To My Servlet Class (using this urlPatterns = "/addCustomer"). But I Need to Send Data From the HTML webpage To My Servlet Class But I Do Not Need to Redirect To Servlet Class.
How Can I Stop Redirect Servlet Class and Send My Data To Servlet Class Without Redirecting..?
Solution
Before Jumping into the solution,You should know AJAX,How it works
Try This: Client Side:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<body>
<form method="post" name="customerForum">
CID: <input type="text" id="custID" name="custID">
CNAME:<input type="text" id="custName" name="custName">
<button class="btn btn-success" id="addCustomerBTN"
type="button" value="addCustomer" onclick="register()">Add Customer
</button>
</form>
</body>
<script>
function register()
{
var custName = document.getElementById('custID').value;
var custID = document.getElementById('custName').value;
$.ajax({
type: "GET",
url: "addCustomer",
data: {custID: custID, custName: custName},
success: function (status) {
alert(status);//You can add if codition to check status values and alert msg accordingly if 'inserted' then alert data inserted sucessfully
}
});
}
</script>
</html>
Server Side(addCustomer Servlet):
String status="notInserted";
String customerID = request.getParameter("custID");
String customerName = request.getParameter("custName");
System.out.println("custID:" + customerID);
//Your insert Logic
//if data inserted sucessfully set status="inserted";
status="inserted";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(status);
Answered By - naveen4181