简体   繁体   English

存取Java <List> 来自jsp / jstl MVC应用程序

[英]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. 我知道我们应该与时俱进,但是我不确定如何用JSTL taglibrary函数替换可以完成工作的scriptlet。

I have a Model class called Ranges.class which contains a rangeName (String) and a startRange (BigDecimal) and an endRange (BigDecimal) value. 我有一个名为Ranges.class的Model类,其中包含rangeName(字符串)和startRange(BigDecimal)和endRange(BigDecimal)值。 I have a DAO class that handles all the db queries (crud type methods). 我有一个DAO类,处理所有的数据库查询(crud类型的方法)。 I have a method in RangesDao.class called getAllRanges() which will get all the potential ranges from a mysql db and return a List. 我在RangesDao.class中有一个名为getAllRanges()的方法,该方法将从mysql数据库中获取所有可能的范围并返回一个List。 This will fetch all the Range objects which include the rangeName, startRange and endRange. 这将获取包括rangeName,startRange和endRange的所有Range对象。

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. 问: 所以基本上我想做的是从jsp页面中选择文本输入时,我要检查它是否在每个Range对象(在List中返回)的起始值和结束值之间以及是否有一个匹配我想使用该对象的rangeName值更新不同的文本输入。

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 DAO类:这是getAllRanges()方法

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(). 控制器:此类具有doGet()和doPost()方法,我正在忙的部分是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. 在添加“ plannedRoute”对象(只是一个具有其他几个属性的对象需要添加到另一个表中时,才使用doPost()。-这里不是问题)从doGet()中,我列出了所有“ plannedRoute”全部具有一个关联的对象。 When adding a new route I launch a jsp page from the doGet() method. 添加新路由时,我从doGet()方法启动一个jsp页面。 The following part should make things a little clearer. 以下部分应该使事情更清楚一些。

doGet(): 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 所以现在我们有了这个问题的症结所在…… 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. 问:因此,当范围输入文本字段中的值发生更改时(我在标记中调用该方法,然后我要遍历列表并匹配键入的内容,以查看其是否介于以下任意一项的开始和结束范围之间当找到匹配项时,我希望能够获取该对象的rangeName属性并将其添加到testName输入文本区域。

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. 我已经尝试了失败,并且不确定在不使用scriptlet的情况下该从哪里去...任何帮助将不胜感激。

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. 首先,将DAO对象放入请求中,但是在jsp中,您想访问DAO方法将返回的列表。 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. 其余的全部都是客户端代码,除非您想更改设计以使用ajax。 Try serializing the range list, in the controller, into a JSON string. 尝试将控制器中的范围列表序列化为JSON字符串。 Then in your jsp, you'll be giving javascript access to the data. 然后在您的jsp中,您将为javascript提供访问数据的权限。 Let's say you're using Gson to serialize in your servlet: 假设您使用Gson在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: 因此,当您在jsp中访问${rd}时,它将是以下形式的String:

[{"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. 在jsp中,将其设置为可以由您的change函数访问的javascript变量。

$("#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);
        }
    }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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