1

added the directory structure

I created a simple java servlet to add two numbers into textboxes and return the result when the submit button is clicked. which calls the javaservlets to fetch the result. I am using eclipse for the edit.

index.jsp code
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax Example in JSP And Servlet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $('#btn').click(function() {
  var number = $('#number').val();
  var number1=$('#number1').val();
  var datastr='number='+number+'&number1='+ number1;
  $.ajax({
   type:"post",
   url:"CalcAjax",
   data:datastr,
   success:function(msg)
   {
        $("p").append(response.d);
   }
  });
 });
});
</script>
</head>
<body>
<form id="form" method="post">
 Enter number1:
 <input id="number" type="text" name="number" />
 Enter number2:
 <input id="number1" type="text" name="number1" />
 <input id="btn" type="button" value="Calculate" name="btn"/>
</form>
<p></p>
</body>
</html>


CalcAjax.java code

    package com.ajax.servelets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CalcAjax
 */

public class CalcAjax extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        int number=0, number1=0;
        number=Integer.parseInt(request.getParameter("number"));
        number1=Integer.parseInt(request.getParameter("number1"));
        PrintWriter out=response.getWriter();
        out.println(number+number1);    
    }
}


web.xml code

    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd">
  <servlet>
    <servlet-name>CalcAjax</servlet-name>
    <servlet-class>com.ajax.servelets.CalcAjax</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>CalcAjax</servlet-name>
    <url-pattern>/CalcAjax</url-pattern>
  </servlet-mapping>
</web-app>
Sanjeev
  • 9,876
  • 2
  • 22
  • 33
WakeUpSid
  • 33
  • 6

2 Answers2

2

After carefully re-visiting your whole code, it was a tiny mistake in your code.

Everything in your code is working perfectly fine just the displaying part wrongly shows result

So this:

$("p").append(response.d);

Needs to be replaced by

$("p").html("");
$("p").append(msg);

As the response of ajax call is coming into msg

Hope this resolves your concern.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
  • tried http://localhost:8080/HowToAjaxJsp/com/ajax/servelets/CalcAjax" but didn't worked – WakeUpSid May 10 '16 at 12:49
  • 1
    You informed full package in the URL. It must be only http://:port//. In case that your .WAR is called HowToAjaxJsp.war so you will have: http://localhost:8080/HowToAjaxJsp/CalcAjax – fhofmann May 10 '16 at 13:20
  • Please add your deployment details to the question ie. which server you are using, either you are deploying war/ear/exploded directory etc. – Sanjeev May 11 '16 at 06:35
  • I am new to this field. But when i see in eclipse under window->prefernces->server->runtime environment i see J2EEE Preview. I also edited my post and added the directory structure. Can u look at that. I am using a red hat system. – WakeUpSid May 11 '16 at 06:47
  • i believe you are deploying it in exploded form so try `localhost:8080/WebContent/CalcAjax` – Sanjeev May 11 '16 at 06:49
  • By the way how did you opened your index.jsp ? whats the full path in address bar of your browser? – Sanjeev May 11 '16 at 06:54
  • When i run the HowToAjaxJsp in eclipse using right-click->runas in server I got the path http://localhost:8080/HowToAjaxJsp/ in the browser and for index.jsp i got the path http://localhost:8080/HowToAjaxJsp/index.jsp – WakeUpSid May 11 '16 at 07:06
  • try in your browser `localhost:8080/HowToAjaxJsp/CalcAjax` – Sanjeev May 11 '16 at 07:10
  • Its giving out :HTTP ERROR 404 Problem accessing /HowToAjaxJsp/CalcAjax. Reason: Not Found – WakeUpSid May 11 '16 at 07:12
  • Perhaps look at my directory structure in the top of the page (just posted) U may able to identify the problem – WakeUpSid May 11 '16 at 07:14
  • Thanks dude for giving your precious time. It Worked. :) . Happy Time . – WakeUpSid May 11 '16 at 08:56
0

Try this,

$.post("CalcAjax",
{
    "number": "number",
    "number1": "number1"
},
function(data, status){
    $("p").append("Data: " + data + " Status: " + status);
});

instead of $.ajax() method, and in your servlet before,

PrintWriter out=response.getWriter();

add

response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");

hope this will work

Fahad
  • 346
  • 2
  • 16