Spring MVC 配置Controller详解

在SpringMVC中,对于Controller的配置方式有很多种,如下做简单总结

 第一种 URL对应Bean
如果要使用此类配置方式,需要在XML中做如下样式配置:

<!-- 表示将请求的URL和Bean名字映射-->  
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>  
<bean name="/hello.do" class="test.HelloController"></bean> 

以上配置,访问/hello.do就会寻找ID为/hello.do的Bean,这类配置应用型不太广,网站大了,controller多了的话,这种方式要累死

第二种 为URL分配Bean
使用一个统一配置集合,对各个URL对应的Controller做关系映射:

    <!-- 最常用的映射配置方式 -->  
    <!-- <prop key="/hello*.do">helloController</prop>-->  
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">  
     <property name="mappings">  
      <props>  
       <prop key="/hello.do">helloController</prop>  
      </props>  
     </property>  
    </bean>  
    <bean name="helloController" class="test.HelloController"></bean>  

此类配置还可以使用通配符,访问/hello.do时,Spring会把请求分配给helloController进行处理,这类方式比第一种好一点,可以使用通配符,进行通用性匹配,不过实用性也不是很大

第三种  注解@controller

首先需要在配置文件配置一下注解:

<!-- 启用 spring 注解 -->  
<context:component-scan base-package="test" />  ----扫描test中所有@controller标记
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> 

在编写类上使用注解@org.springframework.stereotype.Controller标记这是个Controller对象
使用@RequestMapping("/hello.do")指定方法对应处理的路径,这里只是简单示例,会有更复杂配置

代码类如下:

    package test;  
    import java.util.Date;  
    import javax.servlet.http.HttpServletRequest;  
    import javax.servlet.http.HttpServletResponse;  
    import org.springframework.web.bind.annotation.RequestMapping;  
    // http://localhost:8080/spring/hello.do?user=java  
    @org.springframework.stereotype.Controller  
    public class HelloController{  
        @SuppressWarnings("deprecation")  
        @RequestMapping("/hello.do")  
        public String hello(HttpServletRequest request,HttpServletResponse response){  
            request.setAttribute("user", request.getParameter("user") + "-->" + new Date().toLocaleString());  
            return "hello";  
        }  
    }  
原文地址:https://www.cnblogs.com/shilin000/p/5070911.html