2022-08-20  阅读(620)

Spring MVC支持对多种类型的请求参数进行封装

  • 基本类型
  • Pojo对象类型
  • 包装Pojo对象类型
  • List集合类型
  • Map集合类型

下面我们来先看看对基本参数类型的封装。

1 设计表单页面

            
            <%@ page contentType="text/html;charset=UTF-8" language="java" %>
            <html>
            <head>
                <title>一点教程网 - www.yiidian.com</title>
            </head>
            <body>
            <h2>基本类型参数封装</h2>
            <form action="/param.do">
                用户名:<input type="text" name="username"><br>
                年龄:<input type="text" name="age"><br>
                <input type="submit" value="提交">
            </form>
            </body>
            </html>

2 编写控制器接收参数

            
            package com.yiidian.controller;
            import org.springframework.stereotype.Controller;
            import org.springframework.web.bind.annotation.RequestMapping;
            /**
             * 普通参数封装
             * 一点教程网 - www.yiidian.com
             */
            @Controller
            public class ParamController {
            
                @RequestMapping("/param.do")
                public String save(String username,Integer age){
                    System.out.println("用户名:"+username);
                    System.out.println("年龄:"+age);
                    return "success";
                }
            }

这里要注意的是,控制器接收参数的形参名称必须和表单的name属性保持一致,否则会接收失败!

3 springmvc.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:mvc="http://www.springframework.org/schema/mvc"
                   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/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">
            
                <!-- 1.扫描Controller的包-->
                <context:component-scan base-package="com.yiidian.controller"/>
            
                <!-- 2.配置视图解析器 -->
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <!-- 2.1 页面前缀 -->
                    <property name="prefix" value="/pages/"/>
                    <!-- 2.2 页面后缀 -->
                    <property name="suffix" value=".jsp"/>
                </bean>
            
                <!-- 3.创建处理器适配器和处理器映射器-->
                <mvc:annotation-driven/>
            </beans>

4 运行测试

202202131334358431.png

控制台输出:

202202131334363022.png

源码下载:https://pan.baidu.com/s/1R0sWIyti8H-t6uN5i7S_bQ

阅读全文
  • 点赞