[an error occurred while processing this directive]

BeanNameUrlHandlerMappingWithCommandClass Example

                   

BeanNameUrlHandlerMappingWithCommandClass example in Spring 2.5 MVC framework

Learn how to use BeanNameUrlHandlerMapping with CommandClass.

In this example we will used BeanNameUrlHandlerMapping with Command class. You can see what is the process of using command class with BeanNameUrlHandlerMapping handler mapping.

Step 1:

Now we will create a index.jsp inside the /WebContent/ directory that will have a hyperlink for generate Client request in the web browser. The code of the index.jsp is:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>

<head>

<title>BeanNameUrlHandlerMapping using Command Class</title>

</head>

<body>

<center>

<a href="beannameurlhandlermappingwithcommandclass.html">BeanNameUrlHandlerMapping Using Form</a>

</center>

</body>

</html>

Step 2:

Now we will configure the web.xml for DispatcherServlet and set index.jsp as a welcome file. we will also add string.tld file with the help of <taglib> in the web.xml file. The code of the web.xml is:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"

version="2.5">

<servlet>

<servlet-name>dispatcher</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>dispatcher</servlet-name>

<url-pattern>*.html</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<taglib>

<taglib-uri>/spring</taglib-uri>

<taglib-location>/WEB-INF/spring.tld</taglib-location>

</taglib>

</web-app>

Step 3:

Now we will create a dispatcher-servlet.xml file inside the /WEB-INF/ project directory. The dispatcher-servlet.xml file contains maps incoming HTTP requests to names of beans by using BeanNameUrlHandlerMapping. The code that are use for this task is:

<bean id="defaultHandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

<bean id="contactValidator" class="net.roseindia.web.ContactValidator"/>

<bean name="/beannameurlhandlermappingwithcommandclass.html" class="net.roseindia.web.BeanNameUrlHandlerMappingController">

<property name="formView"><value>CreateContact</value></property>

<property name="validator"><ref bean="contactValidator"/></property>

<property name="successView"> <value>ContactCreated</value> </property>

<property name="commandClass"><value>net.roseindia.web.Contact</value></property>

<property name="commandName"><value>contact</value></property>

</bean>

First bean setting provides BeanNameUrlHandlerMapping for the use as a HandlerMappings. The second bean setting provide a validator class and third bean setting uses Http request as a name of the bean and provides class to handle this request. The  BeanNameUrlHandlerMapping using Url of the Client is directly mapped to the Controller. we have also set the properties like formView,  validator with reference bean , successView, commandClass and commandName.

Step 4:

Now we will create CreateContact.jsp file inside the /WEB-INF/jsp/ folder that will have a form with user contact information fields, user fill own contact information in this fields. The BeanNameUrlHandlerMappingController display this jsp file as a formView. The code of the CreateContact.jsp is:

<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%@ taglib prefix="spring" uri="/spring"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>

<head>

<title>BeanNameUrlHandlerMapping Example Using Command class</title>

</head>

<body>

<center>

<form:form method="POST" commandName="contact" name="contact">

<table border="2">

<tr>

<td>First Name :</td>

<td><form:input path="fname" /><font color="red"><form:errors path="fname"/></font></td>

</tr>

<tr>

<td>Last Name</td>

<td><form:input path="lname" /><font color="red"><form:errors path="lname"/></font></td>

</tr>

<tr>

<td>EMailId :</td>

<td><form:textarea path="emailid" /><font color="red"><form:errors path="emailid"/></font></td>

</tr>

<tr>

<td>Gender :</td>

<td>

<form:radiobutton path="gender" value="Male" label="Male" />

<form:radiobutton path="gender" value="Female" label="Female" />

<font color="red"><form:errors path="gender"/></font>

</td>

</tr>

<tr>

<td>Address :</td>

<td><form:textarea path="address" /><font color="red"><form:errors path="address"/></font></td>

</tr>

<tr>

<td>Contact Number :</td>

<td><form:textarea path="contactnumber" /><font color="red"><form:errors path="contactnumber"/></font></td>

</tr>

<tr>

<td>Country :</td>

<td><form:input path="country" /><font color="red"><form:errors path="country"/></font></td>

</tr>

<tr>

<td colspan="2"><input type="submit" value="Create Contact"></td>

</tr>

</table>

</form:form>

</center>

</body>

</html>

Step 5:

Now we will create a ContactCreated.jsp for display all information (using command class and command name) that are entered by user. The bean property successView display this file if user fill all  information successfully. The code of the ContactCreated.jsp is:

<%@ page session="false"%>

<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%@ taglib prefix="spring" uri="/spring" %>

<html>

<head>

<title>BeanNameUrlHandlerMapping Example Using Form</title>

</head>

<body>

<center>

<table>

<tr>

<td colspan="2" align="center"><font size="5">Contact Information</font></td>

</tr>

<tr>

<td>First Name:</td>

<td><core:out value="${contact.fname}"/></td>

</tr>

<tr>

<td>Last Name:</td>

<td><core:out value="${contact.lname}"/></td>

</tr>

<tr>

<td>EmailId:</td>

<td><core:out value="${contact.emailid}"/></td>

</tr>

<tr>

<td>Gender:</td>

<td><core:out value="${contact.gender}"/></td>

</tr>

<tr>

<td>Address:</td>

<td><core:out value="${contact.address}"/></td>

</tr>

<tr>

<td>Contact Number:</td>

<td><core:out value="${contact.contactnumber}"/></td>

</tr>

<tr>

<td>Country:</td>

<td><core:out value="${contact.country}"/></td>

</tr>

</table>

</center>

</body>

</html>

Step 6:

Now we will create a a controller class that's name BeanNameUrlHandlerMappingController.java  for handle user generated request and return ModelAndView with contact class object. The code of the BeanNameUrlHandlerMappingController.java is:

package net.roseindia.web;

import javax.servlet.ServletException;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
 
import net.roseindia.web.Contact;
public class BeanNameUrlHandlerMappingController extends SimpleFormController 
      
    @Override
    protected ModelAndView onSubmit(Object commandthrows ServletException {
      Contact contact = (Contactcommand;
      System.out.println(contact.getFname());
      System.out.println(contact.getLname());
      System.out.println(contact.getGender());
      System.out.println(contact.getAddress());
      System.out.println(contact.getCountry());
      System.out.println(contact.getContactnumber());
      System.out.println(contact.getEmailid());
    
    ModelAndView modelAndView = new ModelAndView("ContactCreated");
    modelAndView.addObject("contact", contact)
    return modelAndView;
    }
}

Step 7:

Now we will create a Contact.java class inside the project src folder. We have used this class as command class for the user request. This class is a Javabean class that have user contact variables and these setter and getter methods. The code of the Contact.java is:

package net.roseindia.web;

public class Contact {
  public Contact(){}
    private String fname;
    private String lname;
    private String gender;
    private String address;
    private String country;
    private String emailid;
    private String contactnumber;

    public String getFname() {
        return fname;
    }
    public void setFname(String fname) {
        this.fname = fname;
    }
    public String getLname() {
        return lname;
    }
    public void setLname(String lname) {
        this.lname = lname;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getGender() {
        return gender;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getAddress() {
        return address;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    public String getCountry() {
        return country;
    }
    public void setEmailid(String emailid) {
        this.emailid = emailid;
    }
    public String getEmailid() {
        return emailid;
    }
    public void setContactnumber(String contactnumber) {
        this.contactnumber = contactnumber;
    }
    public String getContactnumber() {
        return contactnumber;
    }
 }

Step 8:

Now we will create a ContactValidator.java class that validate the CreateContact.jsp form fields. The code of the ContactValidator.java is:

package net.roseindia.web;
import java.util.regex.*;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.ValidationUtils;

import net.roseindia.web.Contact;

public class ContactValidator implements Validator {

   @Override
    public boolean supports(Class clazz) {
        return Contact.class.isAssignableFrom(clazz);
    }
    public void validate(Object obj, Errors errors) {
      Contact contact = (Contactobj;     

      
      if ((contact.getEmailid() != ""|| (contact.getEmailid().length()) != 0) {        
        Pattern p=Pattern.compile(".+@.+\\.[a-z]+");
          Matcher m=p.matcher(contact.getEmailid());
          boolean b=m.matches();
          if(b!=true)
          {
             errors.rejectValue("emailid""error.is.not.valid""Email ID does not Valid ");        
          }
        }
      
      if ((contact.getContactnumber()!= ""|| (contact.getContactnumber().length()) != 0) {        
          Pattern pattern = Pattern.compile("\\d{1}-\\d{4}-\\d{6}");
          Matcher matcher = pattern.matcher(contact.getContactnumber());
          boolean con=matcher.matches();
          if(con!=true)
            {
              errors.rejectValue("contactnumber""error.is.not.valid""Enter Contact Number Like 0-9999-999999");
            }
        }
      if (contact.getFname() == null || contact.getFname().length() == 0) {
            errors.rejectValue("fname""error.empty.field""Please Enter First Name");
        }        
        if (contact.getLname() == null || contact.getLname().length() == 0) {
            errors.rejectValue("lname""error.empty.field""Please Enter Last Name");
        }        
        if (contact.getEmailid() == null || contact.getEmailid().length() == 0) {
            errors.rejectValue("emailid""error.empty.field""Please Enter EmailId");
        }
        if (contact.getAddress() == null || contact.getAddress().length() == 0) {
            errors.rejectValue("address""error.empty.field""Please Enter Address");
        }
        if (contact.getCountry() == null || contact.getCountry().length() == 0) {
            errors.rejectValue("country""error.empty.field""Please Enter Country");
        }
        if (contact.getContactnumber() == null || contact.getContactnumber().length() == 0) {
            errors.rejectValue("contactnumber""error.empty.field""Please Enter Contact Number");
        }
        if (contact.getGender() == null || contact.getGender().length() == 0) {
            errors.rejectValue("gender""error.empty.field""Please Enter Genter");
        }
    }
} 

Step 9:

Now we will run this example and output is:

If user click on this link then the output is:

If user not fill all information with correct format then the validation called like:

If the user fill all information correct format and click on the button "Create Contact". After that the output is:

Download code

                 

[an error occurred while processing this directive]