一、请求参数
请求路径设置好后,只要确保页面发送请求地址和后台Controller类中配置的路径一致,就可以接收到前端的请求,接收到请求后,如何接收页面传递的参数?
关于请求参数的传递与接收是和请求方式有关系的,目前比较常见的两种请求方式为:
-
GET
-
POST
针对于不同的请求前端如何发送,后端如何接收?
1.1 环境准备
-
创建一个Web的Maven项目
-
pom.xml添加Spring依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.itheima</groupId> <artifactId>springmvc_03_request_mapping</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</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>tomcat7-maven-plugin</artifactId> <version>2.1</version> <configuration> <port>80</port> <path>/</path> </configuration> </plugin> </plugins> </build> </project>
-
创建对应的配置类
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer { protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringMvcConfig.class}; } protected String[] getServletMappings() { return new String[]{"/"}; } protected Class<?>[] getRootConfigClasses() { return new Class[0]; } } @Configuration @ComponentScan("com.itheima.controller") public class SpringMvcConfig { }
-
编写UserController
@Controller public class UserController { @RequestMapping("/commonParam") @ResponseBody public String commonParam(){ return "{'module':'commonParam'}"; } }
-
编写模型类,User和Address
public class Address { private String province; private String city; //setter...getter...略 } public class User { private String name; private int age; //setter...getter...略 }
最终创建好的项目结构如下:
1.2 参数传递
GET发送单个参数
发送请求与参数:
http://localhost/commonParam?name=itcast
另外: 对于PostMan如何觉得字小不好看,可以使用 ctrl+=
调大, ctrl+-
调小。
接收参数:
@Controller public class UserController { @RequestMapping("/commonParam") @ResponseBody public String commonParam(String name){ System.out.println("普通参数传递 name ==> "+name); return "{'module':'commonParam'}"; } }
GET发送多个参数
发送请求与参数:
http://localhost/commonParam?name=itcast&age=15
接收参数:
@Controller public class UserController { @RequestMapping("/commonParam") @ResponseBody public String commonParam(String name,int age){ System.out.println("普通参数传递 name ==> "+name); System.out.println("普通参数传递 age ==> "+age); return "{'module':'commonParam'}"; } }
GET请求中文乱码
如果我们传递的参数中有中文,你会发现接收到的参数会出现中文乱码问题。
发送请求: http://localhost/commonParam?name=张三&age=18
控制台:</