1

In my jsp page,

<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>

In my 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);
    }
}

In my 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 can de generated by genesys and working fine..Having problem with msg only...

In java class,

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();
            }
    }
}

When I will type any special character in the text field and when pressed the send button , it will call the sendMessage() in JavaScript and displayed the values in the textarea except the % symbol .

All the special character are working except the % symbol.

How do I display the % symbol?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Fisher Man
  • 487
  • 1
  • 5
  • 14
  • post your code for handling SendMessageAction – xiaoyi Nov 15 '12 at 14:38
  • Thanks XIAOYI ... I got the solution because of you... Thanks for supporting me.. – Fisher Man Nov 15 '12 at 15:14
  • although I don't know how you fix it, or what the exact problem is, congratulation. please vote up for the answers that helped you (and mark the one you think is the answer or answer the question yourself to close the question.) – xiaoyi Nov 15 '12 at 15:18
  • Now I need to logout my application when I closed the browser window..How can I do this XIAOYI... – Fisher Man Nov 15 '12 at 15:21

3 Answers3

1

First never use escape(), use encodeURIComponent() instead. see this for detail.

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

Second set the value in the <textarea> with .value instead of .innerText.

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

Third you need to setup Content-type:application/x-www-form-urlencoded in requestHeader when make a POST request. And send your payload with xhr.send(data) instead of passing it with query string.

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

All adds up, assuming your response is plain (that is not encoded in url encoding, it's unnecessary!)

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));
}

And your problems should solve themselves.

Community
  • 1
  • 1
xiaoyi
  • 6,641
  • 1
  • 34
  • 51
0

I can see you're already escaping the messages, but it looks like you also need to URL -encode and then -decode the messages. A + symbol is used in URLs to represent a space, so any actual + symbols will just be removed unless you encode them (to '%2B').

On the Javascript side you can use encodeURIComponent() and decodeURIComponent(), and on the Java side use URLDecoder and URLEncoder.

In your Javascript add something like...

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

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

...and in the Java code that send/receives the messages...

String inMessage = URLDecoder.decode(rawMessage, "UTF-8");
...
return URLEncoder.encoder(outMessage, "UTF-8");
Zutty
  • 5,357
  • 26
  • 31
  • Thanks for your reply, It worked in and + symbol displayed in client side Chatting but didn't shows the + symbol in Agent(server) side.. I am doing the chat application..Please help me... – Fisher Man Nov 15 '12 at 12:30
  • There is no need to send a encoded result to client! This is very wrong behavior. – xiaoyi Nov 15 '12 at 12:51
  • Thanks but now I having problem with the % symbol to display it in the text area.. – Fisher Man Nov 15 '12 at 14:37
  • Thanks XIAOYI ... I got the solution because of you... Thanks for supporting me.. – Fisher Man Nov 15 '12 at 15:13
0

The solution is,

I used the encodeURIComponent() and decodeURIComponent() instead of escape() , when sending the values to the servlet using AJAX.

My Script was like this,

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

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

Thanks for all who supported me ....

Fisher Man
  • 487
  • 1
  • 5
  • 14