0

As an extension to my previous post (unable to get the passed data from servlet), here is my original question.

In regular JSP/Servlet MVC communication, we use requestdispatcher to send data from a servlet response to next jsp. Below is my current code.

Index.jsp

<%@ 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>Insert title here</title>
</head>
<body>
    <form name="form1" id="name1" method="post" action="GetData">
        <input type="text" id="name" name="name" /> <input type="text"
            id="number" name="number" /> <input type="submit" />
    </form>
</body>
</html>

Index1.jsp

<%@ 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>Insert title here</title>
</head>
<body>
    <input id="Name" name="Name" type="text"
        value="${userBeans[0].getName()}" />
    <input id="Number" name="Number" type="text"
        value="${userBeans[0].getNumber()}" />
</body>
</html>

UserBean

public class UserBean {
    private String name;
    private int number;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

GetData servlet

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GetData
 */
@WebServlet("/GetData")
public class GetData extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetData() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        GetDataDAO getdatadao = new GetDataDAO();

        List<UserBean> userBeans = null;
        try {
            userBeans = getdatadao.list();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        request.setAttribute("userBeans", userBeans);
        request.getRequestDispatcher("index1.jsp").forward(request, response);

    }

}

GetDATADAO

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class GetDataDAO {

    public List<UserBean> list() throws ClassNotFoundException, SQLException {
        ArrayList<UserBean> list = new ArrayList<UserBean>();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs;
        String queryString = null;
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String userName = "sa";
        String password = "T!ger123";
        String url = "jdbc:sqlserver://home\\SQLEXPRESS;DatabaseName=TEST";
        conn = DriverManager.getConnection(url, userName, password);
        System.out.println("Connecting to database…");
        System.out.println("Oracle JDBC Driver Registered!");
        if (conn != null) {
            System.out.println("You made it, take control your database now!");
        } else {
            System.out.println("Failed to make connection!");
        }
        stmt = conn.createStatement();
        queryString = "SELECT * from UserTable";
        rs = stmt.executeQuery(queryString);

        while (rs.next()) {
            UserBean userBean = new UserBean();
            userBean.setName(rs.getString("name"));
            userBean.setNumber(rs.getInt("number"));
            list.add(userBean);
        }

        return list;
    }

}

Basically in my program there is are 2 textboxes, once I click on the submit button, the data from database should be pulled and displayed in the textboxes in the second page(index1.jsp).

When i do my program in this manner everything is working fine. But when i use Jquery/AJAX, it is not passing the values to next page.

I've removed the action and method and changed the input type to button and assigned a ID. And below is my updated file(to use with Jquery/AJAX).

<form name="form1" id="name1">
        <input type="text" id="name" name="name" /> <input type="text"
            id="number" name="number" /> <input type="button" id="getCase" name="getCase"/>
<script type="text/javascript" src="indexJS.js"></script>
    </form>

And I've created a JS file as below and in my index page I've added the required jquery and ajax files (the web links).

$('#getCase').click(function() {
    $.ajax({
        type : 'post',
        url : 'GetData',
        success : function(data) {
            alert(data);
            console.log(data);
        },
    });
});

And when I run this program nothing is happening, but the data is printed in the console,the entire HTML file with the values in it.

Can someone please let me know how can i display the values in the next page text boxes?

Thanks

Community
  • 1
  • 1
user3872094
  • 3,269
  • 8
  • 33
  • 71
  • When you're submitting you'll receive the value from request, but through ajax you have to send parameter's. Like this `data: { name: $("#name").val(), number: $("#number").val()},` – Vinoth Krishnan Feb 23 '16 at 11:22

1 Answers1

0

Send Ajax request like this,

$('#getCase').click(function() {

  var name = $("#name").val();
  var number = $("#number").val();
  $.ajax({
    type : 'post',
    url : 'GetData',
    data: { name: name, number: number},
    success : function(data) {
        alert(data);
        console.log(data);
    },
  });
});

And in the servlet,

 protected void doGet(HttpServletRequest request, 
 HttpServletResponse response) throws ServletException, IOException {

    String userName = request.getParameter("name").trim();
    String number= request.getParameter("number").trim();

    String greetings = "Hello " + userName + "-"+ number;

    response.setContentType("text/plain");
    response.getWriter().write(greetings);
}

Now in your alert you'll get data. Hope this helps.

Vinoth Krishnan
  • 2,925
  • 6
  • 29
  • 34
  • Thanks for this. But how do I make these values popped up in the textboxes in index1.jsp? , will the statements `request.setAttribute("userBeans", userBeans);` and `request.getRequestDispatcher("index1.jsp").forward(request, response);` and here I've to get the data from DB and put it in the textboxes and initially, `$(#name).val()` and `$(#number.)val();` are null and they are fetched from DB and popped in the textboxes. – user3872094 Feb 23 '16 at 11:27
  • From you code, I understood that you're passing two values. But in your servelet you're not using those values. Simply taking the `List` instead. Can you explain this? – Vinoth Krishnan Feb 23 '16 at 11:31
  • `userBeans` is basically a list. How can you expect it will return the single value in your text box like this `${userBeans[0].getName()}` – Vinoth Krishnan Feb 23 '16 at 11:36
  • Here, I'm getting the name using the list.get value property Sir. The `list` combines both Name and number to make a list. And in each iteration, there is new bean present. – user3872094 Feb 23 '16 at 11:40
  • But you are not using the value(s) from `index.jsp` isn't it? How it will be appear in the next page? `HttpServletRequest request` is the request object in your servlet. I don't find anywhere you're fetching the values from your request. – Vinoth Krishnan Feb 23 '16 at 11:50
  • See [here](http://stackoverflow.com/questions/2148658/iterate-over-elements-of-list-and-map-using-jstl-cforeach-tag) and [here](http://stackoverflow.com/questions/2147495/accessing-java-based-dom-tree-directly-from-jsf-richfaces/2147716#2147716) to get idea for iterating the list using jstl. – Vinoth Krishnan Feb 23 '16 at 11:57
  • In Ajax you need to return the data. The same approach of submitting the page won't help. You need to return the response to same page (Since ajax is nothing but a javascript). Once you got the values in ajax response, set it in local/session storage of browser(works on all latest browser). So you can get it in `index1.jsp` page. – Vinoth Krishnan Feb 23 '16 at 12:08
  • Here index and index1, both are 2 identical pages, one without content, and the other to show the same with content. It is like this. You get into index.jsp, click the button, and the same page comes up, but this time with values(this is index1.jsp). And is it mandate using JSTL (Asking out of curiosity). – user3872094 Feb 23 '16 at 12:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/104285/discussion-between-vinoth-krishnan-and-user3872094). – Vinoth Krishnan Feb 23 '16 at 12:20