25.Performing Validations and Re-Populating Fields Using MVC

Saturday, February 5, 2011 Posted by Sudarsan
In this post we are going to learn how to validate data using JSPs and to repopulate the data into the html inputs when the JSP Form page is submitted to the server.

Have look at the fallowing web pages, there we can observe that the data submitted in the form are validated, to perform the validations use the fallowing Servlet and JSP codes.












AddCusServ.java

public class AddCusServ extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String cname = request.getParameter("cname");
            String uid = request.getParameter("uid");
            String pwd = request.getParameter("pwd");
            String cpwd = request.getParameter("cpwd");
            String dob = request.getParameter("dob");

            boolean error = false;

            if (cname.length() == 0 || cname == null) {
                error = true;
                request.setAttribute("cnameerror", "Please Enter Customer Name");
            } else if (!Validations.isValidName(cname)) {
                error = true;
                request.setAttribute("cnameerror", "Customer Name Can Only Contains Alphabet");
            }

            if (uid.length() == 0 || uid == null) {
                error = true;
                request.setAttribute("uiderror", "Please Enter User Name");
            }

            if (pwd.length() == 0 || pwd == null) {
                error = true;
                request.setAttribute("pwderror", "Please Enter Password");
            }

            if (cpwd.length() == 0 || cpwd == null) {
                error = true;
                request.setAttribute("cpwderror", "Please Confirm Password");
            } else if (!cpwd.equals(pwd)) {
                error = true;
                request.setAttribute("cpwderror", "Passwords do not match ");
            }

            if (dob.length() == 0 || dob == null) {
                error = true;
                request.setAttribute("doberror", "Please Enter Date of Birth");
            } else if (!Validations.isValidDate(dob)) {
                error = true;
                request.setAttribute("doberror", "Date Must be in DD/MM/YYYY Format");
            }

            if (error) {
                RequestDispatcher view = request.getRequestDispatcher("/client/newcustomer.jsp");
                view.forward(request, response);
                return;
            }

            CustLogin custLogin=new CustLogin();
            custLogin.setCustomername(cname);
            custLogin.setUsername(uid);
            custLogin.setPassword(pwd);
            custLogin.setDob(dob);

            Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            em.persist(custLogin);
            utx.commit();

            RequestDispatcher view=request.getRequestDispatcher("/client/index.jsp");
            view.forward(request, response);


        } catch (Exception e) {
            out.print(e.toString());
        } finally {
            out.close();
        }
    }

newcustomer.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <head>
        <title>Customer Registration</title>
        <link rel="stylesheet" type="text/css" href="/OnlineTelecomCustomerSupport/css/myStyle.css"/>
    </head>
    <body>
        <h1>Customer Registration</h1>
        <td height="20" align="center">
            <img src="/OnlineTelecomCustomerSupport/images/hr.jpg"/>
        </td>
        <p> <p> <p> 
        <form method="POST" action="<%=request.getContextPath()%>/AddCusServ" class="formContent">
            <table border="0" align="center">
                <tr>
                    <td>Customer Name</td>
 <td><input type="text" name="cname" value="<%=request.getAttribute("cname") != null ? request.getParameter("cname") : request.getParameter("cname") != null ? request.getParameter("cname") : ""%>" /></td>
                    <%if (request.getAttribute("cnameerror") != null) {                    %>
                    <td class="error"><%=request.getAttribute("cnameerror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td>Desired User Name</td>
                    <td><input type="text" name="uid" value="<%=request.getAttribute("uid") != null ? request.getParameter("uid") : request.getParameter("uid") != null ? request.getParameter("uid") : ""%>" /></td>
                    <%
        if (request.getAttribute("uiderror") != null) {
                    %>
                    <td class="error"><%=request.getAttribute("uiderror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="pwd" value="" /></td>
                    <%
        if (request.getAttribute("pwderror") != null) {
                    %>
                    <td class="error"><%=request.getAttribute("pwderror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td>Confirm Password</td>
                    <td><input type="password" name="cpwd" value="" /></td>
                    <%
        if (request.getAttribute("cpwderror") != null) {
                    %>
                    <td class="error"><%=request.getAttribute("cpwderror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td>Date of Birth</td>
                    <td><input type="text" name="dob" value="<%=request.getAttribute("dob") != null ? request.getParameter("dob") : request.getParameter("dob") != null ? request.getParameter("dob") : ""%>" /></td>
                    <%
        if (request.getAttribute("doberror") != null) {
                    %>
                    <td class="error"><%=request.getAttribute("doberror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Add" class="buttonText" style="background:url(/OnlineTelecomCustomerSupport/images/submit_bg.gif) no-repeat scroll 37px 0px;"/></td>
                    <td></td>
                </tr>
            </table>
        </form> <p> <p> 
        | <a href="/OnlineTelecomCustomerSupport/client/index.jsp">Back</a> |
    </body>
</html>




When we run this project, after successful completion of validations the form data will be submitted to the database otherwise we will get the same page and we need to fulfill the requirements.

Here I am also providing the validating class to validate Name and Date in the JSP page.

Validations.java

public class Validations implements java.io.Serializable {
    public static boolean isValidName(String cname) {
        if (cname.matches("^[a-zA-Z]+$")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isValidDate(String dob) {
        if (dob.matches("\\d{1,2}/\\d{1,2}/\\d{2,4}")) {
            return true;
        } else {
            return false;
        }
    }
}

Okay Folks !!, Next time I will meet you with some other interesting topic !!!
Labels: ,

Post a Comment