1.导入包,准备web的项目环境
pom.xml:packaging: war spring-webmvc
<packaging>war</packaging>
<dependencies>
<!-- 导入springMVC依赖包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
</dependencies>
2.配置web.xml中的前端控制器
说明:前端控制器,既是帮我们找handle(我们要访问的方法-类似之前的doGet\doPost)的控制器
在前端控制器中,初始加载mvc的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ServletWithoutMappingInspection, WebProperties -->
<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"></web-app>
web.xml:
<servlet>
<servlet-name>mvc</servlet-name>
<!-- 前端控制器的配置,找目标handler-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<!-- 访问任何路径都会先经过url:/-->
<url-pattern>/</url-pattern>
</servlet-mapping>
handle在这:
package com.qf.controller;
public class UserController {
public String show(){
}
}
3.mvc配置文件的设置
a.扫描控制层的注解
b.开启注解
c.视图解析器,去解析渲染页面
resouse: web.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!--1.指定扫描控制器的包的注解-->
<context:component-scan base-package="com.qf.controller"></context:component-scan>
<!--2.开启注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 静态资源访问-->
<!-- 在controller中生成一个handler,该handler用于解决静态资源访问
访问优先级最低,其他路径都访问不到的时候就访问/**-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!-- 3.视图解析器配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- return /ok.jsp-->
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
4.后台控制器:
a.控制层组件
b.映射路劲的配置
@Controller //控制器组件 类似于 <bean id="" class="com.qf"/>
@RequestMapping("/user") /*请求映射路径,handler*/
public class UserController {
@RequestMapping("/show")
public String show(){
System.out.println("show...");
return "ok";
}
}
webapp: ok.jsp
<body>
OK...!
</body>