javaweb 前台向后台传值

一、ajax中向后台传list集合,后台springmvc接收

JSON对象和JSON字符串

在SpringMVC环境中,@RequestBody加粗样式接收的是一个Json对象的字符串,而不是一个Json对象。然而在ajax请求往往传的都是Json对象,用 JSON.stringify(data)的方式就能将对象变成字符串。同时ajax请求的时候也要指定dataType: "json",contentType:"application/json"这样就可以轻易的将一个对象或者List传到Java端

Content-Type

服务器为什么会对表单提交和文件上传做特殊处理,因为表单提交数据是名值对的方式,且Content-Type为application/x-www-form-urlencoded,而文件上传服务器需要特殊处理,普通的post请求(Content-Type不是application/x-www-form-urlencoded)数据格式不固定,不一定是名值对的方式,所以服务器无法知道具体的处理方式,所以只能通过获取原始数据流的方式来进行解析。

第一种方式 传递的参数Bean

$("#saveuddd").click(function(){
var saveDataAry=[];
var data1={"name":"test","password":"gz"};
var data2={"name":"ququ","password":"gr"};
saveDataAry.push(data1);
saveDataAry.push(data2);
$.ajax({
type:"POST",
url: basePath + "/user/saveUser",
dataType:"json",
contentType:"application/json", // 指定这个协议很重要
data:JSON.stringify(saveDataAry), //只有这一个参数,json格式,后台解析为实体,后台可以直接用
success:function(data){
}
});
})
java文件
@RequestMapping(value = "saveUser", method = {RequestMethod.POST }) 
@ResponseBody
public void saveu( @RequestBody List<User> users ){ //List 泛型必须为实体,为map接收不到
System.out.println(users) ;
}
使用如下方法,可以使用bean
@RequestMapping(value = "saveUser", method = {RequestMethod.POST })
@ResponseBody
public void saveu( @RequestBody User[] users ){ 
System.out.println(users.getName()) ; // 此时的user是实体bean
}

第二种方式 传递的键值对

jsp同上
另外一种:
@RequestMapping(value = "saveUser", method = {RequestMethod.POST })
@ResponseBody
public void saveu( @RequestBody List<Map<String,String>> users ){ // spring MVC只能解析外层的json格式,内部的bean转化为Map格式的键值对,需要对map解析
List<User> userList = new ArrayList<User>();
for(Map<String,String> map : users){
User u = new User();
u.setName(map.get("name"));
u.setPassword(map.get("password"));
userList.add(u);
}
// 这里就可以使用 userList 了
}

第三种方式

能够传递多个参数,但是每一个参数都是字符串(bean类型的数据会转化为JSON格式的字符串)

jsp文件
$("#saveuddd").click(function(){
                    var saveDataAry=[];
                    var data1={"name":"test","password":"gz"};
                    var data2={"name":"ququ","password":"gr"};
                    saveDataAry.push(data1);
                    saveDataAry.push(data2);
                    $.ajax({
                        type:"POST",
                        url: basePath + "/user/saveUser",
                        dataType:"json",
                        data:{users:JSON.stringify(saveDataAry),aa:"ddd"},
                          // 可以传递多个参数,但此时的users内容与另外一个参数:aa 的内容一起传递,所以后台解析为字符串
                         // 后台接收的users内容:[{"name":"test","password":"gz"},{"name":"ququ","password":"gr"}]
                         // 后台接收的 aa 内容:"ddd"
                        success:function(data){}
                    });
                })
     java文件
	@RequestMapping(value = "saveUser", method = {RequestMethod.POST })
        @ResponseBody
         public void saveu( String users , String aa ){
         	System.out.println(users) ;
         }   
        

第一二种方式

dataType: 'json',
contentType:"application/json",
data: JSON.stringify(datas),//data数据必须使用JSON.stringify方法处理,后台才能正常接收,否则报400错误

以上转载自https://blog.csdn.net/junehappylove/article/details/81288885
现象如题,环境为MYECLIPSE和TOMCAT6,代码如下: 提交数据的文件department_add.jsp: <%@ page contentType="text/html" pageEncoding = "GBK"%> <%@ page import="com.lb.teashop.factory.*,com.lb.teashop.vo.*"%> <jsp:useBean id="department" scope="request" class="com.lb.teashop.vo.DepartmentBean"/> <html> <head><title>连锁店信息维护</title></head> <script type="text/javascript" src="../js/set_editable.js"></script> <% request.setCharacterEncoding("GBK"); //解决中文乱码问题 %> <body> <h3>添加连锁店</h3> <% String id = request.getParameter("id"); if(!(null == id || "".equals(id))){ //指定code时,显示对应信息 try{ DepartmentBean dpt=DAOFactory.getDepartmentDAOInstance().findDepartmentById(Integer.parseInt(id)); //out.println("dgc_code:" + dpt.getName()); department = dpt; //out.println("department_id:" + department.getId()); %> <form action="department_update_do.jsp" method="post"> <table> <tr> <td>店名:</td> <td> <input type="text" id="id_edit" name="id" value="<%=department.getId()%>" readonly> </td> <td> <input type="text" id="name_edit" name="name" value="<%=department.getName() %>" readonly> </td> </tr> <tr> <td>地址:</td> <td> <textarea id="address_edit" name="address" rows="6" cols="40" readonly><%=department.getAddress()%></textarea> <br><%=department.getErrorMsg("errAddress")%> </td> </tr> <tr> <td>电话:</td> <td> <input type="text" id="phone_edit" name="phone" readonly value="<%=department.getPhone()%>"> <%=department.getErrorMsg("errPhone")%> </td> </tr> <tr> <td>真:</td> <td> <input id="fax_edit" name="fax" readonly value="<%=department.getFax()%>"> <%=department.getErrorMsg("errFax")%> </td> </tr> <tr> <td>测试号:</td> <td> <input id="apply_page_sn_edit" name="apply_page_sn" readonly value="<%=department.getApply_page_sn()%>"> <%=department.getErrorMsg("errApply_page_sn")%> </td> </tr> <tr> <td><input type="button" value="修改" onclick="set_editable();"></td> <td><input type="submit" value="提交"></td> </tr> </table> </form> <% }catch(Exception e){ e.printStackTrace(); } }else{ //未指定code时,显示空白录入界面。 %> <form action="department_add_do.jsp" method="post"> <table> <tr> <td>连锁店名称:</td> <td> <input type="text" name="name" > <%=department.getErrorMsg("errName")%> </td> </tr> <tr> <td>拼音码:</td> <td> <input type="text" name="py_code" ></input> <br><%=department.getErrorMsg("errPy_code")%> </td> </tr> <tr> <td>地址:</td> <td> <textarea id="address" name="address" rows="6" cols="40"></textarea> <br><%=department.getErrorMsg("errPy_code")%> </td> </tr> <tr> <td>电话:</td> <td> <input type="text" name="phone"></input> <br><%=department.getErrorMsg("errPhone")%> </td> </tr> <tr> <td>真:</td> <td> <input type="text" name="fax" ></input> <br><%=department.getErrorMsg("errFax")%> </td> </tr> <tr> <td><input type="submit" value="添加"></td> <td><input type="reset" value="重置"></td> </tr> </table> </form> <% } %> </body> </html> JAVABEAN文件DepartmentBean.java: /** * */ package com.lb.teashop.vo; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * @author Administrator * */ public class DepartmentBean implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private String py_code; private String address; private String phone; private String fax; private int apply_page_sn; private int page_sn; private Map<String,String>errors=null; //声明一个保存全部错误信息的Map集合 public DepartmentBean(){ //this.code=""; this.name=""; this.py_code=""; this.errors = new HashMap<String,String>(); //实例化Map对象,保存错误信息 } public boolean isValidate(){ //数据验证操作 boolean flag = true; // //System.out.println(this.name); // //System.out.println(this.comment); // if(this.name==null || "".equals(this.name)){ // flag = false; // //System.out.print(this.name); // errors.put("errName", "请输入商品类别名称。"); //保存错误信息 // } // if(this.py_code==null || "".equals(this.py_code)){ // flag = false; // errors.put("errComment", "请输入规格描述,长度不超过150个汉字。"); // }else if(this.py_code.length()>15){ // flag = false; // //System.out.println(this.specification.length()); // errors.put("errComment", "规格描述是不超过150个字的中文。"); // } return flag; } public String getErrorMsg(String key){ String value = this.errors.get(key); return value == null?"":value; //返回value对应的内容 } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the py_code */ public String getPy_code() { return py_code; } /** * @param py_code the py_code to set */ public void setPy_code(String py_code) { this.py_code = py_code; } /** * @return the address */ public String getAddress() { return address; } /** * @param address the address to set */ public void setAddress(String address) { this.address = address; } /** * @return the phone */ public String getPhone() { return phone; } /** * @param phone the phone to set */ public void setPhone(String phone) { this.phone = phone; } /** * @return the fax */ public String getFax() { return fax; } /** * @param fax the fax to set */ public void setFax(String fax) { this.fax = fax; } /** * @return the apply_page_sn */ public int getApply_page_sn() { return apply_page_sn; } /** * @param apply_page_sn the apply_page_sn to set */ public void setApply_page_sn(int apply_page_sn) { this.apply_page_sn = apply_page_sn; } /** * @return the page_sn */ public int getPage_no() { return page_sn; } /** * @param page_sn the page_sn to set */ public void setPage_no(int page_sn) { this.page_sn = page_sn; } } 接收数据的文件department_update_do.jsp: <%@ page contentType="text/html" pageEncoding = "GBK"%> <%@ page import="com.lb.teashop.factory.*" %> <jsp:useBean id="department" scope="request" class="com.lb.teashop.vo.DepartmentBean"></jsp:useBean> <jsp:setProperty name = "department" property="*"></jsp:setProperty> <html> <head><title>连锁店信息维护</title></head> <% request.setCharacterEncoding("GBK"); //解决中文乱码问题 %> <head><title>添加连锁店</title></head> <body> <%=department.getId() %><br> <%=department.getName() %><br> <%=department.getAddress() %><br> <%=department.getPhone() %><br> <%=department.getFax() %><br> <%=department.getApply_page_sn() %><br> <% if(department.isValidate()){ try{ if(DAOFactory.getDepartmentDAOInstance().doUpdateDepartment(department)>0 ){ %> <h3>商品信息修改成功!</h3> <% response.setHeader("refresh","2;URL=department_list.jsp"); }else{ %> <h3>商品信息修改失败!</h3> <% response.setHeader("refresh","2;URL=department_add.jsp?id="+department.getId()); } }catch(Exception e){ e.printStackTrace(); //在Tomcat后台打印 } }else{ %> <jsp:forward page="department_add.jsp?id=<%=department.getId() %>"></jsp:forward> <% //response.setHeader("refresh","2;URL=department_add.jsp"); } %> </body> </html> 全部的整型变量如果小于10,接收文件看到的都为0,大于等于10的都没问题。求大牛指点迷津!非常感谢!
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页