How to map requests to Controllers

 

As we known, when associating a request with a specific controller, DispatcherServlet consults a handler mapping bean. Handler mappings typically map a specific controller bean to a URL pattern. Spring MVC offers several handler mapping implementations to choose form. All of Spring MVC's handler mappings implement the org.springframework.web.servlet.HandlerMapping interface:

  • BeanNameUrlHandlerMapping---Maps controllers to URLs that are based on the controllers' bean name.
  • SimpleUrlHandlerMapping---Maps controllers to URLs using a property collection defined in the context configuration file.
  • CommonsPathMapHandlerMapping---Maps controllers to URLs using sourcelevel metadata placed in the controller code.

DispatcherServlet defaults to use BeanNameUrlHandlerMapping. So, you shouldn't have to declare it explicitly in your context configuration file. If it's necessary ,you can declare it in your context configuration file like this:

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

The BeanNameUrlHandlerMapping is quite simple, it creates a coupling between presentation-layer URLs and your controller names. But we encourage you to consider one of the other handler mappings, such as SimpleUrlHandlerMapping.

SimpleUrlHandlerMapping lets you map URL patterns directly to controllers without having to name your beans in a special way. For example:

<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="mappings">

<props>

     <prop key="/1.htm">controller1</prop>

     <prop key="/2.htm">controller2</prop>

     <prop key="/3.htm">controller3</prop>

</props>

</property>

</bean>

SimpleUrlHandlerMapping's mappings property is wired with a java.util.Properties using <props>.The key attribute of each <prop> element is a URL pattern.

OK, now we will look at the final handler mapping---CommonsPathMapHandlerMapping. This handler mapping considers source-level metadata placed in a controller's source code to determine the URL mapping. In particular the metadata is expected to be an org.springframework.web.servlet.handler.commomsattributes.PathMap attribute compiled into the controller using the Jakarta Commons Attributes compiler. For example:

<bean id="urlMapping" class="org.springframework.web.servlet.handler.metadata.CommonsPathMapHandlerMapping"

/>

 

/**

 *@@org.springframework.web.servlet.handler.commonsattributes.PathMap("/1.htm")

 */

public class controller1 extends AbstractCommandController

{

}

Finally, you'll need to set up your build to include the Commons Attributes compiler so that the attributes will be complied into our application code.

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值