Ajax调用servlet,获取参数

时间:2017-01-17 10:16:05

标签: java jquery ajax servlets

我正在通过AJAX调用调用我的Java Servlet,但是我无法从请求中读取输入参数。我尝试了两种方法,但没有运气:

var id;
$("#scan").click(function() {
    id = 1;
    $.ajax({ 
        type: "POST",
        data: id,
        url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
    });
});

id = 1;
$.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', {
    reqValue: id
}, function(responseText) { 
    // $('#welcometext').text(responseText);
    alert("OK!!!");
});

我的servlet代码是request参数的简单日志打印,但返回值始终为null:

String reqID = "";
log.info("Servlet called");
reqID = request.getParameter("reqValue");
log.info("reqID = " + reqID);

我怎样才能使这个工作?

我发现让代码工作的唯一方法是手动将参数添加到servlet网址,例如http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1

2 个答案:

答案 0 :(得分:2)

我检查了你的代码。这是我的工作代码。

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
    var id;

    function fun() {
        alert("aaaa");
        id = 1;

        $.ajax({
            type : "POST",
            data : {
                reqValue : id
            },
            url : "/WebProject/callAjax"
        });
    }
</script>
</head>
<body>
    <button id="scan" onclick="fun()">Sacn</button>
</body>
</html>

//的Servlet

@WebServlet(urlPatterns = {"/callAjax",})
public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;


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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("reqValue"));
    }

}

答案 1 :(得分:0)

var id;

$("#scan").click(function() {

        id = 1;

        $.ajax({ 
            type: "POST",
            data: { reqValue : id},
            url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
        });
});

您需要在servlet中覆盖不同的方法。那些是doPost(),doGet(),service()等。

我怀疑你正在使用doGet()方法,这就是为什么当你将参数添加到你的java代码工作的URL时,以及在你使用type : "POST"的其他两种情况下,java代码无法从Request中读取数据正文(在post方法中,数据将被添加到Request Body)。

我建议您使用doPost()service()方法代替doGet()。