I'm doing a project in java in which I implemented a chat, everything works perfectly only when I receive messages I can not print the web page.
In my Servlet I have a callback method that is invoked when messages arrive, in fact if you see mold them in the console, but if you are sending them to the jsp using the RequestDispatcher can not get them to see.
I would like to know if there is a system that the jsp page listens for a callback method in the servlet?
Obviously, this system should not be constantly invoke the class I have something absurd like that.
So that I can print the messages I receive.
This is my code I put a comment where I should print eventually find in jsp page, or do a redirect by passing parameters post or get
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strJid = (String) request.getParameter("jid");
String strMessage = (String) request.getParameter("textMessage");
Connection connection = (Connection)getServletContext().getAttribute("classConnection");
ChatManager chatManager = connection.getChatManager();
Chat newChat = chatManager.createChat(strJid, new MessageListener(){
#Override
public void processMessage(Chat chat, Message message){
//from here I have to print the message.getBody () in jsp page,
//how can I do? I'm happy also reload the page and pass as a parameter to get or post
}
});
try{
newChat.sendMessage(strMessage);
}
catch(XMPPException e){
System.out.println("Errore invio messaggio");
}
}
To implement a callback method in your servlet to receive chat messages is the wrong approach. A servlet will be called once for a browser request, creates the HTML page and send it back to the browser. After that there is no such kind of a connection between the servlet and the web page.
In traditional web programming all communication between browser and server is intiated by the client. There is no way for the server to send a message to the client. Workarounds are long polling requests.
But nowadays you can use Websockets. There are several frameworks supporting Websockets both for client and server side. One of them is Atmosphere. Their tutorial is a chat application.
Related
I was wondering what approach I should use to be able to receive messages through Nexmo. Has anybody had any experience on this issue because Nexmo doesn't seem to have clear documentation on how to receive messages through there libraries. Any help would be wonderful.
For each Nexmo number you own, you can configure a URL which will be called by Nexmo when an SMS is received at that number. The GET request will contain information about the received SMS as request params.
A little complexity is added (while you're developing) because Nexmo needs to be able to reach a URL that is hosted on your development machine, which is probably not publicly available on the Internet! For this, you'll want to run something like Ngrok which will provide a tunnel to a port on your local machine with a public URL.
I'd recommend starting with a simple servlet that prints out its params:
public class InboundSMSServlet extends HttpServlet {
#Override
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException {
System.out.println("Received: " + req.getMethod());
for (String param : Collections.list(req.getParameterNames())) {
String value = req.getParameter(param);
System.out.println(param + ": " + value);
}
}
}
... configure it to a convenient URL ...
<servlet>
<servlet-name>inbound-sms</servlet-name>
<servlet-class>getstarted.InboundSMSServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>inbound-sms</servlet-name>
<url-pattern>/inbound</url-pattern>
</servlet-mapping>
Run both your servlet container and ngrok at the same time and check that the ngrok URL with /YOUR_PROJECT_NAME/inbound at the end works as expected. Then go into the Nexmo dashboard, Your Numbers, and hit Edit on the number you want to receive SMS messages to. Enter the Ngrok URL you tested above.
Now send an SMS to the number you configured, and you should see the contents of your message printed to the console; something like:
Received: GET
messageId: 0B0000004A2D09D9
to: 447520666777
text: Hello Nexmo!
msisdn: 447720123123
type: text
keyword: HELLO
message-timestamp: 2017-04-27 14:41:32
The details of how this works are documented on the Nexmo site
I have a Java Servlet application running on JBoss 4 and this application receives POST request from another service. I want to acknowledge back to this service before processing. Is it fine to do the following?
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
readReceivedPOSTData();
//send response
PrintWriter out = res.getWriter();
out.print("ack");
out.close();
//Process
processData(); //takes long time
}
I appreciate your help. Thank you.
The basis is ok.
Just some tips:
Use an identifier in the request so you can check in the future the status of that request.
Start another thread to process the data or use a jms queue
remember that you can't write additional data to the response in the processData() method
I want to open a website in web browser. I know it is easy but i want to do it in different way ...
It is like proxy server .I have made a java code that will get content(source code) of webpage and when browser request localhost on particular port number this code writes source code in browser. But instead of getting web page I am getting source code of webpage in browser and also i want to make a request from java code as a illusion of browser means server should feel that that request is made from a browser and not from java console.
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String args[]) throws Exception{
URL ul = null;
HttpURLConnection ulc = null;
ServerSocket server = null;
Socket client = null;
DataInputStream in = null;
DataOutputStream out = null;
String c = null;
server = new ServerSocket(9898);
System.out.println("Server is waiting for clients on port no 9898....");
while(client == null){
client = server.accept();
}
System.out.println("Connected.....");
out = new DataOutputStream(client.getOutputStream());
ul = new URL("http://www.google.com");
ulc = (HttpURLConnection)ul.openConnection();
in = new DataInputStream(ulc.getInputStream());
while((c = in.readLine())!=null){
out.writeBytes(c);
}
in.close();
out.close();
client.close();
}
}
Loading web pages is not quite as simple as you probably think. Both the browser and the server use a protocol called HTTP. In simple terms, the browser sends a request consisting of a request line, headers and sometimes data, and the server responds with a response line, headers and data. Most web pages also have related resources that need to be loaded for displaying the page (such as images, stylesheets and scripts), and each resource is loaded through a separate request.
Your program only accepts one request, completely ignores the details of the request, and then loads a fixed web page and sends it as the response. The way you are loading the web page (with a URL), you are only getting the data part of the response (the page source); the response line and the headers are missing. The headers are very important as one of them (named "Content-Type") specifies what kind of resource it is - web page, image or something else. Without it, browsers usually assume the data is plain text and display it accordingly.
So if you want your experiment to work better, you need to make sure you send a complete and valid HTTP response to the browser. You can probably reconstruct the response line and headers from the HttpURLConnection object. Or you can use sockets directly to load the web page.
A better solution would be to use a java web server (such as Jetty) in which you'd run a servlet that loads the remote page using an HTTP client library (such as Apache HttpComponents) and does the necessary processing of addresses and headers. But.. small steps :)
I am writing a REST server and client for it on Java. I do this for educational purpose.
My server is a web application that handle request from clients via servlet. After that it opens a storage conenction, retrieve data and send it as a json.
My client is a web aplication which has some simple web pages. User click a button, servlet on client handle and send(sic!) request to the server.
May be this way a little bit odd because on the client side moderbn world write just html pages with rich JS code, e.g. Bootstrap, Backbone Angular etc.and server side is wrote via JAX-RS or Spring, but my aim is to write this pet project on pure java as simple as it can be.
I faced with an issue that I don't understand how to send request from client side to the server side. I have received request from user in servlet and I want to send a reponse to the server.
What are possible ways to do that and what is the best one?
Thanks.
You can use Jquery Ajax to call your webservices with parameter required on server side. Update your view/jsp/html based on the data get from servlet.
Ajax Call from javascript :
function onButtonClick(){
$.ajax({
type: "post", //method type
dataType: "json", //response data type
url: ajaxUrl, //your webservice URL
data: "jsonobj", // Data to be send to server
success: function(response) // call back function after get successfull responce
{
// Process JSON response here
}
});
}
Your servlet code :
public class ResellerServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
//Process request here
// Convert your response in JSON and send it back to client
}
}
I'm going to make streaming. I have .jsp file and at the end of .jsp file I include my Async Servlet using following code:
<jsp:include page = '/simple' flush = 'true' />
So I want when whole page is loaded to open an infinite Async request, which will handle Async response.
Here is my Servlet code:
public class SimpleAsyncServlet extends HttpServlet {
public static AsyncContext ctx;
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
ctx = req.startAsync();
ctx.setTimeout(0);
}
}
From other java classes I'm using the static SimpleAsyncServlet.ctx.getResponse.getWriter() to println some javascript code to current page. It is working without any problem, but browser keep showing that it's loading. According to Async idea page should be loaded and this Async Request should stay alive in background and..that's it, but no....browser keeps loading the page till forever (timeout is 0, cos I want to have infinite open reqeust)
Where am I wrong and how can I make this permanent request without this browser loading ?
P.S. I have tried to access my servlet direct from url (localhost.../simple) and then I see nothing printed on page. It keep loading till forever.
You are trying to achieve the impossible.
The browser will showing that the page is loading until it knows it has received the full request by one of the following methods:
it has received the number bytes stated in a Content-Length header
the connection is closed
it received an end chunk when using chunked encoding
Since you want an 'infinite' response, none of the three options above is ever going to happen.