链接:https://download.csdn.net/download/qq_60567426/88795164
1、SpringMVC是一个基于Spring框架的Web MVC(模型-视图-控制器)框架。
流程:
①创建web-app后,向pom.xml文件导入Springmvc和servlet
目录如下:
java
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency><groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version></dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat9-maven-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
②写下一个Controller类
UserController.java
java
package com.Baike.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@RequestMapping("/save")
@ResponseBody
public String save() {
System.out.print("123456");
return "{'id':'1'}";
}
}
③写一个Config文件,让Spring能扫描到Controller
SpringMvcConfig.java
java
package com.Baike.Config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.Baike.Controller")
public class SpringMvcConfig {
}
④:定义一个servlet容器启动的配置类,在里面加载spring的配置。
Servletboot.java
java
package com.Baike.Config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
public class Servletboot extends AbstractDispatcherServletInitializer{
//加载Springmvc容器配置
@Override
protected WebApplicationContext createServletApplicationContext() {
// TODO Auto-generated method stub
AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
//设置哪些请求归属Springmvc处理
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
//加载spring容器配置
@Override
protected WebApplicationContext createRootApplicationContext() {
// TODO Auto-generated method stub
return null;
}
}
最后访问链接http://localhost/test/save
就能访问到资源,链接结构为localhost/你的项目名/controller的requestmapping名
整个项目结构为:
参数传递:
传递方式:
①普通传参(这种传参需要顺序一一对应)
http://localhost/test/user/save?name='你好'&age=16
②注解传参(这种传参可以让参数不按照顺序,在参数前面加入@RequestParam("后端的参数key值"))
http://localhost/test/user/save?age=20&name='三级'
③pojo(实体对象)传参
④集合传参(传参需要键值key与括号里面参数名一样)
⑤JSON传参
向pom.xml添加以下代码,让能识别到json格式
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
向SpringMvc配置文件中加入@EnableWebMvc
⑥ 日期型参数传递@DateTimeFormat
⑦类型转换Convert