springmvc--请求参数的绑定

目录

一、创建项目,pom文件

二、web.xml

三、spring-mvc.xml

四、index.jsp

五、实体类

Address类

User类

六、UserController类

七、请求参数解决中文乱码

八、配置tomcat,然后启动tomcat

1.

2.

3.

4.

九、接收Map类型

1.直接接收Map类型

(1)Get请求

第一种情况,什么注解也没有

第二种情况:传个值

第三种情况:声明是get请求

第四种情况:加@RequestParam

(2)post请求:

第一种情况:什么注解也没有

前端页面:加一个表单

第二种情况:声明是post请求

第三种情况:加上@RequestParam注解

表单和controller类中的方法改改(加个username)

第四种情况:加@RequestBody注解

2.用对象接收map

(1)User类里加一个map

(2)前端:

[(3)运行:](#(3)运行:)

十、在控制器中使用原生的ServletAPI对象


一、创建项目,pom文件

XML 复制代码
​
<?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.qcby</groupId>

    <artifactId>springMVC12</artifactId>

    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>


    <properties>

        <maven.compiler.source>8</maven.compiler.source>

        <maven.compiler.target>8</maven.compiler.target>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <spring.version>5.0.2.RELEASE</spring.version>

    </properties>


    <dependencies>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-context</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-web</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-webmvc</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <dependency>

            <groupId>javax.servlet</groupId>

            <artifactId>servlet-api</artifactId>

            <version>2.5</version>

            <scope>provided</scope>

        </dependency>

        <dependency>

            <groupId>javax.servlet.jsp</groupId>

            <artifactId>jsp-api</artifactId>

            <version>2.0</version>

            <scope>provided</scope>

        </dependency>


    </dependencies>



</project>

​

二、 web.xml

XML 复制代码
​
<?xml version="1.0" encoding="UTF-8"?>

<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">


    <!--前端控制器-->

    <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>

        <!--配置启动加载-->

        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

        <servlet-name>dispatcherServlet</servlet-name>

        <url-pattern>*.do</url-pattern>

    </servlet-mapping>

    

</web-app>

​

三、 spring-mvc.xml

XML 复制代码
​
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:mvc="http://www.springframework.org/schema/mvc"

       xmlns:context="http://www.springframework.org/schema/context"

       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/mvc

        http://www.springframework.org/schema/mvc/spring-mvc.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context.xsd">


    <!-- 配置spring创建容器时要扫描的包 -->

    <context:component-scan base-package="com.qcby.controller"></context:component-scan>


    <!-- 配置视图解析器 -->

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/pages/"></property>

        <property name="suffix" value=".jsp"></property>

    </bean>


    <!-- 配置spring开启注解mvc的支持-->

<!--    <mvc:annotation-driven></mvc:annotation-driven>-->

</beans>

​

四、 index.jsp

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>请求参数绑定</title>

</head>

<body>

<form action="user/save1.do" method="post">

    姓名:<input type="text" name="username" /><br/>

    年龄:<input type="text" name="age" /><br/>

    <input type="submit" value="提交" />

</form>


<h3>请求参数绑定(封装到实体类)</h3>

<form action="user/save2.do" method="post">

    姓名:<input type="text" name="username" /><br/>

    年龄:<input type="text" name="age" /><br/>

    <input type="submit" value="提交" />

</form>


<h3>请求参数绑定(封装到实体类)</h3>

<form action="user/save3.do" method="post">

    姓名:<input type="text" name="username" /><br/>

    年龄:<input type="text" name="age" /><br/>

    金额:<input type="text" name="address.money" /><br/>

    <input type="submit" value="提交" />

</form>


<h3>请求参数绑定(封装到实体类,存在list集合)</h3>

<form action="user/save4.do" method="post">

    姓名:<input type="text" name="username" /><br/>

    年龄:<input type="text" name="age" /><br/>

    金额:<input type="text" name="address.money" /><br/>

    集合:<input type="text" name="list[0].money" /><br/>

    集合:<input type="text" name="list[1].money" /><br/>

    <input type="submit" value="提交" />

</form>


</body>

</html>

五、 实体类

Address类

java 复制代码
import java.io.Serializable;


public class Address implements Serializable {

    private Double money;


    public Double getMoney() {

        return money;

    }


    public void setMoney(Double money) {

        this.money = money;

    }


    @Override

    public String toString() {

        return "Address{" +

                "money=" + money +

                '}';

    }

}

User类

java 复制代码
import java.io.Serializable;

import java.util.List;


public class User implements Serializable {

    private String username;

    private Integer age;


    // 引用对象

    private Address address;


    // list集合

    private List<Address> list;


    public String getUsername() {

        return username;

    }


    public void setUsername(String username) {

        this.username = username;

    }


    public Integer getAge() {

        return age;

    }


    public void setAge(Integer age) {

        this.age = age;

    }


    public Address getAddress() {

        return address;

    }


    public void setAddress(Address address) {

        this.address = address;

    }


    public List<Address> getList() {

        return list;

    }


    public void setList(List<Address> list) {

        this.list = list;

    }


    @Override

    public String toString() {

        return "User{" +

                "username='" + username + '\'' +

                ", age=" + age +

                ", address=" + address +

                ", list=" + list +

                '}';

    }

}

六、 UserController类

java 复制代码
import com.qcby.pojo.User;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;


@Controller

@RequestMapping("/user")

public class UserController {

    @RequestMapping("/save1.do")

    public String save(String username,Integer age){

        System.out.println("姓名:"+username);

        System.out.println("年龄:"+age);

        return "success";

    }

    

    @RequestMapping("/save2.do")

    public String save2(User user){

        System.out.println("user对象:"+user);

        return "success";

    }


    @RequestMapping("/save3.do")

    public String save3(User user){

        System.out.println("user对象:"+user);

        return "success";

    }


    @RequestMapping("/save4.do")

    public String save4(User user){

        System.out.println("user对象:"+user);

        return "success";

    }

}

七、 请求参数解决中文乱码

在web.xml中配置Spring提供的过滤器

XML 复制代码
​
<!-- 配置过滤器,解决中文乱码的问题 -->

<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>

现在的web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<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">


    <!-- 配置过滤器,解决中文乱码的问题 -->

    <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>



    <!--前端控制器-->

    <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>

        <!--配置启动加载-->

        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

        <servlet-name>dispatcherServlet</servlet-name>

        <url-pattern>*.do</url-pattern>

    </servlet-mapping>


</web-app>

​

八、 配置tomcat,然后启动tomcat

1 .

2 .

3.

4 .

九、 接收Map类型

1. 直接接收Map类型

如果想直接接收前端传过来的map参数,应该使用两个注解(RequestBody或RequestParam;RequestParam--get和post请求都可以,RequestBody只能post请求,底层封装都是LinkedHashMap)

(1)Get请求

第一种情况,什么注解也没有

UserController类里加一个方法

java 复制代码
@RequestMapping("/mapSave1.do")

public String mapSave1(Map<String, Objects> map){

    System.out.println("map:"+map);

    return "success";

}

没有JSP页面,启动tomcat

控制台:什么输出也没有,没有值

第二种情况:传个值

控制台:还是什么都没有

第三种情况:声明是get请求

UserController类的mapSave1()方法:

java 复制代码
@RequestMapping(value = "/mapSave1.do",method = RequestMethod.GET)

public String mapSave1(Map<String, Objects> map){

    System.out.println("map:"+map);

    return "success";

}

再启动:

控制台:还是没有值

所以跟请求是什么没关系,要想接收就要加注解

第四种情况:加@RequestParam
java 复制代码
@RequestMapping(value = "/mapSave1.do")

public String mapSave1(@RequestParam Map<String, Objects> map){

    System.out.println("map:"+map);

    return "success";

}

再运行:

所以,我传递一个map在后端接收,用get请求必须加@RequestParam注解

(2)post请求:

第一种情况:什么注解也没有
javascript 复制代码
@RequestMapping(value = "/mapSave2.do")

public String mapSave1(Map<String, Objects> map){

    System.out.println("map:"+map);

    return "success";

}
前端页面:加一个表单
html 复制代码
<h3>请求参数的绑定--map集合</h3>

<form action="user/mapSave2.do" method="post">

    map集合key:<input type="text" name="map.key" /><br/>

    map集合value:<input type="text" name="map.value" /><br/>

    <input type="submit" value="提交" />

</form>

运行

点提交

控制台:什么也没有

第二种情况:声明是 post 请求
java 复制代码
@RequestMapping(value = "/mapSave2.do",method = RequestMethod.POST)

public String mapSave2(Map<String, Objects> map){

    System.out.println("map:"+map);

    return "success";

}

再运行:

点提交

控制台:

说明跟get的一样,不加注解是没有办法接收到的

第三种情况: 加上@RequestParam注解
java 复制代码
@RequestMapping(value = "/mapSave2.do",method = RequestMethod.POST)

public String mapSave2(@RequestParam Map<String, Objects> map){

    System.out.println("map:"+map);

    return "success";

}

运行:

点提交

控制台:

可以看出,get请求和post请求都可以用@RequestParam注解

表单和controller类中的方法改改(加个username)

表单:

html 复制代码
<h3>请求参数的绑定--map集合</h3>

<form action="user/mapSave2.do" method="post">

    username:<input type="text" name="username"><br/>

    map集合:<input type="text" name="test1"><br/><%-- test1就是map的key,输入框中的就是map的value --%>

    <input type="submit" value="提交" />

</form>

方法:

java 复制代码
@RequestMapping(value = "/mapSave2.do")

public String mapSave2(@RequestParam Map<String, Objects> map,String username){

    System.out.println("map:"+map);

    System.out.println("username:"+username);

    return "success";

}

运行:

点提交:

控制台:

可以看到:表单中的数据都被封装到了map集合中

第四种情况: 加@RequestBody注解

但是这样的话,它只能接收json数据

现在用表单接收就会报错:

java 复制代码
@RequestMapping(value = "/mapSave2.do")

public String mapSave2(@RequestBody Map<String, Objects> map, String username){

    System.out.println("map:"+map);

    System.out.println("username:"+username);

    return "success";

}

运行:

点提交:(报错)

总结:无注解时,什么都接收不了;@RequestParam注解时,将参数包装成LinkedHashMap对象,参数的key是Map的key,参数的值是Map的value,get和

post请求都支持;@RequestBody注解接收json类型的数据(跟表单不一样,表单传不了),也会包装成LinkedHashMap对象,该注解不支持get请求,get请求没有请求体,不能传json

2. 用对象接收map

(1)User类里加一个map

java 复制代码
private Map<String,Address> userMap;

(2)前端:

java 复制代码
<h3>请求参数绑定(封装到实体类,存在map集合)</h3>

<form action="user/save5.do" method="post">

    姓名:<input type="text" name="username" /><br/>

    年龄:<input type="text" name="age" /><br/>

    金额:<input type="text" name="address.money" /><br/>

    Map集合:<input type="text" name="userMap['one'].money" /><br/>

    Map集合:<input type="text" name="userMap['two'].money" /><br/>

    <input type="submit" value="提交" />

</form>

( 3)运行:

点提交:

控制台:

十、在控制器中使用原生的ServletAPI对象

只需要在控制器的方法参数定义HttpServletRequest和HttpServletResponse对象

UserController里加:

java 复制代码
/*原生的API*/
@RequestMapping("/save6.do")
public String save6(HttpServletRequest request, HttpServletResponse response){
    System.out.println(request);
    // 获取到HttpSession对象
    HttpSession session = request.getSession();
    System.out.println(session);
    System.out.println(response);
    return "success";
}

运行:

控制台:

相关推荐
李慕婉学姐3 小时前
【开题答辩过程】以《基于JAVA的校园即时配送系统的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·开发语言·数据库
奋进的芋圆5 小时前
Java 延时任务实现方案详解(适用于 Spring Boot 3)
java·spring boot·redis·rabbitmq
sxlishaobin5 小时前
设计模式之桥接模式
java·设计模式·桥接模式
model20055 小时前
alibaba linux3 系统盘网站迁移数据盘
java·服务器·前端
荒诞硬汉5 小时前
JavaBean相关补充
java·开发语言
提笔忘字的帝国6 小时前
【教程】macOS 如何完全卸载 Java 开发环境
java·开发语言·macos
2501_941882486 小时前
从灰度发布到流量切分的互联网工程语法控制与多语言实现实践思路随笔分享
java·开发语言
華勳全栈6 小时前
两天开发完成智能体平台
java·spring·go
alonewolf_996 小时前
Spring MVC重点功能底层源码深度解析
java·spring·mvc
沛沛老爹6 小时前
Java泛型擦除:原理、实践与应对策略
java·开发语言·人工智能·企业开发·发展趋势·技术原理