使用注解之前的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!--id是请求路径-->
<bean id="/test" class="com.tv189.controller.HelloController" />
</beans>
外加一个类(实现了Controller接口)
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("msg","你好,李焕英!");
mv.setViewName("testindex");
return mv;
}
}
使用注解后的配置
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.tv189.controller" />
<!--自动开启BeanNameUrlHandlerMapping,SimpleControllerHandlerAdapter
mvc:annotation-driven 这个配置写上后会自动开启上面的两个组件
并且自动注入-->
<mvc:annotation-driven />
<!--让springMVC不去处理静态文件 如:.css .js .html .mp3 .mp4 让这些文件不走下面的过滤-->
<mvc:default-servlet-handler />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="suffix" value=".jsp" />
<property name="prefix" value="/WEB-INF/jsp/" />
</bean>
</beans>
类文件
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","Hello,springMVC");
return "testindex";
}
}
@Controller 相当于声明类实现了Controller类 并交给了spring管理
等价与
implements Controller +
@RequestMapping("/test") 等价于
这里可以看出在不使用注解时每写一个请求我们需要写一个实现Controller的类 并配置bean 如: