版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kaizuidebanli/article/details/83053502
一、 配置DispatcherServlet前端控制器
通过在web.xml配置DispatcherServlet前端控制器, web容器启动时加载,并且进行初始化.
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_4_0.xsd"
version="4.0">
<!-- 配置tomcat加载的spring配置文件的路径 -->
<context-param>
<param-name>contextConfigLocation </param-name>
<param-value>WEB-INF/springDispatcherServlet-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextLocation</param-name>
<param-value>classpath:springDispatcherServlet-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<!--默认匹配所有的请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
二、 页面index.jsp
<body>
<a href="hellowWorld">nihao</a>
</body>
三、 过滤器HellowSpringMVC
package mvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//表明当前的类是一个过滤器
@Controller
public class HellowSpringMVC {
/**
* 1. 使用@RequestMapping注解来映射请求的URL
* 2. 返回值会通过视图解析器解析为实际的物理视图,对于InternalResourceViewResolver,会做如下的解析:
* prefix + 返回值 + suffix,得到实际的物理地址,然后做转发操作
* @return
*/
@RequestMapping("hellowWorld")
public String sayHellow(){
System.out.println("hellow");
return "success";
}
}
四、 配置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:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置自动扫描的包,可以支持注解开发-->
<context:component-scan base-package="mvc" />
<!--配置视图解析器:如何把handler方法返回值解析为实际的物理视图-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"></property>
</bean>
</beans>