JSP聊天-如何将值从HTML解析为JSP页面

JSP Chat - How I can parse the value from HTML to JSP page?

本文关键字:JSP HTML 页面 聊天      更新时间:2023-09-26

我必须与JSP、AJAX和Java聊天,我遇到了一个问题:当我试图使用我的变量来存储输入文本的值时,这个变量为null。如果我将"action"属性添加到表单中,变量"textParam"将具有输入文本的值,但是,如果我这样做,我必须使用action重定向到页面,而我不这么做。

我需要在JSP页面中处理更大的内容,然后在HTML页面(这是一个JSP页面)中重新加载(重新加载部分不在实际问题中)。

当我按下按钮时,如何用输入的文本值填充"textParam"?

PS:我需要使用纯javascript,而不是一些库:)

必须处理的JSP是:

String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);

我的表格看起来是这样的:

<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
        <input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
        <input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>

js文件是这样的:

var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {                
    if (window.XMLHttpRequest) {                    
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {                   
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}
function sendChatText() {
    if(document.getElementById('chatMessage').value == '') {
        alert("You have not entered a message");
        return;
    }
    if (request.readyState == 4 || request.readyState == 0) {
        request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
        request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        request.onreadystatechange = handleSendChat; 
        var param = 'message=' + document.getElementById('chatMessage').value;                                  
        param += '&chat=1';
        request.send(param);
        document.getElementById('chatMessage').value = '';
    }                           
}
function handleSendChat() {             
    clearInterval(mTimer);
    getChatText();
}
function blockSubmit() {
    sendChatText();
    return false;
}

问题就在这里:

String textParam = request.getParameter("chatMessage");

我试图获取"chatMessage"参数,它只是输入的名称。解决方法是获取在js:中定义和请求的"消息"参数

String textParam = request.getParameter("message");