简体   繁体   English

如何使用Servlet验证JSP并保留输入数据?

[英]How to validate JSP with Servlet and keep input data?

I need a little help to tie a JSP and two Java Servlet together. 我需要一点帮助将JSP和两个Java Servlet绑定在一起。 I have got the following: 我有以下几点:

On the JSP: 在JSP上:

  • First two radio buttons with onchange="submit()" 带有onchange =“ submit()”的前两个单选按钮
  • a div container, which will only appear if one of the radio buttons is active (containing the next two) div容器,仅当其中一个单选按钮处于活动状态(包含接下来的两个按钮)时才会显示
  • some dropdowns, populated according to the choice of the radio button 根据单选按钮的选择填充一些下拉菜单
  • some input fields 一些输入字段

Two Servlets: 两个Servlet:

  • one for populating the dropdowns 一个用于填充下拉菜单
  • second for validating everything else and filling the db/redirecting to another page in case of success, ... 第二个用于验证其他所有内容并在成功的情况下填充数据库/重定向到另一个页面,...

The population works well, so does the database part. 总体运行良好,数据库部分也是如此。

There are only some combinations allowed for the different drop down menus (there are in reality more values and more drop down menus as in the snippet below). 不同的下拉菜单只有一些组合(实际上,如下面的代码片段所示,有更多的值和更多的下拉菜单)。 My problem is: Whenever validation fails, the JSP reloads (that's obviously ok) and my choices made vanished and I start choosing between the radio button options. 我的问题是:每当验证失败时,JSP就会重新加载(这显然可以),我的选择消失了,我开始在单选按钮选项之间进行选择。

To pass the value of the radio button from Servlet 1 to Servlet 2 seems to work perfectly. 将单选按钮的值从Servlet 1传递到Servlet 2看起来很完美。 (I tried already to use the same methods (request.set...) within the reload of Servlet2, but it did not work.) Also the validation works fine. (我已经尝试在Servlet2的重新加载中使用相同的方法(request.set ...),但是它不起作用。)验证也可以正常工作。


Question : How can I achieve, that after validation the radio-buttons (and other input fields) are preselected as they were before? 问题 :如何获得验证后像以前一样预先选择单选按钮(以及其他输入字段)的信息? I just want to show an error message and keep all input values. 我只想显示一条错误消息并保留所有输入值。


If this is important, here are some parts of the code, names changed, hopefully consistently. 如果这很重要,请在代码的某些部分进行更改,以使名称保持一致。 If someone knows how to put this in an on-demand/spoiler container, feel free to edit. 如果有人知道如何将其放在按需/扰流器容器中,请随时进行编辑。

input.jsp input.jsp

<body>
    <span class="messages">${messages.ERROR}</span>
    <form action="/project/chooseRadio" method="get">

        <h2>Radio</h2>
        <input type="radio" name="option" onchange="submit()"
            value="option1"
            ${param.option == 'option1' ? 'checked' : ''}> 
            <input type="radio"
            name="option" onchange="submit()" value="option2"
            ${param.option== 'option2' ? 'checked' : ''}>
    </form>


    <form action="/project/input" method="post">    
        <div
            style="display:${(option == 'option1'  || option == 'option2') ? 'block' : 'none'}">

            <select name="dd1">
                <c:forEach items="${dd1}" var="dd1">
                    <option><c:out value="${dd1}" /></option>
                </c:forEach>
            </select> 
            <select name="dd2">
                <c:forEach items="${dd2}" var="dd2">
                    <option><c:out value="${dd2}" /></option>
                </c:forEach>            


            <input type="text" name="inputfield1" required="true" /> <br> 
            <input type="text" name="inputfield2" required="true" /> <br>
            <input type="submit" name="submit"
                value="submit" />
          </span>
        </div>
    </form>   
</body>

chooseRadio-Servlet 选择Radio-Servlet

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

    // option1
    int[] dd1_1 = { 1, 2, 3, 4 };
    int[] dd2_1 = { 1, 2, 3, 4 };

    // option2
    int[] dd1_2 = { 9, 8, 7, 6 };
    int[] dd2_2 = { 9, 8, 7, 6 };

    if (request.getParameter("option") != null) {

        switch (request.getParameter("option")) {
        case "option 1":
            request.setAttribute("option", "option1");
            request.setAttribute("dd1", dd1_1);
            request.setAttribute("dd2", dd2_1);
            break;

        case "option2":
            request.setAttribute("gratingType", "option2");
            request.setAttribute("dd1", dd1_2);
            request.setAttribute("dd2", dd2_2);
            break;
        default:
            break;
        }
    }

    request.getRequestDispatcher("/WEB-INF/input.jsp").forward(request, response);
}

input-Servlet 输入Servlet

@WebServlet("/input")
public class InputServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

        request.getRequestDispatcher("/WEB-INF/input.jsp").forward(request, response);
    }

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

        DTO dto = new DTO();

        Map<String, String> messages = new HashMap<String, String>();

        switch (request.getParameter("option")) {
        case "option1":
            dto.setOption("option1");
            break;

        case "option2":
            dto.setOption("option2");
            break;
        default:
            break;
        }


dto.setInputfield1(Integer.parseInt(request.getParameter("inputfield1")));
// ... dto.set for other fields ... //
// save dto in database
// validation
    if(validCombination(...)){
                request.getRequestDispatcher("/WEB-INF/output.jsp").forward(request, response);
            }
            else {
                messages.put("ERROR", String.format("this is not a valid combination."));
                request.setAttribute("messages", messages);
                request.getRequestDispatcher("/WEB-INF/input.jsp").forward(request, response);
            }
        }

You have three options really 你真的有三个选择

  1. Do the validation clientside in javascript without a serverside call prior to submitting the form 在提交表单之前,无需服务器端调用即可在javascript中进行验证客户端
  2. Do the validation clientside in javascript with a serverside call (ajax) prior to submitting the form 在提交表单之前,先用服务器端调用(ajax)在javascript中进行验证客户端
  3. Submit the form and refresh the page for validation 提交表单并刷新页面以进行验证

Options 1&2 will leave the values in the fields. 选项1和2将值保留在字段中。 Option 3 will require you to populate the values as well as showing the error message. 选项3将要求您填充值并显示错误消息。

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

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