SpringMVC参数传递方式的7种方式

本文详细介绍了SpringMVC中参数传递的7种方式,包括使用HTTPServletRequest、参数名匹配、对象参数、日期转换及异步提交JSON等。特别讨论了日期类型的转换和RESTful API的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 方式1–使用HTTPServletRequest
 @RequestMapping("/param1")
    public Object testParam1(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+"---"+password);
        return null; // 不知道要返回什么页面 ,默认将 param1 路径名作为jsp文件名
    }
  1. 方法2的参数名和页面参数一致
//适用于 页面参数 比较少的情况下
    @RequestMapping("/param2")
    public Object testParam2(String username1,String password1){
        System.out.println(username1+"---"+password1);
        return null;
    }
  1. 方式3–方法参数名和页面参数名称不一致 (但是又想拿到 页面参数)
 /**
     * 变量名可以随便写
     * @param username1
     * @param password1
     * @return
     * defaultValue: 代表当前参数的默认值 ,该属性不是必须的,是可选的 ,如果是分页可能设置为1
     * required: 必须的,  默认值是true ,代表当前参数必须给值 , 可以设置为false
     *
     *  如果对参数没有特殊要求,一般写为: @RequestParam("password") String password  就可以了.
     */
    @RequestMapping("/param3")
    public Object testParam3(@RequestParam(name="username") String username1,
                             @RequestParam("password") String password1){
        System.out.println(username1+"---"+password1);
        return null;
    }
  1. 方式4–参数过多使用对象作为参数
@RequestMapping("/param4")
    public Object testParam4(User u){
        System.out.println(u);
        return null;
    }
  1. 方式5–包含时间类型,需要类型转换
 /**
     * springmvc 对于时间 , 仅支持 格式: 2020/11/12      2020-01-02
     */
    @RequestMapping("/param5")
    public Object testParam5(User u){
       /**
         * 1.  封装时加注解
         *     @DateTimeFormat(pattern = "yyyy-MM-dd")
         *     private Date time;
         * 2.  在springmvc.xml里配置全局日期时间转换器
         *     <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
         *         <property name="converters">
         *             <set>
         *                 <bean class="cn.hp.utils.TimeUtils"></bean>//因为此处可以配置多个转换器 ,所以 用set标签
         *             </set>
         *         </property>
         *     </bean>
         */
        System.out.println(u);
        return null;
    }

前5种是前台jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>

    <fieldset>
      <legend>参数传递方式1--使用HTTPServletRequest</legend>
      <form action="param/param1" method="get">
        账号:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        <input type="submit" value="提交"><br>
      </form>
    </fieldset>

    <fieldset>
      <legend>参数传递方式2--方法的参数名和页面参数一致</legend>
      <form action="param/param2" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        <input type="submit" value="提交"><br>
      </form>
    </fieldset>

    <fieldset>
      <legend>参数传递方式3--方法参数名和页面参数名称不一致</legend>
      <form action="param/param3" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        <input type="submit" value="提交"><br>
      </form>
    </fieldset>

    <fieldset>
      <legend>参数传递方式4--参数过多使用对象作为参数</legend>
      <form action="param/param4" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        <input type="submit" value="提交"><br>
      </form>
    </fieldset>

    <fieldset>
      <legend>参数传递方式5--包含时间类型,需要类型转换</legend>
      <form action="param/param5" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        日期:<input type="text" name="time"><br>
        <input type="submit" value="提交"><br>
      </form>
    </fieldset>
  </body>
</html>

方法5的日期转换类

package cn.hp.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期转换类    2020-10-12
 * <String, Date>  泛型指的是: 将String类型转为 Date类型
 *
 */
public class TimeUtils implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        //判断输入的时间是否 为空
        if(StrUtil.isEmpty(s)){
            throw new RuntimeException("日期不能为空");
        }
        //  StringUtils.isEmpty() 判断是否为空 ,该类属于spring中的工具类
        DateTime time = DateUtil.parse(s, "yyyy-MM-dd");
        return time;
       /* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(s);
            return date;
        } catch (ParseException e) {
            //e.printStackTrace();
            throw new RuntimeException("日期转换失败");   //这句话类似于 return语句
        }*/
        //return null;
    }
}

  1. restful风格api
 /**
     * restful风格api
     * @param abc
     * @return
     *
     * @PathVariable("id")  注解中的 id要和 {id} 重名 , Integer abc  ,abc 就是随意的一个变量名
     */
    @GetMapping("/param6/{id}")
    public Object testParam6(@PathVariable("id") Integer abc){
        System.out.println("根据id删除==="+abc);
        return null;
    }
  1. 该方法用于获取json数据 并返回到 前台
/**
     * 该方法用于获取json数据 并返回到 前台
     * @return
     */
    @RequestMapping("/param7")
    @ResponseBody       //注解作用: 获取到当前 方法执行的 json数据

    /**
     * 接收的参数 名 ; 和 前台的 key值重名
     */
    public Object testJson(String username,String password){

        Map<String,Object> map = new HashMap<>();

        if(StrUtil.isEmpty(username)){
            map.put("type","error");
            map.put("msg","用户名不能为空");
            return map;
        }

        if(StrUtil.isEmpty(password)){
            map.put("type","error");
            map.put("msg","密码不能为空");
            return map;
        }
        map.put("type","success");
        map.put("msg","登陆成功");
        return map;
    }

异步提交json的jsp页面

<%--
  Created by IntelliJ IDEA.
  User: yuan
  Date: 2020/2/23
  Time: 22:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>异步提交</title>
    <script type="text/javascript" src="js/jquery-1.9.1.js"></script>
    <script>
        $(function () {
           $("#btn").click(function () {    //按钮点击事件
               //异步提交 页面数据到 controller
               var name = $("#name").val();
               var pass = $("#pass").val();

               $.ajax({
                   url:'param/param7',  //相对路径 前面没有 /
                   data:{username123:name,"password":pass},         //传递的参数 , key值 的双引号 ,可以省略
                   type:'post',     //请求方式
                   dataType:'json', //后台返回的数据类型 是json
                   success:function (data) {    //data 是后台响应的数据
                        console.log(data);

                        if(data.type=='success'){
                            alert("跳转到首页");
                        }
                        else{
                            alert("登陆失败");
                        }
                   }
               });

           });
        });
    </script>
</head>
<body>
<!--在前端页面发送一个异步请求到 后台 -->
<fieldset>
    <legend>异步提交</legend>
    <div>
        账号:<input type="text" name="username" id="name"><br>
        密码:<input type="text" name="password" id="pass"><br>
        <input type="button" id="btn" value="提交"><br>
    </div>
</fieldset>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值