Why Servlet program outputting HTML text as it is? - java

I created one program that prints 'Welcome to our site' text on browser using servlet. It works fine inside the eclipse default browser but when I use that URL to other browser it displays text as below:
And below is the image of the code that is working well inside eclipse browser
And my code is as follows:
public class WelcomePage extends HttpServlet {
#Override
public void init() throws ServletException {
}
#Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("<h3>Welcome to our site<h3>");
out.println("<form>");
out.println("</form>");
}
#Override
public void destroy() {
}
}

After adding res.setContentType(text/html); problem resolved :)
Before sending data to client (displayed by Browser on client machine), the Servlet container informs the client browser of what type of data is being sent now. The data that can be sent may be simple plain text, html form, xml form, image form of type gif or jpg, excel sheet etc. To send this information, the Servlet container uses response object with the method setContentType().
Some examples :
response.setContentType("text/html");
response.setContentType("text/plain");
response.setContentType("text/css");
response.setContentType("application/html");
response.setContentType("image/gif");
response.setContentType("application/zip");
response.setContentType("application/pdf");

Related

Send additional data to Java server-side using Dojo file upload client-side

I need to send additional data to the server side while uploading files with dojo. How do I do that?
I'm using the upload method of the dojo file uploader. I want to dynamically pass an additional variable for file destination on the server side.
My JavaScript code:
function(Uploader, FileList, dom, on, Carousel, ContentPane, SwapView) {
dojo.ready(function() {
var form = dojo.byId("myForm");
var uploaderDIV = dojo.byId("uploader");
up = new Uploader({
label: 'Attach Files',
multiple: true,
showInput: 'before',
name : 'uploadedfiles[]',
url: '/TestServer/rest-services/submitForm',
}).placeAt(uploaderDIV);
And my server side code:
#Path("/submitForm")
#POST
#Consumes("multipart/form-data")
#Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public Response uploadFile(MultipartFormDataInput input) {
String fileName = "";
Map<String, List<InputPart>> formParts = input.getFormDataMap();
I would recommend using Apache FileUpload here, as it will greatly simplify your life. In my implementations I have set up a servlet mapped to the upload URL and handled the request in a doPost method:
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
}
}
Piggybacking on the information provided by bishop directly in response to your question, you can attach URL parameters using the ? and & characters (i.e. ?one=one&two=two). On the server side you'll need to read those URL parameters from the request:
String one = request.getParameter("one");
String two = request.getParameter("two");

Render HTML response from remote call to the client

I have a working servlet wich originates back from this template:
http://www.objectdb.com/tutorial/jpa/eclipse/web/servlet
So the basic rountrip works.
I added a new feature where I POST data to the servlet, construct a call/request out of the data to a remote http server, retrieve the response-html-string (the content of the website I requested) and want to show this HTML String now as response to my original POST call.
I tried it like this:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
boolean showDetails = Boolean.valueOf(request.getParameter("showDetails"));
if (showDetails) {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
return; // <----------------- if showDetails then this is the end of doPost
}
// Display the list of guests:
doGet(request, response);
}
When I press the link that creates the POST event I see in the logfile, that "loadDetails" has succesfully loaded the content from the remote server, but the browser window does not refresh. Why?
PS: a simple redirect to the other side is not possible for technical reasons.
Try making a ajax request to your servlet which gives to html content as string sent it back to ajax call and set it to innerHTML of a div element.
I changed to use GET instead of POST and I used a separate Servlet for this kind of call. This solved my problem.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
}

Server Sent Event HTML5 error(the resource from this url is not text)

I wrote this Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter printWriter=response.getWriter();
printWriter.write("Hello!");
}
and also this java script in index.jsp:
<script>
var resource = new EventSource("/servlet");
resource.onmessage = function (e) {
document.getElementById("container").innerHTML = e.data;
}
</script>
in order to create demo on server-sent events in html5. I inspected the jsp page in firefox and I got this error: the resource from this url is not text and nothing shows up. by the way request status is 200, OK. What is wrong with that?
Try to change the response header
response.setContentType("text/event-stream");

How to make the server download an image file that was uploaded in an HTTP PUT request from the client?

I need to implement a web server in Java. The web server should download image files that were uploaded by the clients in an HTTP PUT request. What is the procedure for doing it? What Java classes should I use?
Also, if you can recommend a good book that covers these topics it would be great. But the specific question is more important right now.
You should read about Java servlets and servlet containers. Start by implementing a simple servlet that returns "Hello world" string.
Here is the shortest upload/download servlet ever:
import org.apache.commons.io.IOUtils;
#WebServlet(urlPatterns = {"/test"})
public class DownloadServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File f = new File("test.txt");
resp.setContentLength((int) f.length());
final FileInputStream input = new FileInputStream(f);
IOUtils.copy(input, resp.getOutputStream());
input.close();
}
#Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final FileOutputStream output = new FileOutputStream("test.txt");
IOUtils.copy(req.getInputStream(), output);
output.close();
}
}
First hit:
$ curl -X PUT -d "Hello, servlet" localhost:8080/test
To store given text in a file named test.txt somewhere on your disk. Then simply enter localhost:8080/test in your browser. I think it is a good start.

how to display a PDF through an xhtml

I'm trying to display a PDF report on a webApp, I've been following this tutorial here
and it creates the pdf file fine, but I'm having trouble trying to display it in the browser. In my xhtml I have a button, once that button is clicked, a function calling the servlet is called. it goes into the servlet and created a pdf document fine. but I can't seem to figure out how to display it on the screen. is there a way to show the document on a new browser window, or new tab? or even the same one.
I'm working with Java Server faces 2.0 in Eclipse. and have a Tomcat 7.0 server.
on my webxml I added the following code specified in the example:
<servlet>
<servlet-name>PdfServlet</servlet-name>
<servlet-class>com.bravo.servlets.PdfServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PdfServlet</servlet-name>
<url-pattern>/PdfServlet</url-pattern>
</servlet-mapping>
and my servlet looks like this ( pretty much the same as the example):
#WebServlet("/PdfServlet")
public class PdfServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Font font = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
/**
* Default constructor.
*/
public PdfServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
invokePDFViewer(response);
Document document = new Document();
try{
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
addContent(document);
document.close();
}catch(DocumentException e){
e.printStackTrace();
}
}
private void invokePDFViewer(HttpServletResponse response){
response.setContentType("application/pdf");
}
private void addContent(Document document)throws DocumentException {
PdfPTable table = new PdfPTable(2);
Paragraph paragraph = new Paragraph ("Este es un parrafo en celda 1", font);
table.addCell(paragraph);
table.addCell("2");
table.addCell("3");
table.addCell("4");
table.addCell("5");
table.addCell("6");
document.add(table);
}
}
the xhtml I'm calling the servlet from looks like this:
....
function callPdfServlet(){
$.ajax({
type: 'POST',
cache: 'false',
data: 'codeType=notUsed',
url: '/miloWeb/PdfServlet',
async: false,
success: function(data){
},
error: function (xhr, ajaxOptions, thrownError){
alert(ajaxOptions);
}
});
}
.....
<h:commandButton id="reportButton" action=" " styleClass="button" value="get Report" onclick="callPdfServlet();"></h:commandButton>
So at the end, all it does right now is I go into the xhtml in my browser, click on the button, and it hits the servlet, goes through the code, and then thats it. my browser just reloads the screen and nothing else happens. so i need to show the pdf I just created. Thanks in advance for your help!
//************************************************************************************
EDIT 01/02/12:
after reading this and this
I can see that the action in the commandButton will take me to the "response".xhtml with "response" being a string that I either hardcode in, or is returned by an action in a Managed Bean. that response ( if not put in my faces-config file ) will take me to the page IF it's in the same folder as my current page.
so I believe that when I put "miloWeb/PdfServlet" as a response for the action, It looks for the page in the same folder ( which it's not) and since it doesn't find anything just reloads the page. And since I have a break point In the servlet, I am 100% sure it's not hitting it.
so my question is: How do I redirect my page to miloWeb/PdfServlet??
to clarify, it works fine if I put the name of another xhtml in the same folder. so it is working that way.
//This is what I tried just for reference:
Instead of going through the ajax call I've changed the button to
<h:commandButton id="reportButton" action="/miloWeb/PdfServlet" styleClass="button" value="get Report"></h:commandButton>
but it Just reloads the page and doesn't take me to the Servlet.
so another thing I tried was tried to go thought the action of the button calling a Managed Bean:
public String actionPdf(){
return "/miloWeb/PdfServlet";
}
again,same thing, the function returns the string, but it still doesn't take me to the servlet.
Just post a regular form rather than posting in AJAX, and the browser will load the response from your PDF servlet in the page rather than loading it from JavaScript and ignoring it completely:
<form method="post" action="/miloWeb/PdfServlet">
<input type="hidden" name="codeTyped" value="notUsed"/>
<input type="submit" value="Show PDF"/>
</form>
in the action of the commandButton, I had to type this in:
public String doThis(){
String url = "url of your servlet";
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().dispatch(url);
}catch (Exception e) {
e.printStackTrace();
}
finally{
context.responseComplete();
return "";
}
So with this, I get the context root and redirect it there. url being /PdfServlet

Categories