Spring Web MVC应用(注解方式实现)

1、要使用RequestMappingHandlerMapping组件

@RuquestMapping("/login.do"):该标记用在Controller业务方法前

2、Controller组件的编写和配置跟之前xml配置时不同,取消了实现Controller接口的约定,业务方法名也可以改变,还可以改变参数列表,允许我们按需要自定义参数列表,返回值类型可以使ModelAndView或者String

例如:public ModelAndView || String   XXX( 自定义参数列表:根据需要定义HttpServletRequest,HttpServletResponse,HttpSession等对象参数,参数列表也可以为空){

       }

注意:这样使用需要将Controller组件扫描到spring容器中,必须要使用@Controller标记

示例:

(1)web.xml中我们配置的DispatcherServlet核心控制器不需要做改变

(2)但是我们需要将之前使用handlermapping换成另一种组件,也就是RequestMappingHandlerMapping组件。

这里有一种简化配置的方法,这样就可以将之前的组件换成RequestMappingHandlerMapping组件。

 

 <!-- 通过这种方式可以将以注解方式构建MVC框架所需的配置一次性加上 -->
    <mvc:annotation-driven />

 

记得加上mvc命名空间

(3)记得开启spring容器扫描

 <context:component-scan base-package="com.zlc"/>

完整的application.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" >
    
    <!-- 开启容器扫描 -->
    <context:component-scan base-package="com.zlc.controller"/>
    
    <!-- 通过这种方式可以将以注解方式构建MVC框架所需的配置一次性加上 -->
    <mvc:annotation-driven />
    
    <!-- 配置ViewResolver -->
    <bean id="viewresolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    
</beans>

 相应Controller类:

//将组件扫描到Spring容器
@Controller
public class HelloController{
    //添加请求映射
    @RequestMapping("/hello.do")
    public ModelAndView execute() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("hello");
        mav.getModel().put("msg","注解版信息");
        return mav;
    }
}

 

posted @ 2018-08-03 16:41  梦里下起了雪  阅读(253)  评论(0编辑  收藏  举报