I have a simple JSR 286 Portlet that displays a user manual (pure HTML code, not JSP).
Actually, my doView method, just contains this :
public class UserManualPortlet extends GenericPortlet
{
#Override
protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException
{
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(
"/html/usermanual.html");
rd.include(request, response);
}
}
This works as expected, however I'm having trouble when including images. I'm aware that the path to images should be something like :
<img src='<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/html/image.jpg")%>'/>
However, my HTML file containing the user manual is used elsewhere, so I would like to preserve it as a pure HTML file.
Is there a way to dynamically replace my classic images urls by something like the example above ? Perhaps using the PrintWriter of the response ?
If such thing is not possible, I thing I would need to generate a JSP file during my Maven build.
Any solution or ideas are welcome.
With JSR-268 portlets you have a better way of referencing resources: create ResourceURL using renderResponse.createResourceURL() and then you set the resourceID in the ResourceURL. That should give more consistent results across all portlet containers.
That said, if you want to modify the generated content from your usermanual.html but you don't want to convert it to a JSP then, instead of using a request dispatcher, I would load the file contents on my own, parse it at the same time that I do the URL replacements and then print all the contents to the portlet's response.
Related
I am trying to serve a static html file let's call it index.html for all dynamic urls like /tachyon/someId. This someId is generated dynamically. I have tried multiple ways to do this but all failed. This is what all I have tried.
Tried adding controllers.Assets.at(path="/public", file="index.html") for GET url /tachyon/*someId. This failed saying missing parameter someId.
Tried rendering index.html through render. This also failed since index.html is not a scala.html template.
Tried returning routes.Assets.at("index.html") through controller. This also failed since I want to return Result but the return type for the method is different.
Tried returning ok(routes.Assets.at("index.html") through controller. This also failed saying not a valid Call for ok.
It would be better if there is a way to do this through controller and returning Result from method in task helper class to task since I am returning Promise<Result> from method in task class.
I think you can use Twirl to generate the page. Since you want a static html, you can ignore the parameter in the body.
so in routes, add:
GET /tachyon/*someId somecontroller.index(someId)
in the controller's index function, you can return
Ok(views.html.somepage(someId))
And you create a somepage.scala.html Twirl function in views folder, but do not use someId in the body.
I got it working. Not sure if it is the correct solution or not. I rendered the index.html by converting it to a byte array and then using ok to render using ByteArrayInputStream. Something like this.
File file = Play.getFile("path to the file", Play.current());
byte[] byteArray = IOUtils.toByteArray(new FileInputStream(file));
return ok(new ByteArrayInputStream(byteArray)).as("text/html");
Let me know if there is any better way to do this without using scala templating.
Thanks
I am trying to create a pdf where user fills the fields and saves the data. I created a 'save' button on pdf using iText. I am settig the action of the button using PdfAction.createSubmitForm. While I am getting the formfield values of pdf while saving, I am losing the existing javascript on my JSP due to this button. I am using PdfAction.SUBMIT_HTML_FORMAT in the save button. What am I doing wrong here?
Thanks
The issue has been resolved. If I redirect the servlet action, the JSP displayed is then working fine.
Below is the code
HttpServletResponse response ;
response.setContentType("text/html");
response.setContentLength(13);
String url = new URL(request.getScheme(),request.getServerName(), request.getServerPort(),request.getRequestURI()).toExternalForm();
String target = url+"?action="ServletAction";
response.addHeader("Refresh", new StringBuilder(target.length() + 5)
.append("0;url=").append(target).toString());
ServletOutputStream out = response.getOutputStream();
out.print("<html></html>");
I've read your answer and although it solves your problem (and clarifies the initial problem), you are solving the problem in a really bad way. You are sending an almost empty HTML file <html></html> to the browser and you're expecting that the browser will respect the Refresh header. This is so unprofessional!
Redirecting is done like this:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
String url = new URL(request.getScheme(),request.getServerName(), request.getServerPort(),request.getRequestURI()).toExternalForm();
String target = url+"?action=ServletAction";
response.sendRedirect(target);
}
Replace doGet with doPost if your code snippet was part of a doPost method.
I'd like to response to a url request with a hardcoded but dynamic html response.
Are there better ways than doing following way?
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
//
}
?
One way is just to forward the response in your servlet:
getServletContext().getRequestDispatcher("mypage.html").forward(request, response);
It's unclear what you mean by "a hardcoded but dynamic html response."
If you mean that you have some number of existing HTML files, and want to pick one based on request parameters, then your servlet can use Class.getResourceAsStream() to load the files. You'll need to package the files on the classpath, which is easy if you use a tool like Maven, little more difficult with a tool like Ant, and hard to maintain if you're just making builds from Eclipse or the command line.
If you mean that you have a single template file and want to change the content in some way, use JSP.
i've got the follow issue: I wanna implement a file-reader in my GWT-application which allows the user to upload a file and work with it's content (in this particular case I'm talking about HTML). How do I realize that? As far as I know there is no way to use Java's usual BufferedReader.
The only thing I've discovered so far is the following:
try {
Request r = new RequestBuilder(RequestBuilder.GET, file).sendRequest("", new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
String text = response.getText();
System.out.println("1234");
}
#Override
public void onError(Request request, Throwable exception) {
System.out.println("456");
}
});
} catch (RequestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But this wouldn't be that helpful as far as there's no file-chooser dialog.
I'd realy appreciate your help!
Regards
There is no ready to use FileReader API in GWT. You can build your own on top of JS Api http://www.html5rocks.com/en/tutorials/file/dndfiles/ for Firefox/Chrome and you'll have to use some kind of plugin for IE (flash for example) in order to make it work everywhere
You could upload the file to the server using the FileUpload, then immediately download the file from the server to the client, using RequestBuilder or GWT RPC, where you can then work with it. You wouldn't be able to use InputStreams or Readers as these are not actually emulated by GWT (not strictly true, see below).
If it's HTML you need to be careful - there are all sorts of security implications in allowing user generated HTML onto a page. The GWT SafeHTML mechanism can be used to address some of these issues but it is still up to you to manage this.
As an aside it is trivial to create an implementation of streams/readers that does work in GWT - the java.io.InputStream pretty much works in GWT as is but I am not sure if you can just copy this class for licensing reasons. The Apache Harmony project includes implementations that you may be able to "copy" without these restrictions.
Here is another way to read a file on the client side using the File Reader using the GWT Elemental API.
https://gist.github.com/branflake2267/180b69b9a29987214643f62fb279151f
You can't implement client-side file reader, just because of limitations of JavaScript. Client-side GWT code is compiled to JavaScript code and then JavaScript is executed within the browser. It has no access to local files or whatever.
Check this for file uploading: http://gwt.google.com/samples/Showcase/Showcase.html#!CwFileUpload
Did you have a look at this: https://developers.google.com/appengine/kb/java?hl=en#readfile ?
I have a web application that can display a generated PDF file to the user using the following Java code on the server:
#Path("MyDocument.pdf/")
#GET
#Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
PdfGenerator generator = new PdfGenerator(getEntity());
generator.generatePDF(output);
} catch (Exception e) {
logger.error("Error getting PDF file.", e);
throw new WebApplicationException(e);
}
}
};
}
This code takes advantage of the fact that I only need so much data from the front end in order to generate the PDF, so it can easily be done using a GET function.
However, I now want to return a PDF in a more dynamic way, and need a bunch more information from the front end in order to generate the PDF. In other areas, I'm sending similar amounts of data and persisting it to the data store using a PUT and #FormParams, such as:
#PUT
#Consumes({"application/x-www-form-urlencoded"})
public void put(#FormParam("name") String name,
#FormParam("details") String details,
#FormParam("moreDetails") String moreDetails...
So, because of the amount of data I need to pass from the front end, I can't use a GET function with just query parameters.
I'm using Dojo on the front-end, and all of the dojo interactions really don't know what to do with a PDF returned from a PUT operation.
I'd like to not have to do this in two steps (persist the data sent in the put, and then request the PDF) simply because the PDF is more "transient" in this uses case, and I don't want the data taking up space in my data store.
Is there a way to do this, or am I thinking about things all wrong?
Thanks.
I can't quite understand what do you need to accomplish - looks like you want to submit some data to persist it and then return pdf as a result? This should be straightforward, doesn't need to be 2 steps, just submit, on the submit save the data and return PDF.
Is this your problem? Can you clarify?
P.S.
Ok, you need to do the following in your servlet:
response.setHeader("Content-disposition",
"attachment; filename=" +
"Example.pdf" );
response.setContentType( "application/pdf" );
Set the "content-length" on the response, otherwise the Acrobat Reader plugin may not work properly, ex. response.setContentLength(bos.size());
If you provide output in JSP you can do this:
<%# page contentType="application/pdf" %>