基于注解的控制器
控制器不用再实现Controller接口,通过注解类型来描述。创建Hello2Controller
package com.game.controller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /**Controller表示该类是一个控制器*/ @Controller public class Hello2Controller { private static final Log logger = LogFactory.getLog(Hello2Controller.class); /**用来映射请求的url和请求的方法*/ @RequestMapping(value="/hello") public ModelAndView hello() { // TODO Auto-generated method stub logger.info("hello方法被调用"); ModelAndView mv = new ModelAndView(); //添加模型数据,可以是任意的pojo对象 mv.addObject("message", "Hello Spring MVC"); //设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面 mv.setViewName("/WEB-INF/views/welcome.jsp"); return mv; } }
修改springmvc.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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 配置handler,映射/hello请求 <bean name="/hello" class="com.game.controller.HelloController"></bean>--> <!-- 处理映射器将bean的name作为url进行查找,需要在配置handler时指定name(即url)--> <!-- <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>--> <!-- 所有适配处理器都要实现HandlerAdapter接口 --> <!-- <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>--> <!-- spring可以自动去扫描base-pack下边的包或者子包下的java类,如果有扫描到spring相关的注解类,则把这些类注册为spring的bean --> <context:component-scan base-package="com.game.controller"></context:component-scan> <!-- 配置annotation类型的处理映射器 ,它根据请求查找映射--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <!-- 配置annotation类型的处理适配器 ,完成方法的调用--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean> </beans>
最后附件源码
http://pan.baidu.com/s/1i436mZr