一,SpringMVC常用配置
1.springmvc默认加载的配置文件是WEB-INF下的springmvc-servlet.xml,而我们通常将配置文件放在项目的资源目录中,即classpath下,因此需要配置springmvc加载的配置文件地址。
将配置文件转移至resources中,改名,并修改web.xml:
2.上面的配置中所应用的处理器映射器、处理器适配器以及视图解析器都是默认的,可以修改为注解的使用方式。
在springmvc的配置文件中添加配置:
<!--注解方式的处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!--视图解析器
通过逻辑视图:index
视图解析器解析逻辑视图(解析出物理视图):prefix(前缀)+逻辑视图+suffix(后缀)
解析物理视图:/index.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
注:注解方式的处理器映射器和处理器适配器的配置可以合并为一个配置:
<mvc:annotation-driven/>
3.在注解方式的配置下,controller的写法将变得非常简单:
@Controller
public class TestController {
@RequestMapping("/test1") // 为该方法配置访问路径
public String test1() {
System.out.println("Hello,SpringMVC!");
return "index";
}
@RequestMapping("/test2")
public String test2() {
System.out.println("Hello,test2!");
return "index";
}
}