首页 > 其他 > 详细

一个空格惹的祸:服务器端接收不到前端采用问号传参方式传过来的值

时间:2016-03-14 10:44:54      阅读:225      评论:0      收藏:0      [点我收藏+]

        在Web项目中使用问号将浏览器端数据传到服务器端是比较常见的,但是你是否遇到过服务器端怎么也接收不到前端采用问号传参方式传过来的值的情况,不禁要自问:我们的代码怎么了?

        代码一:

package com.ghj.servlet;

import java.io.IOException;

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

public class DataServlet extends HttpServlet {

	private static final long serialVersionUID = 8542386228506190813L;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

		String name = request.getParameter("name");
		if(name != null){
			System.out.println(name.length());
		}else{
			System.out.println("没有接收到客户端传过来的数据!");
		}
	}
}
        代码二:
<%@ page language="java" contentType="text/html; charset=UTF-8" 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>
		<title>首页</title>
		<script type="text/javascript" src="<%=basePath%>js/jquery-1.7.2.js"></script>
		<script type="text/javascript">
			function sendData(){
				$.ajax({
				   	type: "GET",
				   	url: "<%=basePath%>DataServlet?name=John",
				   	success: function(msg){
						console.log("数据传到服务器端了!");
				   	},
				   	error: function(msg){
					   console.log("数据发送失败!");
				     alert("Data Saved: ");
				   	}
				});
			}
		</script>
	</head>

	<body>
		<input type="button" value="发送" onclick="sendData()">
	</body>
</html>
        说明:

        1、当我们点击上面页面“发送”按钮时可以将John发送到服务器端,这时服务器端输出4;
        2、如果我们将上面sendData方法换成下面代码时服务器端将接收不到客户端传过来的数据:

技术分享

        这时之所以没有数据是因为name后面多了一个空格(上图红框框起部分),那么这种情况下还想获取值,则服务器端代码应该这样写(即也要加空格,见下图红框框起部分):

技术分享

        3、如果Servlet代码不变,只在Web端等号右边添加空格,即下图:

技术分享

        这时服务器端接收到的数据包含John前面的空格,即服务器端输出5。

一个空格惹的祸:服务器端接收不到前端采用问号传参方式传过来的值

原文:http://blog.csdn.net/gaohuanjie/article/details/50883656

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!