I would like to show an image when the page loads in a servlet. Considering that this page is an html page, I don't really understand how the image to be displayed can be mentioned programatically(say, for example database.
Had it been a servlet, I would have just done something like the following which shows an image once the button is clicked. But how do I do the same for an html?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<HTML>");
out.print("<HEAD><TITLE>Upload Image</TITLE></HEAD>");
out.print("<BODY>");
out.print("<img src='images/imagethree.jpg' alt='image' />");
out.print("<img src='images/imageone.jpg' alt='image' />");
out.print("<input type=\"submit\" value=\"select\">");
out.print("</BODY>");
out.print("</HTML>");
out.close();
}
i am not sure but you can retrieve image from database at the time of init() or by using some super calling statements in doget() method like(super or this()) and after that you can assign the image.
Assume that your folder structure is something like this:
|_ Web Contents
|_ images
| |_ a.png
|_ WEB-INF
And your Context Path is SampleWebApp. following image tag will show the picture:
<img src="/SampleWebApp/images/a.png">
Related
Relatively new to Xamarin, hitting an issue with PushAsync and navigation I can't figure out.
I have a main navigation page, and then a "MyContentPage" that is responsible for rendering a dynamic list based on a supplied id. When the user clicks on a list item they go to a next (newed up) "MyContentPage" (same class) with a different id. Basically a recursive page hierarchy based on a local db.
Problem is that navigation seems to quickly get messed up in some way I can't work out. The pages get swapped around, or get lost. Navigating back to root, if I click back down again, it skips to a page that is further down etc.
So basically the one page apart from the main page (which has multiple navigationpages in tabs - though I only use one tab at this point) binds its controls to this function:
public async Task NavigateToContent(int contentId)
{
await ((Application.Current.MainPage) as TabbedPage)?.CurrentPage.Navigation.PushAsync(new MyContentPage(contentId));
}
The above is then used recursively. Ie. Similar controls bind to the same function until there are no further pages to click down to.
The MyContentPage constructor loads the model:
public MyContentPage(int id)
{
InitializeComponent();
_id = id;
BindingContext = viewModel = new ContentPageViewModel(id);
}
What is the issue here?
From what you mentioned in comments, the issue is caused by the navigation code called in the 'service' class. When you call the service method multiple times, it actually changes the current navigation stack in xamarin forms. Move the page navigation code from service class to viewmodel class.
Or try to put the page navigation source code into something like 'NavigationService' (one example is the one in https://learn.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/ ) and inject this service into your view model class.
OK so this all turned out to be an issue with concurrency.
The original button click was like this:
private void Button_Clicked(object sender, EventArgs e)
{
Task.Run(async () => await (BindingContext as ContentPageViewModel).ExecuteNavCommand(sender));
}
But this resulted in a UI operation happening on a different task
The event handler can be declared as async
The correction is
private async void Button_Clicked(object sender, EventArgs e)
{
await viewModel.ExecuteNavCommand(sender);
}
i am using iframe tag in order to call ActionMethod that returns FileResult to display PDF file. The issue is after it loads PDF document instead of showing pdf file name, it shows ActionMethod name on the top of the PDF file name in Chrome.
Razor Code:
<iframe src="#Url.Action("GetAgreementToReview", "Employee")" style="zoom: 0.60; -ms-zoom: 1; width: 100%;" width="99.6%" height="420" frameborder="0" id="agreementPdf"></iframe>
CS Code:
public ActionResult GetAgreementToReview()
{
Response.AddHeader("Content-Disposition", "inline; filename=Master-Agreement.pdf");
return File("~/Content/Master-Agreement.pdf", "application/pdf");
}
Image: As you can see in the screenshot, it shows 'GetAgreementToReview' i.e. ActionMethod name instead of 'Master-Agreement.pdf'.
Does anyone know how to fix this issue?
Thanks.
Sanjeev
I had a similar problem and found a solution after exploring almost everything the web has to offer.
You must use a custom route for your action and you must send the filename from UI into the URL itself. (Other parameters won't be affected)
//add a route property
[Route("ControllerName/GetAgreementToReview/{fileName?}")]
public ActionResult GetAgreementToReview(string fileName, int exampleParameter)
{
byte[] fileData = null; //whatever data you have or a file loaded from disk
int a = exampleParameter; // should not be affected
string resultFileName = string.format("{0}.pdf", fileName); // you can modify this to your desire
Response.AppendHeader("Content-Disposition", "inline; filename=" + resultFileName);
return File(fileData, "application/pdf"); //or use another mime type
}
And on client-side, you can use whatever system to reach the URL.
It's a bit hacky, but it works.
If you have an Iframe on HTML to display the PDF (the issue I had), it could look like this:
<iframe src='/ControllerName/GetAgreementToReview/my file?exampleParameter=5' />
And this way you have a dynamic way of manipulate the filename shown by the IFRAME that only uses the last part of an URL for its name shown on the web page (quite annoying). The downloaded filename will have its name given from server-side Content-disposition.
Hope it helps !
please try this code :
return File("~/Content/Master-Agreement.pdf", "application/pdf", "filename.pdf");
Other Helper Link : Stream file using ASP.NET MVC FileContentResult in a browser with a name?
I am trying to do registration example in magnolia. I have a registration form, on submission of form control should be transferred to my own written servlet.
snippet for form :
<body>
<form action="./register" method="post">
Name:<input type="text" name="name"><br />
Email Id:<input type="text" name="email"><br/>
<input type="submit" value="Register">
</form>
</body>
Registration servlet class:
public class Registration extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("This is registration servlet");
}
}
I have configured module descriptor :
<servlets>
<servlet>
<name>RegistrationServlet</name>
<class>com.rbt.registration.Registration</class>
<comment>registration servlet</comment>
<mappings>
<mapping>/register</mapping>
</mappings>
</servlet>
</servlets>
and I have also configured template definition.
But when I click on submit button. It shows error that resource not found.
Please help me.
In your template, when writing html for the form you can also use action="${ctx.contextPath}/register" to have form response directed to uri on which servlet is listening.
Also please go to config:/server/filters/servlets/ and verify that RegistrationServlet is correctly add there.
Same problem (although for different servlet) was also discussed at Magnolia Forum
HTH, Jan
The mapping you configured in the module descriptor will be relative to your context path. E.g. if your base url is http://example.com:8080/public ('public' being your context path), then your servlet will responding to http://example.com:8080/public/register.
Check if that url matches the url your form is submitting to. The action="./register" is a relative path and will depend on the path of the page that contains the form.
I wrote a servlet which takes the name of a image from the client and displays it to client by converting it to byte array.after displaying the image now when i am trying to print some text i m not able to do so.it simply doesn't print the text even after using PrintWriter.
I am using jboss application server to deploy it.
here is the servlet-Image.java:
package javaserv.image;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;
public class Image extends HttpServlet {
private static final long serialVersionUID = 1L;
public Image()
{
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String imagename = request.getParameter("imagename");
File fileimage = new File("C:/langs/projects/javaserv/"+imagename+".jpg");
byte [] imagearray;
imagearray = new byte[(int)fileimage.length ()];
FileInputStream fis = new FileInputStream (fileimage);
fis.read (imagearray);
response.setContentType("image/jpeg");
response.setContentLength((int)fileimage.length ());
ServletOutputStream out = response.getOutputStream();
int i=0;
while(i<imagearray.length)
{
out.write(imagearray[i]);
++i;
}
out.flush();
out.close();
out = response.getOutputStream();
response.setContentType("text/html");
out.println("<html><body>");
out.println("here is your image");
out.println("<p>");
out.println("</html></body>");
out.close();
}
}
"imagename" is the name of the image entered by client
You can either write your JPEG to the out, or the HTML, not both.
Your code writes the JPEG to the output, closes the output stream, then tries to open it again to write some HTML.
If you want to display a synamic image on a HTML page, you should be using a servlet for the image, and a JSP page for the HTML.
You basically need to let the client fire two HTTP requests. One to the HTML which in turn contains an <img> element which let the webbrowser automagically send another HTTP request to the image file.
First create a HTML page like follows:
<!DOCTYPE html>
<html lang="en">
<head>
<title>An image</title>
</head>
<body>
<p>Here is your image</p>
<p><img src="images?imagename=foo.gif"></p>
</body>
</html>
Where I assume that your image servlet is listening on an url-pattern of /images. Finally just give the enduser the URL to the HTML page (can also be a JSP page by the way) instead of the URL to the image. The enduser will then retrieve a HTML page with some text and an image.
That said, your imageservlet is honestly said pretty poor written in terms of speed, memory efficiency and resource handling. I'd suggest to have a look for this basic example how to do it properly.
You can inline the image, then the browser only does one request.
<img src="data:image/png;base64,....
I am new to web programming and Spring MVC 2.5.
I am not sure about my problem is spring sprecific or web specific in general.
I have a menu.jsp and I use jsp:include to include it in all my jsp.
<ul class="menu">
<c:url var="home" value="home.htm"/>
<c:url var="data" value="data.htm"/>
<li><span>HOME</span></li>
<li><span>DATA</span></li>
</ul>
When I hit my app the first time and calls http://localhost:8080/myapp/home.htm, everything went fine.
But when I click a link that brought me to a new url using multiactioncontroller.
#RequestMapping(value = "/epm/epmItemList.htm", method = RequestMethod.GET)
public String setupForm(Model model, HttpServletResponse response) throws IOException {
}
#RequestMapping(value = "/epm/epmdelete.htm", method = RequestMethod.GET)
public String setupForm(Model model, HttpServletResponse response) throws IOException {
}
And then I click, home again. I am getting a 404. I am not sure why, but when I check the link at my url it now it becomes:
http://localhost:8080/myapp/epm/home.htm
Spring is naturally saying no handler mapping can be found since I did not configure any mapping for these. How can I fix this problem? Thanks
Try the following change :
<ul class="menu">
<c:url var="home" value="/home.htm"/>
<c:url var="data" value="/data.htm"/>
<li><span>HOME</span></li>
<li><span>DATA</span></li>
</ul>
This way the links should be relative to your context and not relative to the local page.