1.修改IndexController
在类前面加上@Controller 表示该类是一个控制器
在方法handleRequest 前面加上 @RequestMapping("/index") 表示路径/index会映射到该方法上
注意:不再让IndexController实现Controller接口
1 package controller; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.servlet.ModelAndView; 9 10 @Controller 11 public class IndexController { 12 @RequestMapping("/index") 13 public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { 14 15 ModelAndView mav = new ModelAndView("index"); 16 mav.addObject("message", "Hello Spring MVC——————注解方式"); 17 return mav; 18 } 19 }
2.修改springmvc-servlet.xml
去掉映射相关的配置,因为已经使用注解方式了
增加:<context:component-scan base-package="controller" />
表示从包controller下扫描有@Controller注解的类
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 9 10 <context:component-scan base-package="controller" /> 11 <bean id="irViewResolver" 12 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 13 <property name="prefix" value="/WEB-INF/page/" /> 14 <property name="suffix" value=".jsp" /> 15 </bean> 16 17 </beans>
3.测试