过去的用户操作

时间:2011-03-18 21:35:21

标签: html jsp struts

我有一个jsp页面。在页面中我有3个单选按钮。当我单击按钮时,会将url发送到操作servlet,并再次重新加载相同的页面。但是当新页面重新加载时,我之前检查过的单选按钮未被选中。我想以某种方式记住并再次检查它,以便当页面重新加载时,用户可以看到他点击了什么单选按钮,因为有三个单选按钮,所有都进行相同的页面重新加载。有什么建议我怎么能做到这一点..?

2 个答案:

答案 0 :(得分:-1)

我不熟悉JSP / Struts,但这就是我在PHP中的做法。您可以将其转换为JSP代码:

<form method="POST">
<?php
    // labels for our radio buttons
    $labels = array('Value 0', 'Value 1', 'Value 2');

    // get the submitted value, or set to -1
    $radio = (isset($_POST['radio']) ? (int)$_POST['radio'] : -1);

    // loop for each label
    for ($r=0; $r<count($labels); $r++) {

        // if current iteration matches submitted value, check the radio
        $checked = ($radio == $r ? 'CHECKED' : '');

        // output radio button and label
        echo <<< HTML
    <input type="radio"  id="radio{$r}"  name="radio" value="{$r}" {$checked}>
    <label for="radio{$r}"> {$labels[$r]}</label>
HTML;
    }
?>
    <input type="submit" value="Submit">
</form>

答案 1 :(得分:-1)

有很多方法可以做到这一点。我举一个例子来做这件事。我对此并不是很好,但你可以改进我的编码。这是;

我假设您已经知道如何向服务器发送请求并转发它。

的index.jsp

    <%
        int chkOpt = 0;
        if(request.getAttribute("checked") != null){
            chkOpt = Integer.parseInt(request.getAttribute("checked").toString());  
        }
    %>

<form action="reload" method="post">
<input type="radio" name="option" value="1" <% if(chkOpt == 1) out.print("CHECKED"); %> />First Radio Button
<input type="radio" name="option" value="2" <% if(chkOpt == 2) out.print("CHECKED"); %> />Second Radio Button
<input type="radio" name="option" value="3" <% if(chkOpt == 3) out.print("CHECKED"); %> />Third Radio Button
<input type="submit">
</form>

重新加载Servlet

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

    String optval = null;
    if(request.getParameter("option") != null){
        optval = request.getParameter("option").toString(); 
    }

    request.setAttribute("checked", optval);
    getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);b
}

这里的主要内容是你有一个变量来处理点击了哪个选项。

我希望你能够根据我的例子得到我的观点。这已经工作只是试一试,了解它是如何做的。注意:这只是jsp和servlet