what happens to the html codes written inside the servlet program - java

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

Related

invoke jsp from java code and get output

I have a JSP page that show data in some formatted way. the browser can call spring showInfo.do and it is forward to that JSP.
i.e.
public showInfo(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("info.jsp");
dispatcher.forward(request,response);
}
The output of the JSP is html.
Now I want to save this JSP output manually from my java server side code (not in a servlet context), something like this:
void saveInfo() {
params.setParameter("info1", "data");
String responseStr = Invoke("info.jsp", params);
//save responseStr to disk
}
I want to be able to save the html page on disk from a service and make it look the same as a user can see it from a browser. So if the server is offline a user can double click on the saved html file and see in his browser the last info.
Any idea how this can be done?
Oups. The servlet specification requires the servlet container to be able to execute a JSP file. This is commonly done by converting the JSP to plain Java and the generating a servlet class file.
If you are outside of a servlet container you must:
* either fully implement a JSP execution environment, for example by using sources from a servlet container like Tomcat
* or rely on a servlet container to convert the JSP file to a .java or .class servlet and then use the Servlet interface methods on it
Alternatively, you could try to use a headless browser to capture the output of the application.

how to append getRequestDispatcher with extra data in 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.

How can I pass information from a servlet to JSP and back?

I've been scratching my head for hours now. I'm working expanding a web app and I've come across this problem:
I have a class called SelectionHandler which uses cases in a doPost() method to forward to the right app:
private void userEditor(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("destination", "edit_user");
HttpRedirectHandler.forwardToURL(request, response, "EditUser");
}
Now this servlet is designed to be re-used, so it will decide where to forward the user next:
String header = response.getHeader("destination");
if (header.equals("price_manager")) {
destination = "PriceManager";
} else if (header.equals("new_user")){
destination = "NewUser";
};
and then
HttpRedirectHandler.forwardToURL(request, response, destination);
But before that happens I've been redirecting the user to a JSP page. Problem is, when I do that the information where I wanted to go gets lost.
Can someone advise me as to what is the best way to retain this information? I tried reading the header and writing it again to a header in the JSP page, but I'm not sure that is actually possible.
example:
In your servlet:
request.setAttribute("HelloKey","Hello World!");
In your jsp:
String myHelloString = (String)request.getAttribute("HelloKey");
or you put it in the session:
request.getSession(true).setAttribute("HelloKey","Hello World!");
and in the jsp:
String myHelloString = (String)request.getSession().getAttribute("HelloKey");
I agree with the previous post, you can store information in request, session, or application scope.
I would like to expand on the answer as follows:
From your statement about "I tried reading the header and writing it again to a header in the JSP page", it appears you may not have enough of a grasp on JSP. I suggest you go to amazon.com and look for a JSP book that has good reviews. Then, read it cover to cover. It will save you countless hours of experimenting with the technology and not getting anywhere.

JSP Page Forward Output Includes content from previous form

The problem is: I have a page1.jsp which is submitted and forwarded to page2.jsp. The problem is that the forwarded output should be only the content in page2.jsp, instead of that is showing me content from page1.jsp and immediately the content from page2.jsp
I'm using requestDispatcher.forward(String) but i don know why is this happening
PS: I'm using JE 1.4
Well it seems you have got the method signature incorrect . As per the javaee 1.4 API:
public void forward(ServletRequest request,ServletResponse response)
throws ServletException,
java.io.IOException
Hence your code should be :
RequestDispatcher dispatcher = request.getRequestDispatcher("page2.jsp);
dispatcher.forward( request, response );
Better , you can use the <jsp:forward> standard action.
The JSP that contains the action stops processing, clears its buffer, and forwards the request to the target resource. Note that the calling JSP should not write anything to the response prior to the action.
Suggested Reading:
How to avoid Java Code in JSP-Files?

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.

Categories