第一步:在web.xml中配置中央控制器
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 第一步 配置中央控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--struts习惯使用/*,在springmvc不好用-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
第二步:在springmvc-servlet.xml中配置相关文件
springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!--第一步 mvc的注解驱动 -->
<!-- <mvc:annotation-driven />-->
<!--
加载的时候到指定的包下面寻找有注解的类 ,一旦有扫描器的定义,<mvc:annotation-driven
/>不需要,扫描器已经有了注解驱动的功能
-->
<context:component-scan base-package="com.mth.springmvc"></context:component-scan>
<!-- 配置 ViewResolver试图解析器-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀指定文件夹的路径-->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
第二步 :Controler配置及代码
代码:
package com.mth.springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author 注解controler
*
*/
@RequestMapping("/test") //controler命名空间或者 唯一标识
@Controller
// 用来标注当前类是springmvc的控制层的类
public class TestControler {
/**
* 方法的返回值代表ModelAndView中的ViewName
*
* @return
*/
@RequestMapping("/hello.do")// 用来访问控制层方法的注解
public String hello() {
System.out.println("mth=================");
return "index";
}
}
访问的时候直接输入:
http://localhost:8088/Spring_MVC_2/test/hello.do