SpringMVC配置文件内容
<?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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包,让指定包下的注解生效-->
<context:component-scan base-package="com.yyl"/>
<!--让SpringMVC不处理静态资源:例如css,js,html请求,不走SpringMVC请求 -->
<mvc:default-servlet-handler/>
<!--
配置注解驱动:可以自动实现HandlerMapping以及HandlerAdapter的注入
-->
<mvc:annotation-driven/>
<!--
添加视图解析器:
DispatcherServlet给他的ModelAndView
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
使用注解使一个普通类变成Controller
@Controller
public class HelloController {
public String hello(Model model){
//该方法的返回值必须为String,返回值会被视图解析器处理
//封装数据
model.addAttribute("msg","Hello,SpringMVC annotation!");
return "hello";
}
}
为方法添加url请求以及多级请求
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping("/h1")
public String hello(Model model){//该方法的返回值必须为String,返回值会被视图解析器处理
//封装数据
model.addAttribute("msg","Hello,SpringMVC annotation!");
return "hello";
}
}
【注】:
- 在类上声明@RequestMapping时,代表类级别的url请求,说明请求指向该类下
- 在对应方法上声明@RequestMapping时,相应的url就具体到对应的方法
- 在给出的例子中,想要访问到hello()方法就需要加入url的请求为 /hello/h1
使用注解实现Controller的好处
使用注解时,一个Controller类下面可以写多个请求方法,这是它相对于使用接口来实现Controller的优点
配置总结
SpringMVC配置的三大件:
- HandlerMapping(处理器映射器)
- HandlerAdapter(处理器适配器)
- ViewResolver(视图解析器)
但是在注解中,只要开启:<mvc:annotation-driven/>
上述1,2两项就会被隐式地注入,就不需要再配置一遍了