2

I have a database with houses, and HTML page with <SELECT>, where user need to select a district where the houses are located.

Servlet:

   @WebServlet("/post")
   public class HosesBaseServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
          //choice from html form
        String choice = request.getParameter("district");

        //Database parameters
         final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb2";
         final String DB_USER = "root";
         final String DB_PASSWORD = "root";
         Connection conn;
        try {
            conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
            System.out.println("Connection available");
            PreparedStatement ps = conn.prepareStatement("SELECT Square, RoomNumbers, Price FROM houses  WHERE  District = " + choice);

        }catch (SQLException ex) {
            System.out.println("Fail to connect with base");
        }
    }
}

How can I put SQL select results into HTML page and give it back to client?

I created class House

public class Hosue implements Serializable {
    private String price;
    private String square;
    private String RoomNumbers;
    public String getPrice() {
        return price;
    }
    public String getSquare() {
        return square;}
    public String getRoomNumbers() {
        return RoomNumbers;}

    public void setPrice(String price) {
        this.price = price;
    }

    public void setSquare(String square) {
        this.square = square;
    }

    public void setRoomNumbers(String roomNumbers) {
        RoomNumbers = roomNumbers;
    }
}

and houses

public class Houses {
public List<House> getList() {

}
}

and add script to my html. What next, how to add information from select to this list?

user202822
  • 99
  • 1
  • 1
  • 9

3 Answers3

0

Add result of your query to some List or custom object and set it as attribute in your request object.

request.setAttribute("result", result);

and then forward to your next page using RequestDispatcher.

Jeet
  • 248
  • 1
  • 8
0

You can solve your problem as said by Jeed in the previous answer. However, it would be better if you model your db entities with Java objects and use them to encapsulate information from and towards the db. You may also use the DAO programming pattern to better organize your code, thus you can define simple objects (beans) to model data (your database entities) and data access object (DAO object) in which you would encode interaction with the db (your jdbc code). Then you will have something like this to query your db (this code will be in your servlet):

HouseDAO h=new HouseDAO(db connection param...)
ArrayList<House> list=h.selectHouses();

In the HouseDAO object you will create a method selectHouse in which you will basically move the jdbc code you have in your servlet right now. By the way, your are missing a part in which you call the method execute query from the ps object. This method returns a ResultSet object which contains the query result.

With the code above, you will have your data in the ArrayList list, and you can use the code suggested by Jeed to output it.

Clearly, if you want to avoid using jsp, you can print your html code directly in your servlet. I do not recommend this as you would merge view details with control and model code. This is not good especially if you are planning to change your view in the future.

NoAnOld
  • 171
  • 6
0

Use Gson external Library for sending java-List into String form to HTML,

Your Servlet Code looks likewise,

List<House> listofHouses = getList from Database;
Gson gson = new Gson();
String json_obj = gson.toJson(listofHouses);
response.getWriter().println(json_obj);

Your HTML(use Jquery-ajax for Handling result & send Request to Servlet ) Code looks some what nearer likewise......

<script>
    $.ajax({
            url: 'Servlet.do?distinct=YOUR_SELECTED_district_NAME',
            type: "POST/GET",
            data: query,
            dataType: 'application/json; charset=utf-8',
            success: function (data) {
            var returnedData = JSON.parse(data);    
                alert(data);

            $.each(data, function(index, value) {

         ('#your_drop_down_tag_id').append($('<option>').text(value).attr('value', index));
            });

            }
        });

</script>

NOTE: jquery-XXX.js file must be inclue into your project and into your html file properly.

Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55