Validation Check in Servlet



This is an application which will do the validation check for the student rollno, name and their marks. For this application create an index.html as shown below. In this index.html, I had also done some formatting of the table so you all can also do. Dear students it is a sample only, you all can do more formatting and you also can include more fields for validation. In this application, there is an integer value, one string and one float value which is validated.



index.html


ValidationServ.java
protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
       ArrayList al = new ArrayList();
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String sno1 = req.getParameter("validpro_sno");
        String sname = req.getParameter("validpro_sname");
        String smarks1 = req.getParameter("validpro_smarks");
        String sphone = req.getParameter("validpro_sphone");
        int sno = 0;
        float smarks = 0;
        if ((sno1 == null) || (sno1.equals(""))) {
            al.add("PROVIDE STUDENT NUMBER...");
        } else {
            try {
                sno = Integer.parseInt("sno1");
            } catch (NumberFormatException nfe) {
                al.add("PROVIDE int DATA IN STUDENT NUMBER...");
            }
        }
        if ((sname == null) || (sname.equals(""))) {
            al.add("PROVIDE STUDENT NAME...");
        }
        if ((smarks1 == null) || (smarks1.equals(""))) {
            al.add("PROVIDE STUDENT MARKS...");
        } else {
            try {
                smarks = Float.parseFloat("smarks1");
            } catch (NumberFormatException nfe) {
                al.add("PROVIDE float DATA IN STUDENT MARKS...");
            }
        }
        if ((sphone == null) || (sphone.equals(""))) {
            al.add("PROVIDE STUDENT PHONE NUMBER...");
        }
        RequestDispatcher rd= req.getRequestDispatcher("/index.html");
        rd.include(req, res);
        if (al.size() != 0) {
            pw.println(al);
        }     }
If all the text box are empty, you should get the following error.

If you will enter non numeric data in the student number and all other text boxes empty then you will get an error as



Now test all the possibilities of error

1 comment: