SpringMVC学习1
TestController
package cn.edu.cque.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @ClassName TestController
* @Description 控制器类, 是控制器的集合, 类中的方法才是真正的控制器
**/
@Controller
@RequestMapping("/test")
public class TestController {
/***
* @RequestMapping注解的作用就是将某一个URL地址和处理该请求的方法(控制器)绑定在一起
* 1 当前控制器处理的请求路径为类的路径加上方法的路径:/test/demo01
* 2 @RequestMapping不指定路径时默认是/
* 3 路径中开头的/可以省略
* 4 可以配置多个地址
*
**/
@RequestMapping({"/demo01", "/demo02"})// /demo
public String test() {
System.out.println("TestController的test()");
return "index";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--配置核心控制器-->
<servlet>
<servlet-name>DispatchServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- contextConfigLocation 不能写错
classpath:不能省略
spring-mvc的配置文件本质上就是一个Spring配置文件
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatchServlet</servlet-name>
<!-- 当三种匹配模式都没有匹配到时,会交给/处理
注意/ 和/*的区别
*.do
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-mvc.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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!-- 注解扫描 -->
<context:component-scan base-package="cn.edu.cque.spring.controller"/>
<!-- 视图解析器
将控制器的返回结果解析成对应的视图(拼接jsp的目录)
-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>