1

在我的jsp页面中,

<form id="indexForm" name="indexForm" action="LoginAction" method="post">
<table>
    <tr>
        <td id="fname" class="fontStyle">First Name :</td>
        <td id="fvalue"><input type="text" id="firstname"
            name="firstname" /></td>
        <td id="lname" class="fontStyle">Last Name :</td>
        <td id="lvalue"><input type="text" id="lastname" name="lastname" /></td>
    </tr>
        <tr>
        <td></td>
        <td>
        <center><!-- <input type="button" value="End Chat" onclick="getValues()" /> -->
        <a id="button" href="javascript:getValues();">Start chat</a></center>
        </td>
        <td>
        <center><!-- <input type="button" value="End Chat" /> --> <a
            id="button" href="javascript:logout();">Stop chat</a></center>
        </td>
        <td></td>
    </tr>

</table>

</form>

</div>
<div style="display: none;" id="div">
<div><textarea id="textarea" rows="10"></textarea></div>
<div>
<table>
    <tr>
        <td id="msg" class="fontStyle">message :</td>
        <td id="msgvalue"><input size="40" type="text" id="message" /></td>
        <td style="width: 5%;"></td>
        <td><!-- <input type="button" value="send" onclick="sendMessage()" /> -->
        <a id="button3" href="javascript:sendMessage();">Send</a></td>
    </tr>
</table>
</div>
</div>

在我的 JavaScript 中,

var message ;
var textarea ;

function sendMessage(){


    message = document.getElementById("message").value;
            textarea = document.getElementById("textarea");


    try
    {
        xmlhttp.onreadystatechange=function()
        {
            //alert("Status : "+xmlhttp.status+"\nreadyState : "+xmlhttp.readyState);
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                var checkMsg = encodeURIComponent(xmlhttp.responseText.toString());
                if(checkMsg != "null" && checkMsg != null){
                    //document.getElementById("textarea").innerHTML +=  checkMsg;
                    if(textarea.value == "")
                        textarea.value = checkMsg;
                    else
                        textarea.value += "\n"+ checkMsg  ;
                }
            }
        };
        xmlhttp.open("POST","SendMessageAction?message="+encodeURIComponent(message)+"&sid"+Math.random(),true);
        xmlhttp.send();
    }
    catch(err)
    {
        alert(err.description);
    }
}

在我的 servlet 中,

package com.tps.flexchat.action;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.genesyslab.platform.webmedia.protocol.FlexChatProtocol;
import com.tps.flexchat.Request.SendMessage;
import com.tps.flexchat.info.ApplicationInfo;
import com.tps.flexchat.info.CustomerInfo;

public class SendMessageAction extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private String msg;
    private String seckey;
    private String uid;
    private String sessionId;
    private int counter;
    private FlexChatProtocol protocol = null; 
    private SendMessage message;


    public SendMessageAction() {
    super();
    }

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

        PrintWriter out = response.getWriter();
        msg = request.getParameter("message");
        seckey = request.getParameter("securekey");
        uid = request.getParameter("userId");
        sessionId = request.getParameter("sessionId");
        //counter =Integer.parseInt(request.getParameter("counter"));
        counter = 1;
        protocol = ApplicationInfo.flexProtocol;

        message = new SendMessage();
        message.send(msg, seckey, uid, sessionId, counter, protocol);

        CustomerInfo customer = ApplicationInfo.customerDetails.get(uid);

        out.print(customer.getMessage());

    }

}

sessionId,userId,secureKey可以由genesys生成并且工作正常..只有msg有问题......

在java类中,

package com.tps.flexchat.Request;

import com.genesyslab.platform.commons.protocol.ChannelState;
import com.genesyslab.platform.commons.protocol.Message;
import com.genesyslab.platform.commons.protocol.ProtocolException;
import com.genesyslab.platform.webmedia.protocol.FlexChatProtocol;
import com.genesyslab.platform.webmedia.protocol.flexchat.EventInfo;
import com.genesyslab.platform.webmedia.protocol.flexchat.MessageText;
import com.genesyslab.platform.webmedia.protocol.flexchat.TreatAs;
import com.genesyslab.platform.webmedia.protocol.flexchat.UserType;
import com.genesyslab.platform.webmedia.protocol.flexchat.events.EventStatus;
import com.genesyslab.platform.webmedia.protocol.flexchat.requests.RequestRefresh;
import com.tps.flexchat.info.ApplicationInfo;
import com.tps.flexchat.info.CustomerInfo;


public class SendMessage {
    int i = 0;
    public void send(String msg,String seckey, String uid, String sessionId, int counter, FlexChatProtocol protocol){
            CustomerInfo customer = ApplicationInfo.customerDetails.get(uid);
            RequestRefresh refresh = RequestRefresh.create();
            refresh.setMessageText(MessageText.create(null, TreatAs.NORMAL, msg));
            refresh.setFromPosition(customer.getFromPosition()+1);
            refresh.setSecureKey(seckey);
            refresh.setUserId(uid);

            try {
                if(protocol.getState() == ChannelState.Opened){
                    Message resp = protocol.request(refresh);
                    if(resp != null){
                        EventStatus status = (EventStatus)resp;
                        if(status.messageId() == EventStatus.ID){
                            String userId = status.getUserId();

                            if(status.getFlexTranscript() != null && status.getFlexTranscript().getEventInfoList() != null){
                                EventInfo info = (EventInfo) status.getFlexTranscript().getEventInfoList().getLast();

                                    if(customer != null){
                                        customer.setFromPosition(status.getFlexTranscript().getLastPosition());
                                        customer.addMessage(info.getText());
                                    }

                            }


                        }
                    }
                    //System.out.println(msg+";"+seckey+";"+uid+";"+sessionId+";"+counter);
                }else{
                    protocol.open();
                }
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}

当我在文本字段中键入任何特殊字符并按下发送按钮时,它将调用sendMessage()JavaScript 并在文本区域中显示除 % 符号之外的值。

%符号外,所有特殊字符都在工作。

如何显示%符号?

4

3 回答 3

1

首先不要使用escape()encodeURIComponent()而是使用。有关详细信息,请参阅

message = encodeURIComponent(document.getElementById("message").value);

其次在<textarea>with.value而不是 中设置值.innerText

textarea.value = textarea.value ? textarea.value + '\n' + checkMsg : checkMsg;

第三,您需要Content-type:application/x-www-form-urlencoded在发出请求时在 requestHeader 中进行设置POST。并发送您的有效负载,xhr.send(data)而不是使用查询字符串传递它。

xmlhttp.open("POST", "SendMessageAction?sid="+Math.random(), true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("message=" + message);

一切加起来,假设您的响应是简单的(未以 url 编码编码,这是不必要的!

var messageEl = document.getElementById("message");
var textareaEl = document.getElementById("textarea");

function sendMessage(){

    var xhr = new XMLHttpRequest();
    xhr.onload = function(evt) {
        var checkMsg = xhr.responseText;
        if (textareaEl.value)
            textareaEl.value += '\n';
        textareaEl.value += checkMsg;
    };
    xhr.onerror = function(evt) {
        // handle the error.
    };
    xhr.open('POST', "SendMessageAction?sid="+Math.random(), true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send("message=" + encodeURIComponent(messageEL.value));
}

你的问题应该自己解决。

于 2012-11-15T12:41:41.653 回答
0

我可以看到您已经在转义消息,但看起来您还需要 URL -encode 然后 -decode 消息。URL 中使用 + 符号来表示空格,因此任何实际的 + 符号都将被删除,除非您对它们进行编码(到 '%2B')。

在 Javascript 端,您可以使用encodeURIComponent()and decodeURIComponent(),在 Java 端使用URLDecoderand URLEncoder

在您的 Javascript 中添加类似...

var checkMsg = decodeURIComponent(xmlhttp.responseText.toString());
...

xmlhttp.open("POST","SendMessageAction?message=" + encodeURIComponent(message)  +"&sid"+Math.random(),true);

...在发送/接收消息的 Java 代码中...

String inMessage = URLDecoder.decode(rawMessage, "UTF-8");
...
return URLEncoder.encoder(outMessage, "UTF-8");
于 2012-11-15T11:55:20.827 回答
0

解决办法是,

在使用 AJAX 将值发送到 servlet 时,我使用了 encodeURIComponent() 和 decodeURIComponent() 而不是 escape() 。

我的脚本是这样的,

var checkMsg = decodeURIComponent(xmlhttp.responseText.toString());
...

xmlhttp.open("POST","SendMessageAction?message=" + encodeURIComponent(message) 

感谢所有支持我的人......

于 2012-11-16T08:31:22.153 回答