关闭

servlet如何接受JS函数中的数组

1169人阅读 评论(0) 收藏 举报

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="js/lib/jquery-1.4.4.js"></script>
  </head>
  <script type="text/javascript">
  
  var arr = new Array();
  for(var i = 0; i < 5; i++){
  	arr[i] = "huangbiao----"+i;
  }
  //alert(arr.toString());//将数组以字符串的形式展现出来
  
  function testJson(){
  	var date = new Date();
	var timestamp = date.getTime();
	//alert(timestamp);
	//参数后面加上时间戳是以为ajax机制利用了缓存,如果参数一致就不会再次发送请求了
	//前面的../表示路径要在上一个目录,才能发送请求
	$.get("servlet/GetServletJson", { HB: "[111,222,333]",time:timestamp,arr:arr.toString()},
		//function方法是接受server端传递过来的方法
		function(data){
			//alert(data);
	});
  }
  </script>
  
  <body>
    <input type="button" value="发送一个数组JSON" id="testLog" onclick="testJson()">
  </body>
</html>

 

 

servlet接受AJAX传递过来的参数

package hb.com;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetServletJson extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println(request.getParameter("HB"));
		System.out.println(request.getParameter("time"));
		System.out.println(request.getParameter("arr"));
		System.out.println(request.getParameterValues("arr"));
				
	}

}

 

将数组格式的字符串转换为字符串数组

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String ss = "[111, 222, 333, 444]";
		String a[] = ss.replace("[", "").replace("]", "").split(",");
		for(int i = 0 ; i < a.length; i++){
			System.out.println(a[i].replace(" ", ""));
		} 
	}

}

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:322736次
    • 积分:8882
    • 等级:
    • 排名:第2253名
    • 原创:1096篇
    • 转载:14篇
    • 译文:0篇
    • 评论:5条
    最新评论