js怎么传各种类型参数到Controller层

发布时间:2023-02-27 14:56:41 作者:iii
来源:亿速云 阅读:102

这篇文章主要讲解了“js怎么传各种类型参数到Controller层”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“js怎么传各种类型参数到Controller层”吧!

一 .@RequestBody和@RequestParam区别

1.@RequestParam

用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

RequestParam可以接受简单类型的属性,也可以接受对象类型。 

实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。

2.@RequestBody

处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。

3.@ModelAttribute

该注解有两个用法,一个是用于方法上,一个是用于参数上;

用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;

用于参数上时:用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

二.一些常用的传参类型 

1.字符串类型参数

/**
 * 传递字符串参数
 */
getStringParam:function(){
   var param={"stringParams":hidden_input_value};
   //var param={};两种方式都行
   // param.stringParams=hidden_input_value;
   $.ajax({
      url:basePath+"/ParamFormatController/getStringParam.shtml",
      data:param,
      type : 'POST',
      dataType : 'json',
      success:function(data){
         
      },
      
   })
},

Controller层

  /**
     * 接收字符串类型参数
     * 
     * @param userName
     * @return
     */
    @RequestMapping("/getStringParam")
    @ResponseBody
    public String getStringParam(String userName) {
        String password = userService.getUserpassword(userName);
        return password;
    }

2.对象类型

/**
		 * 传递对象参数
		 */
		setObjectParam:function(){
			var objectParams={};
			objectParams.name="张三";
			objectParams.age="19";
			objectParams.sex="男";
			$.ajax({
				url:basePath+"/ParamFormatController/getObjectParam.shtml",
				data:objectParams,
				type : 'POST',
				dataType : 'json',
				success:function(data){
					
				},
			})
		},
    /**
     * 接收对象参数
     * 
     * @param
     * @return
     */
    @RequestMapping("/getObjectParam")
    @ResponseBody
    public void getObjectParam(Student objectParams) {
        System.out.println("姓名:" + objectParams.getName());
        System.out.println("性别:" + objectParams.getSex());
        System.out.println("年龄:" + objectParams.getAge());
 
    }

3.复杂对象类型

/**
		 * 传递复杂对象参数(包含id,username,String[],List<Person>)
		 */
		setHardObjectParam:function(){
			
			 var objectParams = {
	                    schoolName:"鹏峰中学",
	                    data:new Date(),
	                    teacherNames:["张老师","李老师","王老师"],
	                    students:[
	                        {name:"小明",sex:"男",age:"19"},
	                        {name:"小红",sex:"男",age:"19"},
	                    ]
	                };
	                $.ajax({
	                    type: "POST",
	                    url:basePath+"/ParamFormatController/getHardObjectParam.shtml",
	                    data: JSON.stringify(objectParams),//重点
	                    contentType:"application/json"     //指定类型
	                })
		},

School类

public class School {
    private String[] teacherNames;
    private String schoolName;
    private Date data;
    private List<Student> students;
 
 
 
    public String[] getTeacherNames() {
        return teacherNames;
    }
 
    public void setTeacherNames(String[] teacherNames) {
        this.teacherNames = teacherNames;
    }
 
    public String getSchoolName() {
        return schoolName;
    }
 
    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }
 
    public Date getData() {
        return data;
    }
 
    public void setData(Date data) {
        this.data = data;
    }
 
    public List<Student> getStudents() {
        return students;
    }
 
    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

Controoler

  /**
     * 接收复杂对象参数(包含id,username,String[],List<Person>)
     * 
     * @param
     * @return
     */
    @RequestMapping("/getHardObjectParam")
    @ResponseBody
    public void getHardObjectParam(@RequestBody School objectParams) {
        System.out.println("学校名:" + objectParams.getSchoolName());
 
    }

4.数组与字符串

/**
         * 传递数组与字符串
         */
        getArrayAndStringParam:function(){
            var pointCodes= new Array(); //定义一数组  
            pointCodes.push("1");
            pointCodes.push("2");
            pointCodes.push("3");
            pointCodes.push("4");
            $.ajax({  
                url:basePath+"/ParamFormatController/getArrayAndStringParam.shtml",  
                type:"POST",  
                data:{"names":pointCodes,"id":'6'},  
                dataType:"json",  
                success:function(res){     
                }
                }); 
            
        },              


    /**
     * 接收数组与字符串
     * 
     * @param
     * @return
     */
    @RequestMapping("/getArrayAndStringParam")
    @ResponseBody
    public void getArrayAndStringParam(@RequestParam(value = "names[]") String[] names, String id) {
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }
 
    }

5.List字符串集合

        /**
         * 传递字符串List参数
         */
        getListByStringParam:function(){
                var orderNosList = new Array(); 
                orderNosList.push("List1");
                orderNosList.push("List2");
                orderNosList.push("List3");
                orderNosList.push("List4");
                $.ajax({
                    url:basePath+"/ParamFormatController/getListByStringParam.shtml",
                    data:{"StringList":orderNosList},
                    type : 'POST',
                    dataType : 'json',
                    success:function(data){
                        
                    },
                })
            
        },

    /**
     * 接收字符串List集合
     * 
     * @param
     * @return
     */
    @RequestMapping("/getListByStringParam")
    @ResponseBody
    public void getListByStringParam(@RequestParam("StringList[]") List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
 
    }

6.List对象集合

    /**
     * 接收对象List集合
     * 
     * @param
     * @return
     */
    @RequestMapping(value = "/getListByObjectParam")
    @ResponseBody
    public void getListByObjectParam(@RequestBody List<Student> students) {
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            System.out.println(s.getName());
        }
 
    }

/**
         * 传递对象List参数
         */
        getListByObjectParam:function(){
                 var param=[];
                 var data1={"name":"张三","age":"21","sex":"2"};
                                 var data2={"name":"李四","age":"24","sex":"2"};
                                 param.push(data1);
                                 param.push(data2);
                $.ajax({
                    url:basePath+"/ParamFormatController/getListByObjectParam.shtml",
                    data:JSON.stringify(param),
                    type : 'POST',
                    contentType: "application/json",
                    success:function(data){
                        
                    },
                })
            
        },

后续类型在补充。

感谢各位的阅读,以上就是“js怎么传各种类型参数到Controller层”的内容了,经过本文的学习后,相信大家对js怎么传各种类型参数到Controller层这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. JS中attribute和property的区别有哪些
  2. 如何使用js实现滑动拼图解锁

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js controller

上一篇:VUE3中如何实现拖拽与缩放自定义看板

下一篇:python中 __init__的意义及作用是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》