简体   繁体   中英

Access java <List> from from jsp / jstl MVC app

I have been finding it difficult to understand where I am going wrong. I understand that we should move with the times but I am not sure how to replace a scriptlet, that I can get to do the job, with the JSTL taglibrary functions.

I have a Model class called Ranges.class which contains a rangeName (String) and a startRange (BigDecimal) and an endRange (BigDecimal) value. I have a DAO class that handles all the db queries (crud type methods). I have a method in RangesDao.class called getAllRanges() which will get all the potential ranges from a mysql db and return a List. This will fetch all the Range objects which include the rangeName, startRange and endRange.

Q: So basically what I want to do is from my jsp page when a text input is selected I want to check if it is between the start and end value of each Range object (that was returned in the List) and when I have a match I want to update a different text input with that objects rangeName value.

This is what I have so far.

Range.class

package za.co.zs6erb.model;
import java.math.BigDecimal;

public class Range {

    private int range_id;
    private String rangeName;
    private BigDecimal startRange;
    private BigDecimal endRange;

    //...getters and setters for each of the above variables ...

    @Override
    public String toString() {
        return "Ranges [range_id=" + range_id + ", Range Name=" + rangeName + ", Start Range=" + startRange  
        + ", End Range=" + endRangeBand + "]";
    } 
}

DAO Class: This is the getAllRanges() method

public List<Range> getAllRanges() {
    List<Range> rangeList = new ArrayList<Range>();
    try {
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("select * from ranges order by range_id");
        while (rs.next()) {
            Range lRange = new Range();
            lRange.setID(rs.getInt("range_id"));
            lRange.setRangeName(rs.getString("rangeName"));
            lRange.setStartRange(rs.getBigDecimal("start_range"));
            lRange.setEndRange(rs.getBigDecimal("end_range"));
            rangeList.add(lRange);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return rangeList;
}

Controller: This class has a doGet() and a doPost() method the piece I am busy with is the doGet(). The doPost() is used when adding a "plannedRoute" object (just an object that has several other attributes that need to be added to a different table. - not the issue here) From the doGet() I list all the "plannedRoute" objects which all have one Range associated with each. When adding a new route I launch a jsp page from the doGet() method. The following part should make things a little clearer.

doGet():

private static String LIST_PLANNEDROUTES = "plannedroutes.jsp";
private RangeDao rDao;    

//Constructor
public PlannedRouteController() {
    super();
    rDao = new RangeDao();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String forward = "";
    String action = request.getParameter("action");

    if (action.equalsIgnoreCase("new")) {
        forward = LIST_PLANNEDROUTES;
        request.setAttribute("rd", rDao);
    }
    RequestDispatcher view = request.getRequestDispatcher(forward);
    view.forward(request, response);
}

So now we have the crux of the issue ... plannedRoutes.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>MyTest</title>
        <script src="sj/jquery.js"></script>
        <script type="text/javascript">
            //<!--
            $(document).ready(function(){
                $("#range").change(function() {

                alert("A Range was entered");

                <c:forEach var="entry" items="${rd}">
                    alert( "HERE>" + ${entry.rangeName});
                </c:forEach>

                document.getElementById("testName").value =  $("#range").val();
            });                
        });
        //-->
        </script>
    </HEAD>
    <BODY>
        <form method="POST" action='<form method="POST" action='ContactController' name="frmAddContact">' name="frmAddRoute">
            Range: <input type="text" id="range" name="range" />
            Name:  <input type="text" id="testName" name="testName" readonly />
        <!-- a whole bunch of other stuff here -->

        </form>
    </BODY>
</HTML>

Q: So when the value in the range input text field changes (I call the method in the tag and there I want to step through the List and match what was typed in to see if it falls between the start and end range of any of the Range Objects. When I find a match I want to be able to fetch the rangeName attribute of that object and add that to the testName input text area.

I hope this is clear enough. I have tried the without success and am not sure where to go from here without using scriptlets ... Any help would be appreciated.

Kind Regards Sean

First, you're putting the DAO object into the request, but in the jsp you want to access the list that the DAO method would return. Call the method in your controller and put the resulting list into the request.

request.setAttribute("rd", rDao.getAllRanges());

The rest all needs to be client-side code unless you want to change your design to use ajax. Try serializing the range list, in the controller, into a JSON string. Then in your jsp, you'll be giving javascript access to the data. Let's say you're using Gson to serialize in your servlet:

request.setAttribute("rd", new Gson().toJson(rDao.getAllRanges(), List.class));

So when you access ${rd} in the jsp, it will be a String in the following form:

[{"range_id":1,"rangeName":"Range 1", "startRange":10.0, "endRange":19.99},{"range_id":2,"rangeName":"Second Range", "startRange":18.75, "endRange":29.5}]


In the jsp, you set that as a javascript variable that can be accessed by your change function.

$("#range").change(function() {
    var rdArray = ${rd};

    alert("A Range was entered");

    var floatVal = parseFloat($("#range").val());
    var rangeFound = false;
    var rdSize = rdArray.length;
    var index = 0;
    while (index < rdSize && !rangeFound)
    {
        var rangeObject = rdArray[index++];
        if (floatVal >= rangeObject.startRange && floatVal <= rangeObject.endRange)
        {
            rangeFound = true;
            $('#testName').val(rangeObject.rangeName);
        }
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM