how to append getRequestDispatcher with extra data in java? - java

So Basically I have:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/zips/packet.html").forward(request, response);
return;
}
As you can you can see when a request is made for this servlet, It responds with packet.html file. To be precise, inside my packet.html I have a video element with src="" which I need to fill it by users requested url.
Question: How do I send a little extra data saying video source to the client, So in my client side it could change the video source from src="" to src="actual video source"
I TRIED:
String video_source = "/zips/video.mp4";
response.getWriter().append(video_source);
request.getRequestDispatcher("/zips/packet.html").forward(request, response);
With this method I can see my packet.html being received in my front-end But I can't find the video_source. FYI: don't know how to receive the video_source.

Well, To satasify your demand you can follow many apporoaches. One approach that I would suggest would put into consideration whatever you've already started
As Below
Step 1. Forward your request and response objects into packet.jsp,instead of into packet.html
Step 2. inside packet.jsp grab the input from user and send it with
the request object from packet.jsp
Step 3. Write a servlet class that process the request object from
packet.jsp and send the video as mulitpart file with the response.
Moreover, Do some research on how to use jsp's and servlets
The second approach would be to write client side javascript code that send ajax request to grab the video in a second call. For this you might even consider some client side frameworks and libraries(like jquery, angular, etc) that ease your work.

You could do the following:
Pass that additional information via request attribute (request.setAttribute())
Use some dynamic handler (like a servlet or JSP) to serve /zips/handler.html
Use request.getAttribute() in that handler.
So:
in your initial servlet, put
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("real_source", /some real source/);
request.getRequestDispatcher("/zips/packet.html").forward(request, response);
return;
}
In your /zips/packet.html you just use request.getAttribute("real_source") to generate the html attribute you need.

Related

what happens to the html codes written inside the servlet program

I would like to know what happens to the html codes written inside the servlet?
What is the need of writing like this?
Sample code:
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
out.println("<html>"<head><title>"Welcome"</title></head>\n" +
"<body><p>Welcome to servlet</p></body></html>");
}
The HTML code written in the servlet goes to the Client through the Container (or through web server talking with the Container) which is responsible to send a response back to the Client (browser) that, in turn, will render the HTML to the user.
Here you will find a nice explanation of what is going on behind the scenes: How do servlets work? Instantiation, sessions, shared variables and multithreading
An HTML page is nothing else than plain text following HTML syntax.
Hence, anything you give as a response to a HTTP request, being plain text following HTML syntax (like your String does), IS an HTML page, provided you tell the caller what is the content type of the response :
response.setContentType("text/html");

Servlet that receives a XML based request and then make a new XML file to send back as the response

I am trying to create a Servlet that receives a XML based request and sends a XML in the response. I am new to Servlet first of all.
I have created the below Servlet in which I thought I am creating a Servlet that receives a XML based request in the doGet method and then in the doPost method, I can parse that XML file and then make a new XML file to send back the response. But I believe my understanding is wrong.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/xml");
PrintWriter writer = response.getWriter();
writer.println("<?xml version=\"1.0\"?>");
writer.println("<request uuid = \"hello\">");
writer.println("<app hash = \"abc\"/>");
writer.println("<app hash = \"def\"/>");
writer.println("</request>");
writer.flush();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request);
//parse the xml file if my understanding is right?
}
Can anyone provide me a simple example of this? I am just trying to create a Servlet that receives a XML based request (I am not sure of this, how can I make a servlet that can receive a XML based request), xml should be like above in my example.
And then parse the above XML file and use some content from that XML file to make a new sample XML file which I will be sending back as the response from that same Servlet.
Any help will be appreciated on this as I am slightly new to Servlet. This is the first time I am working with Servlet.
Update:-
I haven't got a proper answer on this yet. Any simple example will make me understand better. Thanks
You probably want to do everything in the doPost() method. Just one of doGet or doPost will be called, for a given HTTP request, depending on if the caller specified GET or POST in their request.
Your creation of the XML response looks basically ok. That is the general approach anyway, write the result XML to the response writer. If this is for production code, and not just a learning exercise, then you should use a library to create the XML, not just manually build it from strings. See "HOWTO Avoid Being Called a Bozo When Producing XML" http://hsivonen.iki.fi/producing-xml/
As far as parsing the incoming request:
BufferedReader reader = request.getReader()
Use that to read the characters of the incoming XML, and pass them to your XML parser.

request dispatcher forward is not forwarding after include of any servlet

Someone please HELP ME.
private void forward(String address,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
getServletContext()
.getRequestDispatcher("/" + address)
.forward(request, response);
}
private void include(String address,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
getServletContext()
.getRequestDispatcher("/" + address)
.include(request, response);
}
These two functions have been written in every servlet in my project and the problem is that when I have used these two functions in a servlet at first include("servlet/abc",request.response); and after it have used forward("servlet/def",request.response); so using Netbeans 7 I have step by step watched that forward is not forwarding the control of servlet but when I don't use include before the forward its forwarding the control.
So I want to know that why it is happening and what's the reason and how can I do forward after include any servlet.
Please someone HELP ME ...it's an interesting question.
include("servlet/abc",request, response);
forward("servlet/def",request, response); //HERE IS PROBLEM NOT FORWRDING AFTER INCLUDE
Regardless of exactly why you seem to observe this behavior, what you're attempting will never work. Per the contract of RequestDispatcher.forward(), "If the response already has been committed, this method throws an IllegalStateException," and "Uncommitted output in the response buffer is automatically cleared before the forward."
Therefore, whether the forward succeeds or not, you'll never be able to successfully send content back to the user both before and after a forward. This is because the purpose of a forward is to allow "one servlet to do preliminary processing of a request and another resource to generate the response", not to let two different servlets generate different parts of the response. In the Servlet model, generating a response always belongs to exactly one servlet.
If you don't know what "committed" and "uncommitted" means, it's referring to whether the response status and headers have been sent to the user yet. When you're writing a response, you're actually writing into a local buffer. Nothing will necessarily be sent immediately. As long as everything you've written is still local, you're free to do whatever, including resetting the buffer and starting over, like a forward does, but as soon as something is sent off, you're committed and can no longer change what you were going to do. A response can become committed (i.e. be all or partly sent to the user) in a few ways, including filling up the buffer so that it has to be sent to make room for more content, flushing the buffer manually, or flushing the Writer or OutputStream of a response.
Ultimately, what's probably happening in your case is that you're writing some stuff using an include, and it's causing the response to be committed, either because you've filled the buffer or because I seem to recall that an include generally causes an automatic flush (not sure about documentation on this one). Then when you try to forward, it's throwing the required IllegalStateException, which you should probably see in your logs somewhere, but won't cause the typical 500 response status since, as I've discussed, you've already committed with some other status code.
You cannot change the response status or state once response is committed. When you include some page using request dispatcher you are actually committing response and data is starting to be sent to client. After that you are not allowed to make a change of response status to 302 which is required for redirect.
You will get an error java.lang.IllegalStateException: Cannot forward after response has been committed if you try that.
RequestDispatcher has only two methods:
public interface javax.servlet.RequestDispatcher {
public abstract void forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse) throws javax.servlet.ServletException, java.io.IOException;
public abstract void include(javax.servlet.ServletRequest, javax.servlet.ServletResponse) throws javax.servlet.ServletException, java.io.IOException;
}
You are giving it as
include("servlet/abc",request, response);
forward("servlet/def",request, response);
but in the API it is mentioned only servlet request object and response object as parameters, so I guess you should remove your url from there. Correct me if I'm wrong, as I'm also learning.

A one step upload for uploading images using google app engine

I am trying to implement a very basic functionality of uploading images from Android,iPhone and web clients to the google app engine. I did an initial version of the implementation thanks to this blog:
However there always seems to be a 2 step process to uploading an image:
Get the initial upload URL to POST to using the createUploadUrl(). I am attaching the fragment of code which I use :
public class CreateUploadUrl extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String uploadURL = blobstoreService.createUploadUrl("/image/uploadImage");
resp.setContentType("text/plain");
resp.getWriter().println(uploadURL);
}
}
POST the image using the URL which you just "got"
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
BlobKey blobKey = ParameterExtractor.getBlobParameter(req, "blob-key", blobstoreService);
if (blobKey == null) {
log.info("blob Id is null. POST failed");
} else {
log.info("ze business logic");
}
}
My question is if it is possible to do it in one step since right now all clients need to do a http GET to get the upload URL and then a http POST to POST the image.
Is it not possible to just do one Http POST with a predefined URL.
Thanks
Rajat
This is possible, with limitations. You can bypass the UploadUrl mechanism by creating blobs directly in your servlet using the (currently experimental) createNewBlobFile API. In your mobile app(s) create an HTTP request encoded as multipart/form-data, and teach your servlet how to decode such a thing (consult e.g. How to upload files in JSP/Servlet?). Be aware that HTTP requests are limited to 32MB; with form encoding the amount of binary data you can upload will be less than that.
Sure you can do it with single POST. For example you have user that have an id. This user select image and you send in POST image data and user data on client side.
On server side (GAE) you have url for image uploding (your_host/imageUpload) and server or Spring controller that read data from request and write it to Blobstore.

Get URL # hash with JSTL

To get the URL hash # in javascript you can just do:
window.location.hash
Is there a similar simple and easy way to do it in JSTL?
Example of a URL I have: http://hatsos.com/#somehashname
If there is not a built-in easy method, how would I go about getting the URL and then parsing the hash out of it?
The only way to get the hash fragment identifier in the server side is to let the client side send a HTTP request with the value as a request parameter whenever it has changed. For example, with Ajax during the window.onhashchange event. I see in your question history that you're familiar with jQuery. Here's a kickoff example:
window.onhashchange = function() {
$.get('someservlet', { 'hash', window.location.hash }, function(response) {
// ...
});
}
with
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hash = request.getParameter("hash");
// ...
}
To cover lack of IE6/7 support for window.onhashchange, consider jQuery hashchange plugin.
You're talking about a URI Fragment id, and most user agents don't even send that to the server, so you can't really get it there. JavaScript can access it because it runs on the client side.

Categories