0

I have a JSP which will let a user register for an account at my website. If the user submits wrong or illegal info into the JSP, then I want to return the same JSP with an appropriate error message next to/above each wrongly filled (form) fields.

If possible, highlight the wrongly filled form field - this feature is not necessary though.

I have given a sample below to show what I need. I understand that the sample must be using something like javascript, but I don't know all that client side scripting. I only want to use JSP to do it. As I said, I want to sort of return the JSP form to the user after marking all the mistakes and how to correct them.

How do I do this ? I only need some initial direction. I will make the code myself and post it here later.

Thanks.

EDIT - I don't want the drop down box. I don't want red borders around wrongly entered fields. I only want to display the error messages (in red color) next to the relevant fields.

enter image description here

Here is some sample code -

<%@ 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);

        }

    }

}
Erran Morad
  • 4,563
  • 10
  • 43
  • 72
  • 2
    Some of those are HTML 5 attributes. Others are not, and handling this use case using plain JSP and Servlets is not easy task. It would be better if you use a mvc web framework like JSF or Spring MVC that eases the development of such requirement. – Luiggi Mendoza Jun 05 '14 at 22:05
  • +1 for using Spring MVC + Java Validation. Also, server side validation is required. It is quite easy to get around only client side validation. I would recommend only using server side validation, that way you only have validation code in one place, instead of two. – hooknc Jun 05 '14 at 22:10
  • @LuiggiMendoza - Thanks. Long ago, I saw someone doing this in JSP and servlets only. That is, he was only showing the same registration form with error messages. There was NO dropdown list and NO red border around wrongly entered fields. Can't find that tutorial :( – Erran Morad Jun 05 '14 at 22:13
  • I would recommend AngularJS for client side validation, I have attached a link to the end of this comment. Of course you will want server-side validation as well but you can do this with trivial Java once the data has been submitted. https://docs.angularjs.org/guide/forms – Dennis Jun 05 '14 at 22:13
  • @Mr.White - Thanks for the suggestion. Right now, I am only looking for a way to do this with jsp and servlets. – Erran Morad Jun 05 '14 at 22:15
  • Ok well this is a great tutorial I used some time ago. http://www.javaworld.com/article/2076076/java-web-development/server-side-java--advanced-form-processing-using-jsp.html?page=1 – Dennis Jun 05 '14 at 22:16
  • 2
    @Mr.White that article is from year 2000. Technology has advanced since there, so there's no need to use `` anymore... – Luiggi Mendoza Jun 05 '14 at 22:21
  • @LuiggiMendoza - I was thingking of an approach. Create a Form Bean. It has field String user, boolean isUserExists = false and other things. If verification servlet sees that the user exists already, then it sets the bean isUserExists = true. The JSP displays an message (i.e error message) only when isUserExists = true for a form bean. Makes sense ? Would this be a good way ? – Erran Morad Jun 05 '14 at 22:42
  • From your given code: 1) Use HTML 5, looks like you're lost in web technology since 2011 (no need of that `"blah..."` senseless code). 2) You need to add `
    `s next to each `` in your view that will display the error messages for clients. 3) Use Servlet 3.0 or more, so you may take advantage of annotation configuration rather than tedious XML through web.xml. 4) You absolutely don't want to perform such validations in a common POST-FORWARD request, instead using ajax request for a better look-n-feel for your clients.
    – Luiggi Mendoza Jun 05 '14 at 22:42
  • @BoratSagdiyev that's the basic approach, and you should use something similar per input that needs validation in your `
    `
    – Luiggi Mendoza Jun 05 '14 at 22:46
  • @LuiggiMendoza - I am not an expert like you. I only know basic html, jsp and servlets. I am trying to use just that to get this done, if its not too complicated. Otherwise, I will simply make the reg servlet generate a html form with errors next to each field. Simple. I need time to learn spring, ajax, js and all the good stuff. – Erran Morad Jun 05 '14 at 22:46
  • @LuiggiMendoza - Can you please suggest some tutorial which shows me all the 4 points ? – Erran Morad Jun 05 '14 at 22:47
  • 1
    *I am trying to use just that to get this done, if its not too complicated* if you re read my first comment, I'm stating that this is too complicated to handle using JSP and Servlets only. You can make it to work, but it takes too much time and effort to do it that should be only for learning purposes (and I would even say it is not that necessary). Instead, look on frameworks that helps you to accomplish these tasks. JSP + Servlets are not the solution for everything, but note that other solutions are built over JSP and/or Servlets. – Luiggi Mendoza Jun 05 '14 at 22:50
  • The AOL Mail page is definitely using Ajax and from what they've named their inputs it looks like they're also using a framework, probably Struts considering the names like `{action.something}` and the use of the `.do` extension. – developerwjk Jun 05 '14 at 23:15
  • Why was I given -1 ? This is a conspiracy. – Erran Morad Jun 05 '14 at 23:25

2 Answers2

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");
Tusar
  • 759
  • 5
  • 21
-1

have the page post to itself, like this login.jsp fragment:

    <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>
Lorenzo Boccaccia
  • 6,041
  • 2
  • 19
  • 29
  • It gives me many errors - `Multiple annotations found at this line: - Syntax error, insert "enum Identifier" to complete EnumHeader - Syntax error on token "catch", invalid AnnotationName - Syntax error on token(s), misplaced construct(s) - Syntax error, insert "}" to complete EnumBody` – Erran Morad Jun 05 '14 at 23:15
  • sorry left too much parentheses (it is pasted from a program of mine, reduced) – Lorenzo Boccaccia Jun 05 '14 at 23:18
  • the form make a request to the jsp itself. then the request object is read, and if the data is valid user gets redirected to another page – Lorenzo Boccaccia Jun 05 '14 at 23:19