本节实训内容为Spring Web Mvc框架、表单提交、JSON数据转换器
文章目录
新建maven-archetype-webapp项目
不要选择前两天的quickstart项目
导入SpringMvc依赖
pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
配置web.xml
web.xml是web项目的核心配置文件,当tomcat服务器启动时,会先加载web.xml配置文件的内容,dispatchServlet:前端中转控制器,将前端请求对应的路径与后端controller中对应的映射匹配
所以我们需要在web.xml中配置dispatchServlet,并且加载spring-mvc.xml
web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置中转控制器 dispatchservlet-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
创建项目目录
在src/main目录下新建java和resources两个目录并把resources给mark一下
完整项目目录结构如下
配置tomcat
tomcat8.0下载链接:https://pan.baidu.com/s/1AjWr8AO9Im1xYjdYau09Cg
提取码:8888
下载tomcat后解压
点击Configure…选中tomcat文件夹路径,按下图红框进行配置
选择Deployment,点击+出现Artifact,选择exploded即可
如果没有Artifact就检查pom.xml文件和项目是否为webapp项目
运行项目
配置spring-mvc.xml
在resources目录下新建一个spring-mvc.xml文件
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"
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">
<context:component-scan base-package="com.qianfeng.controller">
</context:component-scan>
</beans>
UserController.java
@Controller
public class UserController {
//定义后台映射 hello
@RequestMapping("/hello") // 返回的String都是页面
public String