Not able to retrieve images in jsp - java

display.jsp
<body>
<h1>Displaying Image</h1>
<%
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
session.setAttribute("username", auth.getName());
%>
<c:forEach var="imageName" items="${files}">
${username}${imageName}
<img src="../images/${username}/${imageName}"/>
</c:forEach>
</body>
Saving the images in path
(C:\workspace\fileupload\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\images\user1\)
in code using .....
new File(request.getSession().getServletContext().getRealPath("../")+"/images"+"/"+auth.getName());
reaching to the deployed webfolder and then coming one step back(as using here ../) then creating a folder "images" then inside images creating a folder with the name of user (as using here +"/"+auth.getName()), saving the images successfully.But while retrieving these image, i tried the code written in jsp, but it is not working.here in jsp , i checked for ${username} and ${imageName} both are retrieving correct values from controller, means there is not any issue with controller side, but while constructing the url for retrieving image, it is getting wrong somewhere.Could someone plz help to get it right
src="../images/${username}/${imageName}"

Keep your Image folder in the place where display.jsp is stored and try again.

Related

Using ArrayList in a sub-template on .jsp page

I have a JSP home page with a menu. I want that menu to be on multiple pages so I created a menu.jsp template. I imported, all static source code appears but the <c:forEach /> tag is not picking it up. When I print (just put it plainly in the html) out my ${allCategories} variable I get all the data correctly.
In a controller, I set model.addAttribute("allCategories", categoryService.getPrimaryCategories());
home.jsp where the categories were before is importing <jsp:include page="menu.jsp"/>
in menu.jsp I am unable to get <c:forEach items="${allCategories}" var="category"> to work but when I just put <p>${allCategories}</p> at the beginning of the file it shows stuff like [Category(id=1281, name=Bundles, image=https://images...
How do I get the data correctly in the sub-template so it works like directly on the page?
You could try using the JSP include directive. It is used to include a file during the translation phase. For example,
<%# include file = "menu.jsp" >

RequestDispatcher prints output on the URL of the servet instead of redirecting to the JSP [duplicate]

This question already has answers here:
RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
(9 answers)
Closed 6 years ago.
This code snippet is from my CustomerController servlet.
#WebServlet("/CustomerController")
/*
.
.
.
*/
if(request.getParameter("operation").equalsIgnoreCase("search-customer")) {
CustomerDAO customerDAO = new CustomerDAO();
Customer customer = customerDAO.searchCustomer(Integer.parseInt(request.getParameter("customer_id")));
request.setAttribute("Customer-Result", customer);
RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/search-results.jsp");
requestDispatcher.forward(request, response);
}
Instead of redirecting to search-results.jsp so as to print the result of the search, the results are printed on the servlet's (CustomerController) url itself.
Refer to the image.
search-results.jsp
<%#page import="com.servlet.Customer"%>
<!DOCTYPE html>
<html>
<body>
Customer Found :
<%
Customer customer = (Customer) request.getAttribute("Customer-Result");
out.println(customer.getCustomer_name());
%>
</body>
</html>
What is wrong ?
You do not want that!
The URL displayed in the browser is the one for the last query sent by the browser. In your case, you send a query to /CustomerController and server side, the servlet forwarded the request to a JSP to display results. That forward is an internal detail in a web application, and you have no reason to show that to the client.
More, you should not let the client know about that. Common usage is to put the JSP used internally by the servlets (via includes or forwards) under the WEB-INF folder precisely to avoid direct queries from the client. What would be the sense to ask the browser to display an URL that it cannot query? The interesting part here is that if you later change from JSP to a template engine like velocity, as that part is hidden from client, nothing will change in the visible interface
I'm not sure that this is the expected answer but you really should wonder why you want to display an internal URL in the client browser. As that will require that you put the JSP outside of the protected WEB-INF folder, it would be definitely a bad practice.
#Maven Maverick. Hope this can help you.
If you want your search-results.jsp in your URL remove that file from your WEB-INF folder and deploy it under WebContent folder(IDE:Eclipse). Because WEB-INF is protected folder its not accessed directly by user call or url. For that you have to move that jsp file under WebContent folder and instead of RequestDispatcher use response.sendRedirect("//test.jsp");return;
Comment If this works for you or not .. because works for me.
Hope it works for you :)

jsp ${pageContext.request.contextPath} dosent get requested

Currently i have a .jsp project where my welcome page is a servlet
<welcome-file>frontpage</welcome-file>
The servlet sets gets two ressources, a header file containing the < nav> and a footer containing the < footer>
request.setAttribute("header1", sc.getResource("/includes/nav.jsp").toString());
request.setAttribute("footer", sc.getResource("/includes/footer.jsp").toString());
And forwards to the index.jsp page
getServletContext().getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
My question is.
When i get the ressource (footer.jsp), how can i in the footer.jsp dynamically import / include images?
I tried the following
<img src="${pageContext.request.contextPath}/images/picture1.png" alt="picture1"/>
But the expression ${pageContext.request.contextPath} gets treated as a string instead of a command, and does not get the context path.
I suspect its because the content of the footer.jsp is fetched in this manner and their for the context path isint actually ever requested within the footer.jsp.
But how do i solve this?
add <%# page isELIgnored="false" %> in top of your JSP page, to enable expression language.
and to include a JSP page with other use <jsp:include like:
<jsp:include page="/includes/nav.jsp"/>
<jsp:include page="/includes/footer.jsp"/>
This is not the way to include stuff. Use jsp:include action to include the header/footer. If for some reason you really want to do it in the servlet, see this post. As long as you just grab a resource like you do, you're reading the file like any text, there is no JSP compilation/evaluation.

How to transfer parameter to redirect web

We know that we can redirect an website by putting this below the tag:
<head>
<meta content=0;url=http://www.google.com http-equiv='Refresh'/>
</head>
But what happen if the link I want to redirect is not google.com but it is stored in a string variable that I processed from my Java code? I know if it load from head down, then it will redirect immediately to that page without going through the following code right? So, how to combine the string that I extracted and let the website to load to that link?
From JSP (or servlet):
<%
response.sendRedirect(redirectURL);
%>
Where redirectURL is the variable containing the page you want to go to.
Ok, finally I figured it out:
First, need to construct the index.jsp and its java class in an web app:
https://netbeans.org/kb/docs/web/quickstart-webapps.html
then in the index.jsp, use this to get variable from that java class and redirect:
<%#page import = "org.mypackage.Webredirect.*" %>
<%Webredirect obj = new Webredirect();%>
<%response.sendRedirect( obj.getName());%>
thank you.

JSP not detecting the javascript file

From a servlet, I'm forwarding the request to a JSP page which renders a FusionChart.
But I've a problem in loading the chart. The JSP file is not detecting the JavaScript file. The folder structure is:
axis
|
WebContent
|
WEB-INF
|
classes
|_ com
|_FusionCharts.js
|_MyChartJsp.jsp
|_Line.swf
And the JSP code:
<html>
<head>
<script language="text/javascript" src="/WEB-INF/classes/FusionCharts.js"></script>
</head>
<body bgcolor="#ffffff">
<div id="chartdiv" align="left">The chart will appear within
this DIV. This text will be replaced by the chart.</div>
<script type="text/javascript">
var foo = //value fetched from DAO
var myChart = new FusionCharts("/WEB-INF/classes/Line.swf",
"myChartId", "1000", "500");
myChart
.setDataXML("<graph caption='aCaption' xAxisName='xAxis' yAxisName='yAxis' showNames='1' decimalPrecision='0' formatNumberScale='0'>"+foo+"</graph>");
myChart.render("chartdiv");
</script>
</body>
</html>
The Servlet code to forward the request:
final RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/classes/MyChartJsp.jsp");
requestDispatcher.forward(request, response);
The request is getting forwarded to the JSP. But the chart is not getting displayed because it is unable to figure out what FusionCharts is in the line
var myChart = new FusionCharts("/WEB-INF/classes/Line.swf",
"myChartId", "1000", "500");
I tried
src="/FusionCharts.js"
src="FusionCharts.js"
but no luck.
Has it something to do with the request being forwarded??
You cannot have .js (or .swf, .jpg, etc.) files in WEB-INF - they are not publically accessible.
Move it to /js/
There is no reason to hide static resources (like scripts and css) in WEB-INF. If you insist on that, you should make a servlet that, given the name of the js/css, would read it from its location and will serve it as a response. This is what the default servlet does when you access static resources.
The flow of the page loading is as follows: the browser sends a request to the servlet; the servlet forwards internally to the JSP, and the JSP is rendered as a response; then the browser parses the <script> tag and fires another request to the script. If the script is not accessible via URL, it's not loaded.
Then, to make the script url fixed to the servlet context root, use
src="<c:url value="/js/script.js" />"
This will work regardless of what is the current url
Not the cause of your problem, but also note that your <script> element is incorrect. It should be <script type="text/javascript"....
(I tried to post this as a comment, but for some reason it wouldn't let me.)
I was facing same issue. In my case when I calling the myFile.jsp directly its reading the myFile.js;
But when calling through login-> myFile.jsp, its not reading the myFile.js;
After analyzing the path through the Developer tools :=> console, I found that its inserting the uri, so final path was incorrect.
Final Solution:
I'd used the absolute path for all .js and .css. Now its called from everywhere.
My Project Structure is:
In my servlet-context.xml
i) <context:component-scan base-package="com.SBP.SHWeb" />
ii) <resources mapping="/resources/**" location="/resources/" />
My old path for including .js was: /resources/MyJs/myfile.js ===> Its not get called sometimes.
My Absolute path, which get called from all places is like this:
/SHweb/resources/MyJs/myfile.js ==> Its get called from everywhere.
Hope it help you.

Categories

Resources