Java 在jsp中获取选定动态表行的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21662644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:55:27  来源:igfitidea点击:

get value of selected dynamic row of table in jsp

javajspdynamicradio-button

提问by Seema

i have a page in jsp where i am dynamically displaying records from the database in a table, with dynamic rows being generated. With every row, there is a radio button so that the user can select one row.

我在jsp中有一个页面,我在一个表中动态显示数据库中的记录,并生成动态行。每一行都有一个单选按钮,以便用户可以选择一行。

The code for page1.jsp is:

page1.jsp 的代码是:

<form action="page2.jsp" method="post">

<table>
<%
 try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb,        *.accdb)};DBQ=C:/Users/hp/Documents/Sample1.accdb";

Connection con = DriverManager.getConnection(database, "", ""); 
Statement stmnt = con.createStatement();

String source=request.getParameter("from");
String dest=request.getParameter("to")
ResultSet resultset = stmnt.executeQuery("select * from Trains123 where From='" +source+    "' and To='" +dest+ "' ");

     while(resultset.next())
     {          
         %>        

<tr>

<td><% out.println(resultset.getString("From")); %></td>
<td><% out.println(resultset.getString("To")); %></td>
<td><% out.println(resultset.getString("TrainName")); %></td>        


<td><input type="radio" name="TName" value="<%=    resultset.getString("TrainName")%>">book</td>
</tr>
</table>
</form>

and the code on page2.jsp is:

page2.jsp 上的代码是:

<% out.println(request.getParameter("Tname")); %>

There is no problem with the record set, the values are getting printed. but the radio button is not being displayed.Also, If there are 2 records in the recordset, only the first one gets printed without the radio button. I debugged the file, the control stops at the radio button line.

记录集没有问题,正在打印值。但是没有显示单选按钮。另外,如果记录集中有 2 个记录,则只有第一个被打印而没有单选按钮。我调试了文件,控件停在单选按钮行。

I have no idea, where the error is and what is the problem with giving dynamic value to the radio button. All i want to do is to find out the row selected by the user.

我不知道错误在哪里以及为单选按钮提供动态值有什么问题。我想要做的就是找出用户选择的行。

回答by Cromax

AFAIR JDBC specification does not give guarantee, that you can call getXxxon a result set with the same column name/number twice. Most of JDBC drivers do support it, but some might not I am not sure if ODBC is not probably this exception. So first try to get values of all columns in a row to extra variables like this:

AFAIR JDBC 规范不保证您可以getXxx两次调用具有相同列名/编号的结果集。大多数 JDBC 驱动程序确实支持它,但有些可能不支持我不确定 ODBC 是否可能不是这个例外。因此,首先尝试将一行中所有列的值获取到像这样的额外变量:

String from = resultset.getString("From");
String to = resultset.getString("To");
String trainName = resultset.getString("TrainName");

and use it in this way:

并以这种方式使用它:

<tr><td><%=form%></td>
    <td><%=to%></td>
    <td><%=trainName%></td>
    <td><input type="radio" name="TName" value="<%=trainName%>"/> book</td>
</tr>

Also please do escape these values, as if trainNamewould contain '"'character, you may break HTML code.

也请转义这些值,好像trainName包含'"'字符一样,您可能会破坏 HTML 代码。

But much more important is the way you wrote your code. First of all you should separate view layer (JSP) from the code. So you should create a class, that reads list of trains and simply put it into request, more or less like this:

但更重要的是你编写代码的方式。首先,您应该将视图层 (JSP) 与代码分开。所以你应该创建一个类,它读取列车列表并将其放入请求中,或多或少是这样的:

public class RailLink {
    public String from;
    public String to;
    public String trainName;
}

public class Trains {

    private Connection getConnection() {
        //- This code actually should be put somewhere else.
//          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//          String db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:/Users/hp/Documents/Sample1.accdb";
//          Connection cn = DriverManager.getConnection(db, "", ""); 
            return cn;
    }

    public static List<RailLink> findLinks(String from, String to) {
        assert from != null && to != null;
        List<RailLinks> links = new LinkedList<>();
        try (
            Connection cn = getConnection();
            PreparedStatement ps = cn.prepareStatement("SELECT * FROM Trains123 WHERE \"From\" = ? AND \"To\" = ?");
        ) {
            ps.setString(1, from);
            ps.setString(2, to);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    RailLink link = new RailLink();
                    link.from = rs.getString("From");
                    link.to = rs.getString("To");
                    link.trainName = rs.getString("TrainName");
                    links.add(link);
                }
            }
        }
        return links;
    }
}

Now write a servlet which handles your form:

现在编写一个处理表单的 servlet:

public class FindLinks extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse respone) {
        List<RailLink> links = Trains.findLinks(request.getParameter("from"), request.getParameter("to"));
        request.setAttribute("rail-links", links);
        request.getRequestDispatcher("page1.jsp").forward(request, response);
    }
}

And finally modify your page1.jsp as:

最后将你的 page1.jsp 修改为:

<%@page ...%>
...
<%  List<RailLink> links = request.getAttribute("rail-links");
    if (links != null) {%>
        <table><%
        for (RailLink l : links) {%>
            <tr><td><%=l.from%></td>
                <td><%=l.to%></td>
                <td><%=l.trainName%></td>
                <td><input type="radio" name="TName" value="<%=l.trainNam%"/> book</td>
        <%}%>
        </table><%
    }
    else {%>
        <p>No connections found.</p><%
    }%>

Have a good luck with it.

祝你好运。