SSM4.2【Spring:SpringMVC获取请求数据】

获取基本数据类型、POJO类型、数组类型的请求参数

 

 

 

复制代码
 1 /**
 2      * SpringMVC获取请求数据--基本数据类型参数
 3      * @param username
 4      * @param age
 5      */
 6     @RequestMapping("/save11")
 7     @ResponseBody //不进行页面跳转,以直接响应(http-response响应体)的方式回写数据
 8     public void save11(String username, int age) { //void表示什么数据都不回写,响应体为空;
 9         //形参中age为int,是因为springMVC可以自动实现数据类型转换(单纯web来讲,获取到的应该是字符串)
10         System.out.println(username);
11         System.out.println(age);
12         /*
13         http://localhost:8080/ssm4/user/save11?username=lisi&age=22
14         lisi
15         22
16          */
17     }
18 
19 
20     /**
21      * SpringMVC获取请求数据--POJO类型参数
22      * @param user
23      */
24     @RequestMapping("/save12")
25     @ResponseBody
26     public void save12(User user) {
27         System.out.println(user);
28         /*
29         http://localhost:8080/ssm4/user/save12?username=wangwu&age=24
30         User{username='wangwu', age=24}
31          */
32     }
33 
34     /**
35      * SpringMVC获取请求数据--数组类型参数
36      * @param strArr
37      */
38     @RequestMapping("/save13")
39     @ResponseBody
40     public void save13(String[] strArr) {
41         System.out.println(strArr);
42         System.out.println(Arrays.asList(strArr));
43         /*
44         http://localhost:8080/ssm4/user/save13?strArr=i&strArr=am&strArr=u&strArr=dad
45         [Ljava.lang.String;@3466c2c6
46         [i, am, u, dad]
47          */
48     }
复制代码
复制代码
 1 package com.haifei.domain;
 2 
 3 public class User {
 4 
 5     private String username;
 6     private int age;
 7 
 8     public String getUsername() {
 9         return username;
10     }
11 
12     public void setUsername(String username) {
13         this.username = username;
14     }
15 
16     public int getAge() {
17         return age;
18     }
19 
20     public void setAge(int age) {
21         this.age = age;
22     }
23 
24     @Override
25     public String toString() {
26         return "User{" +
27                 "username='" + username + '\'' +
28                 ", age=" + age +
29                 '}';
30     }
31 }
复制代码

获取集合类型的请求参数

复制代码
 1 /**
 2      * SpringMVC获取请求数据--集合类型参数
 3      *  应用场景1:form.jsp
 4      * @param vo
 5      */
 6     @RequestMapping("/save14")
 7     @ResponseBody
 8 //    public void save14(List<User> userList) { //表单提交这样写是封装不进去的,需要将其包装到一个POJO对象中,
 9 //    一般称为VO对象,有人称为视图对象ViewObject,也有人称为值对象ValueObject
10     public void save14(VO vo) {
11         System.out.println(vo);
12     }
复制代码
复制代码
 1 package com.haifei.domain;
 2 
 3 import java.util.List;
 4 
 5 public class VO {
 6 
 7     private List<User> userList;
 8 
 9     public List<User> getUserList() {
10         return userList;
11     }
12 
13     public void setUserList(List<User> userList) {
14         this.userList = userList;
15     }
16 
17     @Override
18     public String toString() {
19         return "VO{" +
20                 "userList=" + userList +
21                 '}';
22     }
23 }
复制代码
复制代码
 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: yubaby
 4   Date: 2021/7/16
 5   Time: 18:52
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10 <head>
11     <title>form</title>
12 </head>
13 <body>
14 
15     <form action="${pageContext.request.contextPath}/user/save14" method="post">
16         <%--i表明是第几个User对象--%>
17         <input type="text" name="userList[0].username"><br/>
18         <input type="text" name="userList[0].age"><br/>
19         <input type="text" name="userList[1].username"><br/>
20         <input type="text" name="userList[1].age"><br/>
21         <input type="submit" value="提交">
22     </form>
23 
24 </body>
25 </html>
复制代码

 

 

 

 

 

 

复制代码
 1 /**
 2      * SpringMVC获取请求数据--集合类型参数
 3      *  应用场景2:ajax.jsp
 4      * @param userList
 5      */
 6     @RequestMapping("/save15")
 7     @ResponseBody
 8     public void save15(@RequestBody List<User> userList) {
 9         //当使用ajax提交时,可以指定contentType为json形式,并在方法参数位置使用@RequestBody,可以直接接收集合数据而无需使用POJO进行包装
10         System.out.println(userList);
11         /*
12         http://localhost:8080/ssm4/ajax.jsp
13         [User{username='zhangsan', age=18}, User{username='lisi', age=28}]
14          */
15         //注意,要在spring-mvc.xml中配置开放静态资源的访问,不然报错找不到js文件而无法触发ajax
16     }
复制代码
复制代码
 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: yubaby
 4   Date: 2021/7/16
 5   Time: 18:52
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10 <head>
11     <title>ajax</title>
12 
13     <script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
14     <script>
15         var userList = new Array();
16         userList.push({username:"zhangsan",age:18});
17         userList.push({username:"lisi",age:28});
18 
19         $.ajax({
20             type:"POST",
21             url:"${pageContext.request.contextPath}/user/save15",
22             data:JSON.stringify(userList), //将userList数组转为json字符串
23             contentType:"application/json;charset=utf-8"
24         });
25     </script>
26 
27 </head>
28 <body>
29 
30 </body>
31 </html>
复制代码
复制代码
 1 spring-mvc.xml
 2 
 3 +
 4 
 5 <!--开放静态资源的访问-->
 6     <!--mapping值为访问地址(url),location值为实际路径(文件夹)-->
 7     <!--<mvc:resources mapping="/js/**" location="/js/" />
 8     <mvc:resources mapping="/img/**" location="/img/" />-->
 9 
10     <!--或者也可以这样设置,达到开放资源访问的相同效果。-->
11     <!--即若springMVC(匹配RequestMapping地址)找不到资源,则会交由原始容器(Tomcat)来处理-->
12     <mvc:default-servlet-handler />
复制代码

 请求数据乱码问题

复制代码
web.xml
 
+

<!--配置全局过滤的filter-->  <!--防止post请求中的中文乱码-->
    <!--get请求中的乱码tomcat8之后解决了,但本项目使用的是tomcat7的maven插件,需要设置UTF-8编码防止get的乱码-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
复制代码
复制代码
pom.xml

+插件的编码参数


<!--jdk编译插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <target>1.8</target>
                    <source>1.8</source>
                    <encoding>UTF-8</encoding> <!--防止sout内部输出中文乱码-->
                </configuration>
            </plugin>
            <!--tomcat7插件-->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <port>8080</port>
                    <path>/ssm4</path>
                    <uriEncoding>UTF-8</uriEncoding> <!--防止get请求url中中文参数乱码-->
                </configuration>
            </plugin>
复制代码

参考https://blog.csdn.net/weixin_40886648/article/details/81627542

 

 

 

 

 

 参数绑定注解@RequestParam

 

 

 

 

复制代码
 1 /**
 2      * 参数绑定注解@requestParam
 3      * @param username
 4      */
 5     @RequestMapping("/save16")
 6     @ResponseBody
 7 //    public void save16(@RequestParam("name") String username) { //@RequestParam(value = "name")
 8 //    public void save16(@RequestParam(value = "name", required = true) String username) { //required默认true
 9     public void save16(@RequestParam(value = "name", required = false, defaultValue = "张三") String username) { //设置defaultValue时,required设为true没太大意义
10         System.out.println(username);
11         /*
12         http://localhost:8080/ssm4/user/save16?name=1122
13         1122
14 
15         http://localhost:8080/ssm4/user/save16
16         required = true时:HTTP Status 400 - Required String parameter 'name' is not present
17         required = false时:null
18 
19         http://localhost:8080/ssm4/user/save16
20         张三
21         http://localhost:8080/ssm4/user/save16?name=lisi
22         lisi
23          */
24     }
复制代码

获取Restful风格的参数

 

 

复制代码
 1 /**
 2      * 获得Restful风格的参数
 3      * @param username
 4      */
 5     @RequestMapping("/save17/{name}") //{name}占位,匹配请求路径中的参数
 6     @ResponseBody
 7     public void save17(@PathVariable("name") String username){ //@PathVariable("name")用于解析@RequestMapping中的参数占位
 8         System.out.println(username);
 9         /*
10         此处仅演示GET(Restful中,用于获取资源)请求
11         http://localhost:8080/ssm4/user/save17/%E6%9D%8E%E5%9B%9B
12         李四
13         http://localhost:8080/ssm4/user/save17/tom
14         tom
15          */
16     }
复制代码

 

posted @   yub4by  阅读(121)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示