1. 导入 jar
2. 在 web.xml 中配置前端控制器 DispatcherServlet
2.1 如果不配置<init-param>,它会找/WEB-INF/<servlet-name>-servlet.xml
<servlet>
<servlet-name>jqk</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定SpringMVC配置文件的位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 配置优先级 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jqk</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3. 在 src 下新建 springmvc.xml
3.1 引入 xmlns:mvc 命名空间
3.2 若将DispatcheServlet请求映射设置为/,则SpringMVC将捕获WEB容器的所有请求,包括静态资源的请求,SpringMvc会将它们当成一个普通的请求处理,那么将会出现因找不到对应的处理器将导致错误。配置<mvc:resoucres >可以解决这个问题,其中“/xxx/**”代表凡是以满足/xxx/...格式的请求都会在/xxx/目录下去搜寻
<?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"
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="com.bjsxt.controller"></context:component-scan>
<!-- 注解驱动(相当于扫描了下面两个类) -->
<!-- org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping -->
<!-- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
</beans>
4. 编写控制器类
4.1 RequestMapping是一个用来处理请求地址映射的注解,默认值赋值为value,即要拦截的请求
4.2 return的值为要跳转的路径
@Controller
public class DemoController {
@RequestMapping("demo")
public String demo(){
System.out.println("执行 demo");
return "main.jsp";
}
@RequestMapping("demo2")
public String demo2(){
System.out.println("demo2");
return "main1.jsp";
}
}