Showing posts with label Spring MVC. Show all posts
Showing posts with label Spring MVC. Show all posts

Saturday, January 28, 2017

Model value ${} is not displayed in the JSP

The Spring Expression Language (SpEL) is a powerful expression language that supports querying and manipulating an object graph at runtime. It can be used with XML or annotation-based Spring configurations. Sometimes, it will make you to scratch your head, when things not working. Recently i encountered a wired problem while working on the Spring MVC project, me trying to set a value into a model, and display the value in JSP via EL, e.g ${name}, but it just outputs the result as it is – ${name}, not the “value” stored in the model.

Controller

 @Controller  
 public class HelloController {  
      @RequestMapping("/hello")  
      public String hello(Model model) {  
           model.addAttribute("name", "John Doe");  
           return "welcome";  
      }  
 }  

JSP File

 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
 <!DOCTYPE html>  
 <html>  
 <head>  
      <title>Home Page</title>  
      <link rel='stylesheet' href='<c:url value="/resources/css/style.css" />' type='text/css' media='all' />   
 </head>  
 <body>  
      <h2>Hello World, Spring MVC</h2>  
      <p>Welcome, ${name}</p>  
      <p>Welcome, ${name}</p>  
      <p>Welcome, ${name}</p>  
 </body>  
 </html>  

Everything looks good in the above, then what makes the jsp page just to dump the EL script as it is. Actually the issue is caused by the old JSP 1.2 descriptor. If you are using the old JSP 1.2 descriptor, defined by DTD ,for example web.xml. The EL is disabled or ignored by default, you have to enable it manually, so that it will outputs the value store in the "name" model.

JSP 1.2 web.xml
 <!DOCTYPE web-app PUBLIC  
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
  "http://java.sun.com/dtd/web-app_2_3.dtd" >  
 <web-app>  
  <display-name>Archetype Created Web Application</display-name>  
 </web-app>  

So you just add the following tag <%@ page isELIgnored="false" %> , this will resolve the issue.

JSP 2.0
If you are using the standard JSP 2.0 descriptor, defined by w3c schema ,for example web.xml. The EL is enabled by default, and you should see the value stored in the "name" model, which is "John Doe".

 <web-app id="WebApp_ID" version="2.4"  
      xmlns="http://java.sun.com/xml/ns/j2ee"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  
      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
 //...  
 </web-app>  

Happy Programming...!!!

Sunday, May 8, 2016

java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute

By default, Spring MVC throws an exception when errors occur during request binding. This usually not what we want – instead we should be presenting these errors to the user. We’re going to use a BindingResult by adding one as an argument to our controller method:

 @RequestMapping(value="/addEmployee", method=RequestMethod.POST)  
      public String addEmployees(BindingResult result, @ModelAttribute("employee") Employee employee,  
                Model model, final RedirectAttributes redirectAttributes){  

The BindingResult argument needs to be positioned right after our form backing object – it’s one of the rare cases where the order of the method arguments matters. Otherwise we’ll run into the following exception :


java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply:
public java.lang.String controller.EmployeeController.addEmployees(org.springframework.validation.BindingResult,entity.Employee,org.springframework.ui.Model,org.springframework.web.servlet.mvc.support.RedirectAttributes)


To correct the above exception, just change order of the parameter, where your binding result parameter has to be just after the ModelAttribute as below

      @RequestMapping(value="/addEmployee", method=RequestMethod.POST)  
      public String addEmployees( @ModelAttribute("employee") Employee employee,  
                BindingResult result, Model model, final RedirectAttributes redirectAttributes){  


Happy Programming...!!!

Sunday, August 2, 2015

Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource


Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]

I encountered this error when, i was doing a sample web application, using Annotations fully. Below is the sample snippet, which triggered the above issue. Once i registered the AppConfig to the AnnotationConfigWebApplicationContext, i added context.refresh, to fully process the class, which results in the above exception, when i removed the context.refresh, everything seems to be fine, but when i add it back, i am getting the same exception, so what triggers the issue?

public class AppInitializer implements WebApplicationInitializer{
 
 private static final String MAPPING_URL = "/";

 public void onStartup(ServletContext servletContext) throws ServletException {
  AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
  context.register(AppConfig.class); 
  servletContext.addListener(new ContextLoaderListener(context));
  context.refresh();
  ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new CustomDispatcherServlet(context));
  dispatcher.setLoadOnStartup(1);
  dispatcher.addMapping(MAPPING_URL);  
 } 
 
}

As per DispatcherServlet Constructor as specified here

  • If the given context does not already have a parent, the root application context will be set as the parent.
  • If the given context has not already been assigned an id, one will be assigned to it
  • ServletContext and ServletConfig objects will be delegated to the application context
  • FrameworkServlet.postProcessWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext) will be called
  • Any ApplicationContextInitializers specified through the "contextInitializerClasses" init-param or through the
  • FrameworkServlet.setContextInitializers(org.springframework.context.ApplicationContextInitializer...) property will be applied.
  • refresh() will be called if the context implements ConfigurableApplicationContext

If the context has already been refreshed, none of the above will occur, under the assumption that the user has performed these actions (or not) per their specific needs.

So for the DispatcherServlet, you modify the code as below

AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
context.register(WebConfig .class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new CustomDispatcherServlet(webContext));

Sample Code of the WebConfig class as shown below.

@Configuration
@Configuration
@EnableWebMvc
@ComponentScan("com.practice")
public class WebConfig extends WebMvcConfigurerAdapter{

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);

}

Happy Programming...!!!

Friday, May 24, 2013

Spring MVC Form Validation with Annotation using Spring Bean Validation Framework

This tutorial walks you through the step by step instructions in order to support and apply validation example in Spring MVC, using Spring Bean Validation Framework, which is part of the Spring Modules project.

So here's my record so I don't forget in future how I did it.

Make sure that you have downloaded the spring-modules-validation-0.8.jar have it in your classpath.

Spring Modules validation provides a bunch of generic validation out of the box for all the tedious, standard stuff - length validation, mandatory fields, valid e-mail addresses etc (details here). And you can plug this straight into your application by using annotations. How? Easy.

Below is the configuration, you have to do in your servlet xml file, where you are defining your validator.





Below is my simple Entity Model class, which deals with product. Since the Name and Description of the Product is a must while presisting the data, i have added an validation constraint through annotation, here you can see i have added @NotBlank for name and description variables, and also the message to be shown to the users when they left it blank.

public class Product{
 
    @Id
    @Column(name="ID")
    @GeneratedValue
 private int id;
 
 @NotBlank(message = "Name should not be empty")
 @Column(name="NAME")
 private String name;
 
 @NotBlank(message = "Description should not be empty")
 @Column(name="DESCRIPTION")
 private String description;
 
 public int getId() {
  return id;
 }
....

Now the Spring Controller
The Bean Validation Framework includes its own Validator implementation, called BeanValidator, we are injecting this into the controller, and it was autowired through the xml configuration which we did in the top.

On submitting the form, we will be routed to the addExpense method, where will call the validate() method by passing in the form bean (expense) and the BindingResult. If there any errors, we will just return the form view name which will show the error message.

@Controller
public class ExpenseController 
{
 @Autowired
 private ExpenseService expenseService;
 @Autowired
 private ExpenseTypeService expenseTypeService; 
 @Autowired
    private Validator validator;
    
    public void setValidator(Validator validator) {
        this.validator = validator;
    }
 
 @RequestMapping("/expenselist")
 public String expenselist(Map map, @ModelAttribute("ExpenseName") String expenseName)
 {
  List expenseTypeList = expenseTypeService.fetchAll();
  
  map.put("expense", new Expense()); 
  map.put("expenseTypeList", expenseTypeList);
  map.put("expenseList", expenseService.fetchAll()); 
  map.put("expenseName", expenseName);
  return "expenselist";
 }
 
 @RequestMapping(value="/addexpense", method=RequestMethod.POST)
 public String addExpense(@ModelAttribute("expense") 
   Expense expense, BindingResult result, RedirectAttributes redirectAttrs)
 {
  validator.validate(expense, result);
  if (result.hasErrors()) { return "expenselist"; }
  
  //System.out.println(expense.getExpenseTypeId());
  System.out.println(expense.getName());
  expenseService.add(expense);
  redirectAttrs.addFlashAttribute("ExpenseName", expense.getName());
  return "redirect:/expenselist.html";
 }
}

Suppose if you are not Injecting the Validator, you can just initilize the valiator as shown below in the controller, rest are same as above
public class ExpenseController 
{
 @Autowired
 private ExpenseService expenseService;
 @Autowired
 private ExpenseTypeService expenseTypeService;

        private BeanValidator beanValidator = new BeanValidator(new AnnotationBeanValidationConfigurationLoader());

}

Below is the screen shot, with the error message shown, when the form is submitted.



The tag form:errors will help us to show the error message to the users

Expense :


Amount :


ExpenseType :


Date Incurred :


Description :





Happy programming.

Saturday, May 11, 2013

Spring MVC - FlashAttributes

One of the common problem in a web based application, involving form submission is mutilple form submission, re-entering submitting the form on browser refresh, pop-up alert asking for re-submission of the form, if we press the back button. To overcome the above problem, we will be doing a redirect after a form submission instead of the forward. Doing a redirect causes the browser to do a new GET request and load the page, and provides a solution to the above mentioned problem, but comes with one serious problem, where we will be missing the vital data of request parameters and attributes.

To overcome this problem, Spring MVC comes with FlasAttributes. Flash attributes provide a way for one request to store attributes intended for use in another. This is most commonly needed when redirecting — for example, the Post/Redirect/Get pattern. Flash attributes are saved temporarily before the redirect (typically in the session) to be made available to the request after the redirect and removed immediately.

Spring MVC has two main abstractions in support of flash attributes. FlashMap is used to hold flash attributes while FlashMapManager is used to store, retrieve, and manage FlashMap instances.

Flash attribute support is always "on" and does not need to enabled explicitly although if not used, it never causes HTTP session creation. On each request there is an "input" FlashMap with attributes passed from a previous request (if any) and an "output" FlashMap with attributes to save for a subsequent request. Both FlashMap instances are accessible from anywhere in Spring MVC through static methods in RequestContextUtils.

Here in the below sample code, we are adding the expense details to the DB and redirecting back to the form, with the message saying the following expense have been added to the list.




Flash attributes added via RedirectAttributes are automatically propagated to the "output" FlashMap. Here we have added RedirectAttributes redirectAttrs to your Spring controller’s method addExpense. The addFlashAttribute method automatically add the given parameter to the output flash map and pass it to the subsequent requests.

Before your handler method will be called, Spring Framework will populate the Model with the available Flash Attributes – at this point value passed from addExpense will become a model attribute for the expenselist method, and the same can be added to the map, to return it to the presentation layer, to get it displayed. Here the from the redirect,it comes to the expenselist method, where it will reach as a ModelAttribute and the same have been defined in the method signature with the respective type.

@RequestMapping("/expenselist")
public String expenselist(Map map, @ModelAttribute("ExpenseName") String expenseName)
{
 List expenseTypeList = expenseTypeService.fetchAll();
 
 map.put("expense", new Expense()); 
 map.put("expenseTypeList", expenseTypeList);
 map.put("expenseList", expenseService.fetchAll()); 
 map.put("expenseName", expenseName);
 return "expenselist";
}

@RequestMapping(value="/addexpense", method=RequestMethod.POST)
public String addExpense(@ModelAttribute("expense") 
  Expense expense, BindingResult result, RedirectAttributes redirectAttrs)
{
 //System.out.println(expense.getExpenseTypeId());
 //System.out.println(expense.getName());
 expenseService.add(expense);
 redirectAttrs.addFlashAttribute("ExpenseName", expense.getName());
 return "redirect:/expenselist.html";
}

Happy Programming...!!!

Saturday, May 4, 2013

Integrate ExtJs DataGrid with Spring MVC

Sencha ExtJs is one of the rapidly growing standard for business-grade web application development, which have been used widely as presentation layer. Lets see, how we can intergrate the ExtJs with Spring MVC.

You can download ExtJs from here - Download Extjs

In this example, we are going to populate the list of medicine name available in ExtJS DataGrid.

Below is the Medicine Business clas, Simple POJO. For this example forget about the dealers in the class.
public class Medicine extends BaseObject 
{ 
 private String company;
 private String code;
 private String description; 
 private Set dealers;

        //Relevant Setters and Getters

}

Since the JSON is the most popular way of providing input to ExtJs DataGrid, we are going define the DataStore first, which reads the data from the server through the HttpProxy call, and we use the JsonReader to read a server response that is sent back in JSON format

var store = new Ext.data.Store({
  proxy: new Ext.data.HttpProxy({
   url: '/getmedicine.htm'
  }),
  reader: new Ext.data.JsonReader({
   root:'medicineJson'
  },
  [{name: 'id'}, 
   {name: 'name'}, 
   {name: 'description'},
   {name: 'company'}
  ])
 }); 

And our controller, which return the relevant Medicine data in JSON Format. To return the output from the controller in JSON format, we will be using the classes net.sf api's. Make sure that you have the below jars files in your classpath

json-lib-2.4-jdk15.jar
json-lib-ext-spring-1.0.2.jar
ezmorph-0.8.1.jar

public class DataServiceController implements Controller
{
 private MedicineDao medicineDao;
 
 
 public MedicineDao getMedicineDao() {
  return medicineDao;
 }

 public void setMedicineDao(MedicineDao medicineDao) {
  this.medicineDao = medicineDao;
 }

 public ModelAndView handleRequest(HttpServletRequest request,
   HttpServletResponse response) throws Exception 
 {
  List medicineList = this.getMedicineDao().getAll();
  
  JsonConfig config = new JsonConfig();
  config.setExcludes(new String[] {"dealers" });
  config.setIgnoreDefaultExcludes(false);
  config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  
  //JSONObject obj = JSONObject.fromObject(medicineList, config);
  JSONArray obj = JSONArray.fromObject(medicineList, config);
  
  ModelMap modelMap = new ModelMap();
  //modelMap.addAttribute("medicineList" , obj);  
  //return new ModelAndView("jsonView", modelMap);
  modelMap.addAttribute("medicineJson", obj);
  //modelMap.addAttribute("medicineList" , medicineList);
  return new ModelAndView("jsonView", modelMap);
 }

}

Below is the entire content of medicinelist.js file defined in jsp, which includes the definition of the DataGrid.

Ext.onReady(function(){ 

 var store = new Ext.data.Store({
  proxy: new Ext.data.HttpProxy({
   url: '/getmedicine.htm'
  }),
  reader: new Ext.data.JsonReader({
   root:'medicineJson'
  },
  [{name: 'id'}, 
   {name: 'name'}, 
   {name: 'description'},
   {name: 'company'}
  ])
 }); 

 // row expander
  
    
    var gridBooks = new Ext.grid.GridPanel({
        store: store,
        width: 500,
        height: 500,        
        title: 'Medicine List',
        renderTo: 'medlist',
        cm: new Ext.grid.ColumnModel({
            defaults: {
                sortable: true
            },
            columns: [               
                {header: "Id", dataIndex: 'id'},
                {header: "Medicine Name", dataIndex: 'name'},
                {header: "Description", dataIndex: 'description'},
                {header: "Company" , dataIndex: 'company', renderer:renderCompany}
            ]
        }),       
        listeners: {
      rowClick: function(grid, rowI, event) {
       //alert("You Clicked Row " + rowI);
       //alert("Medicine Name" + grid.getStore().getAt(rowI).get('name'));
      }
     }
    });

    store.load();
});

Make sure that you have relevant extjs .js and .css file in your relevant, which can be downloaded from You can download ExtJs from here - Download Extjs










Happy programming ...!!!

Saturday, April 13, 2013

Spring Tiles Integration

Suppose if your web page has a standard header, footer and only center content will be changed, it is very difficult to hardcode in each and every webpage and if later if any changes is needed then all pages needs to be updated with the relevant details. Here comes Tiles which helps you to templatize the common items and include it in each and every page.

Lets see how we are going to integrate the Titles in our Spring MVC. Our application layout will have the standard header and footer across all web pages, where only the center content will be changed.

Make sure that you have the following jars files included in your lib

commons.beanutils.jar
commons-digester-2.1.jar
commons-logging-1.1.jar
tiles-api-2.0.4.jar
tiles-core-2.0.4.jar
tiles-jsp-2.0.4.jar

Configuring titles framework in Spring MVC

 
    
    


   
       
          /WEB-INF/tiles-def.xml
        
   
	

Using the definitions attribute, we need to specify the tiles definition file. The tiles-def.xml definitions are below, the file should be located under WEB-INF directory in your application. In the tiles-def.xml we need to define our base layout structure. The base layout we are building contatins the attributes title, header, body and footer. We need to create the baseLayout.jsp and place it under /WEB-INF/titles, the template baseLayout.jsp, will contain the different segments of a web page, header, body and footer.


   
      
          
      
      		
   
   
      
      			
   	
   
      	
      	
   	


BaseLayout.jsp - View Template
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
..
..
<tiles:insertAttribute name="title" ignore="true"/>






..

To display the views, we use the ResourceBundleViewResolver. By default the view.properties will be used to store
the key value pairs

hello.(class)=org.springframework.web.servlet.view.tiles2.TilesView
hello.url=base

dealerlist.(class)=org.springframework.web.servlet.view.tiles2.TilesView
dealerlist.url=dealer

Controller File
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("dealerList" , dealerList);		
return new ModelAndView("dealerlist", modelMap);

The base, delear in view.properties refers to the definition name in the tiles-def.xml file. The hello and dealerlist refers to the modelview name sent by your controller.

That's all you have integrated the Tiles with Spring MVC

Happy Programming...!!!

Thursday, April 4, 2013

Spring MVC - Bind an input field to a Date property

For request parameters representing string, number, and boolean values, the Spring MVC container can bind them to typed properties out of the box. Suppose you have the Date Input field, and the bean property is defined as Date Type, when container tries to bind it will throw exception

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

So we need to create a binding between your input field and your bean's Date property. Spring provides a PropertyEditor named CustomDateEditor which you can configure to convert an String to respective date format. You typically have to register it in a @InitBinder method of your controller

@InitBinder
public void initBinder(WebDataBinder binder)
{
    //binder.registerCustomEditor(ExpenseType.class, new ExpenseTypePropertyEditor());
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

Happy Programming..!!!

Sunday, January 27, 2013

InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode

If you have enabled the filter OpenSessionInViewFilter, for fetching the lazily loaded data, you can typically see the below error message, when trying to do a persistence operation outside of Spring-managed transaction.

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
org.springframework.orm.hibernate3.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1186)
org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:696)
org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:694)

OpenSessionInViewFilter has an alternative "deferred close mode", to resolve the issue. This can be activated through setting the singleSession=false. This will use one Session per transaction, but keep each of those open until view rendering has been completed. As no Session will be reused for another transaction in this case, there is no risk of accidentally flushing inconsistent state


  OpenSessionInViewFilter
  org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  
     singleSession     false  


Happy Programming !!!

Saturday, November 24, 2012

Hibernate Error : java.lang.NoClassDefFoundError: org/objectweb/asm/Type

This is the common error we will be getting when working on the Hibernate.
Caused by: java.lang.NoClassDefFoundError: org/objectweb/asm/Type
 at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180)
 at net.sf.cglib.core.KeyFactory.(KeyFactory.java:66)
 at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)
 at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:117)
 at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(CGLIBProxyFactory.java:43)
 at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:162)
 at org.hibernate.tuple.entity.AbstractEntityTuplizer.(AbstractEntityTuplizer.java:135)

This was due to the one of the asm jar missing in your /WEB-INF/lib directory. You can download it from their official directory ASM, or you can use the springsource object jar, which can be downloaded here

Happy Programming !!!

Thursday, September 13, 2012

How to configure multiple handler mappings in Spring MVC

DispatcherServlet is Spring MVC's implementation of the front controller pattern. Essentially, it's a servlet that takes the incoming request, and delegates processing of that request to one of a number of handlers, to determine which controller the request should be sent. When the client request reaches the Dispatcher Servlet, the Dispatcher Servlet tries to find the appropriate Handler Mapping object to map the request.
Spring distribution contains the following Handler mappings

BeanNameUrlHandlerMapping
SimpleUrlHandlerMapping
ControllerClassNameHandlerMappign
CommonsPathMapHandlerMapping

All of the above can be found at org.springframework.web.servlet package. You can use any one of these handler mappings in your application by just configuring it in the application context file. If no handler have been configured, by default BeanNameUrlHandlerMapping will be used. And also you can configure more than one handlers in your application. In case of multiple handlers, we have to guide our DispatcherServlet by setting the order property of the handler mappings. Every handler mapping implements Ordered interface. So all we have to do is set the order
property, where the lower order value has the higher property.


<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/edit/hello.htm">helloController</prop>
<prop key="/hello.htm">helloController</prop>
</props>
</property>
<property name="interceptors">
<list>
<ref bean="myinterceptor" />
</list>
</property>
<property name="order" value="0"/>
</bean>

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="order" value="1"/>
</bean>

<bean name="/adddealer.htm" class="com.practice.web.AddDealerFormController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="dealer"/>
<property name="commandClass" value="com.practice.domain.Dealer"/>
<property name="successView" value="hello.htm"/>
<property name="dealerManager" ref="dealerManager"/>
</bean>


In the above example, we have configured 2 handler mappings BeanNameUrlHandlerMapping the default one and the simplest one to, and SimpleUrlHandlerMapping, and set the priority order. So the DispatcherServlet will consult each one of the them in the order according to their priority set by
the order priority. If a HandlerMapping does not return an appropriate HandlerExecutionChain , the next available HandlerMapping will be consulted. If no appropriate result is found after inspecting all HandlerMappings an exception will be thrown.

Happy Programming !!!