Error while displaying image in jsp - java

First of all, i read tons of posts regarding this but i can't manage to get this working.
I'm really new to jsp and web apps. All i wanna do is to display a simple image.
I have this code in the servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession sesion = request.getSession();
String filePath = getServletContext().getRealPath("image.jpg");
System.out.println(filePath);
sesion.setAttribute("image", filePath);
response.sendRedirect("products.jsp");
}
And this code in the jsp:
<img alt="logo" src="${image}"/>
And the folders in my web app are this:
folders image
And finally, when my page loads, this is what i get:
image does not display
I wonder what is the error here? Why it is so complicated (maybe it's not, but i really tried many ways and non of them worked) to display a simple image?
Thanks in advance for your help!
PS: the folder is correct, it prints without problem in the println()

getRealPath() gets you the real path in the file system.
When you reference any resource (image, js, css) inside a web it is supposed to be accesible via web.
If you click "view source code" in your browser you'll probably see the fil system path in the tag:
<img alt="logo" src="C:/whatever-your-path-is/image.jpg"/>
But what you need is the url path (full or relative) of the resource.
Try this instead:
sesion.setAttribute("image", "resources/images/image.jpg");

Related

How to properly show profile picutre for user

It seems that my Google-fu has failed me since I can't find similiar problems or solutions.
I want to show users image in the users profile page, but the image eather does not load or just consumes everything else.
The profile picture is save as such:
#Lob
#Basic(fetch = FetchType.EAGER)
private byte[] profilePicture;
This the controlle which should return the image. The HttpServeltResponse is something I found related to this, but I made the image consume the whole page.
#GetMapping("/profile")
public String showporfile(Model model, Principal principal, HttpServletResponse response) throws IOException {
acc = accountRepo.findByUsername(principal.getName());
model.addAttribute("accountName", acc.getName());
model.addAttribute("skills", acc.getSkills());
model.addAttribute("accounts", acc);
/*response.setContentType("image/jpg");
InputStream is = new ByteArrayInputStream(acc.getProfilePicture());
IOUtils.copy(is, response.getOutputStream());*/
return "profile";
}
And this is my HTML in which I have tried to get the picture to show. At the moment I get error stating: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). It seems that the image is now going as: http://localhost:8080/[B#1c535b01 and I don't know why that is.
<div th:each="account : ${accounts}">
<label th:text="${account.name}"></label>
<div class="header_image clearfix">
<img th:src="${account.profilePicture}"/>
</div>
</div>
Thank you for advance I have been stuck with this for 3 days now.
EDIT
the image is stored to h2 database and linked to user as seen up.
The first thing you have to understand is that src attribute of the img tag is the URL of the image, and not the image itself.
Given you've already decided to store the image in a database, you'll need to create a separate endpoint to get the image (e.g. "/profile/avatar") where you actually return the image body pretty much the same way you're trying in your commented-out code. And then you would refer to that endpoint in your img src.
BTW, Actually there is a way to embed an image into html using "data" protocol and base64 encoding (here's one example of it), but it's only suitable for tiny images, and I believe you would benefit from learning the usual way first.

How does the HTML page find a servlet in an Eclipse dynamic web project? [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
I created a dynamic web project in Eclipse with a HTML page (in the WebContent folder of the project) that is supposed to send some input data from the user to a servlet (with the name "Tee").
I try to locate the servlet with
form method="get" action="../../src/Tee"
it does not find it. No, its not a Status 404 error message. But simply "the page cannot be displayed."
I tried this:
form method="get" action="/Tee"
as well, does not work either.
The Tomcat server is started and the project is deployed on the server. If i start the servlet itself, it runs on the server without problem (with all the data set to null, as these are supposed to come from the html page).
Yes, there are similary questions out there but those gave no real solution to me.
You need to write a servlet class something like:
#WebServlet("/Tee")
public class Tee extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.write("Hello World!");
//...
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//...
}
}
After writing the servlet, right-click its name in Eclipse and click Run As > Run on server
If it runs successfully in the Eclipse browser, it will be accessible in your HTML with its name e.g.
<form method="GET" action="Tee">
<input type="submit">
</form>
Update
After you posted the servlet code, I can see a problem there. You have written method="GET" in the HTML form but in the servlet code, you have just doPost. You should have doGet in the servlet for method="GET" in the HTML form to be acted on. Add the method, doGet in addition to doPost in the servlet.

Servlet in Eclipse - Where to put static content [duplicate]

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 9 years ago.
When writing a servlet with Eclipse, where am I to put my static content (images, CSS, etc.), so that I can make my HTML link to it (e.g. <img src="http://localhost:8080/context/image.png>). I have tried putting it into the WebContent directory, but that didn't work (or I didn't know how to link to it, I tried <img src="image.png"> and also <img src="http://localhost:8080/context/image.png">).
I attached an image of my Project Explorer, so you can maybe sort it in.
To make it easier to find, here is everything I posted in comments or elsewhere:
The project's web.xml: http://pastebin.com/sTg4ugyw
My Servlet code: http://pastebin.com/az97bZAY
One of my HTML templates: http:pastebin.com/6KALf0Bw
Create a test.html file and place it at /Blog/WebContent/test.html in your Eclipse project.
<html>
<head>
<title>Test WebContent</title>
</head>
<body>
<img src="images/test.png" />
</body>
</html>
Also place a test.png image file inside the /Blog/WebContent/images folder.
Now, point your browser to http://localhost:8080/<your-web-app-name>/test.html and check if test.png gets rendered or not. If yes, then the problem lies in the way you're writing HTML output from your servlet.
For a sample ImgServlet configured as
<servlet>
<servlet-name>ImgServlet</servlet-name>
<servlet-class>pkg.path.to.ImgServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImgServlet</servlet-name>
<url-pattern>/ImgServlet</url-pattern>
</servlet-mapping>
your doGet() method should ouput HTML as
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Test WebContent</title></head>" +
"<body><img src=\"images/test.png\" /></body></html>");
EDIT: To print all the request parameters your servlet is receiving add the following just before your handleRequest() method call (which you can comment out also for testing)
PrintWriter out = response.getWriter();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String param = (String) parameterNames.nextElement();
out.println(param + " = [" + request.getParameter(param) + "]");
}
Try
<img src="/context/image.png">
But it does depend on how you deploy your application. Anyways, files like images must be inside WebContent folder.
First of all, dont hard code your context in your link, it will make you hard to change the link later if your context path is changed. Instead, use EL to make the relative path:
<img src="${pageContext.request.contextPath}/img/abc.png" />
Secondly, I dont see any image in your WebContent, if you put the image manually into the window folder, you need to refresh eclipse project in order to let eclipse detects all the added files. Right click on your project in the Project Explorer and select Refresh

How to make files download instead of opening in browser?

I am a new bie, i want files to get downloaded when user clicks on download option its opening in the browser instead of download option like save as/open.Here i referred for the same and every where they have suggested to use
Response.AddHeader("Content-disposition", "attachment; filename=" + Name);
But i don't know where and how to use.
Actually i'm getting the url value from query written which return url as one of the object of bean stored in arraylist(This list is having other values also with url ).
I am having the url values inside the arraylist as bean as like
type=.pdf
release date=12/3/08
name=hai.pdf
url=/files/en/soft/doc/docs/hai.pdf
I am getting this array list in my controller like this
ArrayList details = dao.getdetails(Bean.getNumber());
and pass this into view like this
Map.put("details", details);
modelView.setViewName("details_list");
modelView.addAllObjects(Map);
return modelView;
in jsp i have iterated this array list and diplays the content like this
Type name Release Date
.txt hai.pdf May 21st 2012 Download
.txt hello.txt May 21st 2012 Download
For download i have used like this in jsp
<td colspan="2" valign="top">
<a href="${details.Url}"/>
<img src="/images/download.gif" alt="Download" border="0" align="right"></a>
</td>
here on click of download its opening in browser.I need this to be downloaded instead.
Please help me in how to use or handle
response.setHeader("Content-Disposition", "attachment;");
where to add the above for my requirement or if i can do with any java script also.Please help me in solving the above.
Here is one way of doing it:
Create a web Filter (or this way )
Map this filter to the PDF URL.
In the doFilter() method, set the response header for content download.
Example :
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String name = request.getAttribute("filename");
response.addHeader("Content-disposition", "attachment; filename=" + name);
chain.doFilter(request, response);
}
You can set the filename as an request attribute (reqest.setAttribute()) from your controller class
Filters are pretty standard in Java web stack.
It's depend on the header which browser get in response.
Suppose if header is image/png then browser will show it. Same way if you send same image with application/octet-stream then browser will force to download it.
take a look http://en.wikipedia.org/wiki/Byte_stream
In a project I have figure out that sending request from browser are different.
If you upload a image from Firefox or IE then it's will upload them as image/png wherever chrome upload them as application/octet-stream.
just try to add header
response.setHeader("Content-Type: application/force-download");

Multiple Pages Inside One Portlet

I am curious if anyone knows if it is possible for a single portlet to contain multiple pages, let's say JSP pages. Furthermore is it possible to link to these different pages within the same portlet?
For example. Let's say I have a single portlet. And in this portlet I want the initial view to be a JSP page with just 5 links on it to 5 different JSP pages. And when a user clicked on one of these 5 links, it would load the appropriate JSP page into the portlet.
The end goal would basically be a little mini website all contained inside a portlet.
Now, I understand that this might not be the best use of a portlet, but for the sake of a project I am working on, I still would like to know if it is possible.
Thanks!
Sure, a portlet can contain more than one JSP.
You can display any JSP you want via the PortletRequestDispatcher in your doView (or doHelp or doEdit) method:
protected void doView(RenderRequest req, RenderResponse resp)
throws PortletException, IOException, UnavailableException {
resp.setContentType("text/html");
String myview = req.getParameter("myview");
String view = "/WEB-INF/jsp/" + (myview==null ? "bar" : myview) + ".jsp";
PortletRequestDispatcher dispatcher =
getPortletContext().getRequestDispatcher(view);
dispatcher.include(req, resp);
}
You could use a parameter to set the view. In the JSP with the links, you'd need to use the Portlet API to create/encode the links to the Portlet. For example:
<portlet:renderURL>
<portlet:param name="myview" value="foo"/>
</portlet:renderURL>
(I haven't really kept abreast of JSR286/Portlet 2.0 - this stuff should work with JSR168/Portlet 1.0 - so it is worth checking the new API if you're using it.)

Categories

Resources