JSP - 在同一个jsp中验证表单并显示错误

时间:2014-06-05 22:02:51

标签: java jsp servlets

我有一个JSP,它允许用户在我的网站上注册一个帐户。如果用户将错误或非法信息提交到JSP中,那么我想返回相同的JSP,并在每个错误填充(表单)字段旁边/上方添加相应的错误消息。

如果可能,请突出显示错误填写的表单字段 - 但此功能不是必需的。

我在下面给出了一个样本来展示我的需求。我知道样本必须使用类似javascript的东西,但我不知道所有客户端脚本。我只想用JSP来做。正如我所说,我希望在标记所有错误以及如何纠正错误之后将JSP表单返回给用户。

我该怎么做?我只需要一些初步指导。我将自己编写代码并稍后在此处发布。

感谢。

编辑 - 我不想要下拉框。我不想在错误输入的字段周围出现红色边框。我只想在相关字段旁边显示错误消息(红色)。

enter image description here

以下是一些示例代码 -

<%@ page language="java" contentType="blah..." pageEncoding="blah..."%>
<!DOCTYPE html PUBLIC "blah...">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user"><br>
password : <input type="password" name="pwd">
</form>
</body>
</html>

RegServlet -

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    static String okUser = "loser";

    public RegServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");

        if(user.equalsIgnoreCase(okUser) == false){
            //Do something MAGICAL to set an error next to username field of Form.jsp, then forward.
            RequestDispatcher view = request.getRequestDispatcher("/jsp/Form.jsp");
            view.forward(request, response);

        }

    }

}

2 个答案:

答案 0 :(得分:0)

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Ajax Validation</title>
     <script src="http://code.jquery.com/jquery-1.9.1.js"></script>    
     <!-- or download to a directory -->
        <!-- <script src="js/jquery-1.9.1.js"></script> -->

        <script type="text/javascript">
            jQuery(document).ready(function(){   
                jQuery('#user').change(function() {     
                    var userName = jQuery(this).val();
                        jQuery.ajax({ 
                            type        : 'GET', 
                            url         : 'AjaxUserCheck',
                            data        : {user:userName},
                            dataType    : 'html',
                            success     : function(data) {                 
                                if(jQuery.trim(data)=='1')
                                {
                                   jQuery("#userLabel").html("Sorry! username is taken");      
                                    //write other stuff: border color ...
                                 }
                                    else if(jQuery.trim(data)=='0')
                                        jQuery("#userLabel").html("user name available"); 
                                    else
                                        alert(data); //possible error
                            },
                            error   : function(xhr,status,error){
                                console.log(xhr);   
                                alert(status);
                            }
                        });    
                });
        });
        </script>

</head>
<body>
    <form method="post" action = "/RegServlet">
        user name: <input type="text" name="user" id="user">
        <label id="userLabel"></label>
        <br>
    password : <input type="password" name="pwd">
    </form>
</body>
</html>

---------的Servlet ------

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String user = request.getParameter("user");
    //if(dao.isUserExist(user)){
    if(user.equals("java")){ // check for db if userid exists in DB print '1' else '0'
        out.print("1");
    }
    else
        out.print("0");

答案 1 :(得分:-1)

将页面发布到自身,就像这个login.jsp片段:

    <div class="error">
        <%

                String usrName = "" + request.getParameter("username");
                String usrPass = "" + request.getParameter("password");
          if (isValid(usrName,usrPass){
                         openUserSession(usrName); //here you open a session and set the user, if the session doesn't have an user redirect to login.jsp
                           response.sendRedirect("index.jsp"); //user ok redirect to index (or previous page)
                        } else {
                            out.print("Invaid user or password");
                        }

        %>
    </div>
    <form action="login.jsp" method="POST"> <!-- login.jsp post to itself -->
        <input type="text" name="username" id="username"/>
        <input type="password" name="password" />
        <input type="submit" value="login" name="login" />
        <input type="submit" value="register" name="register" />
    </form>