correct use of getContextPath() on jsp - image

I have a problem using getContextPath() on jsp.
I want to add an image to the JSP, a logo.
I have read that is better to use getContextPath().
In my browser´s address bar I see de URL:
http://local.host:9080/Cold/start/Result.jsp
So I have assumed my getContextPath() is:
http://local.host:9080/Cold/
Next, I found the Result.jsp file at:
**C:\Users\myname\IBM\rationalsdp\workspace\Cold_WEB\WebContent\start**
So I have created the next path:
**C:\Users\myname\IBM\rationalsdp\workspace\Cold_WEB\WebContent\images**
And I have put the logo file there.
So, I have added next code:
<img src='<%=request.getContextPath()%>/images/SuperlineaPF.gif' border="0">
But, I still can not see the logo at the page on the browser.
What is wrong?
Thank you.

I find the following graphic from HttpServletRequest Path Decoding helpful:

Use the EL expression ${pageContext.request.contextPath}

You can do it following way in your JSP
<c:set var="context" value="${pageContext.request.contextPath}/images/SuperlineaPF.gif"/>
<img alt="image" src="${context }" border="0"/>
At the top of the page put an uri for JSTL as
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Note: You'll require JSTL library for it. This is for best practice.
Since your JSPs are placed under start in WebContent you can simply refer to your images following way.
<img alt="image" src="images/SuperlineaPF.gif"/>
You do not require page context for that.

Related

thymeleaf spring standard dialect: using template

Hello I have some problems with templating pages.
I am returning from controller a view called list:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="layout/template">
<div layout:fragment="pageContent">
<p>LIST</p>
</div>
</html>
And I would like to put this into template where I have a lot of html stuff and:
<div layout:fragment="pageContent">Demo static page content</div>
But I am getting in web browser only list view.
How to put one view returned from controller to template using SpringStandardDialect?
So if i understand correctly, you want to inject that fragment which is called pageContent into some other html page (lets call it main.html for sake of it.
First thing to do is change the div in list to the following:
<div th:fragment="pageContent">
<p>LIST</p>
</div>
then in your main.html you would call the fragment via:
<div th:include="list::pageContent"></div>
or
<div th:replace="list::pageContent"></div>
Btw "list::pageContent" indicates that its in base folder, if its located in folder called example then it would be "example/list:pageContent".
here is the great example on Thymeleaf website: http://www.thymeleaf.org/doc/usingthymeleaf.html#including-template-fragments
Hope this helps, if not let me know.

Spring JSP CSS referencing issues

My team had all ready created a project in spring framework and running successfully. Now i decided to make it run even faster.
Existing project:
My developers do their best and created dynamically output css pages using jsp.
Existing code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<jsp:include page="/WEB-INF/common/layout/head.jsp" />
< jsp:include page="/WEB-INF/common/css/index.jsp" />
</head>
Out put:
<style type="text/css">
body{background: #ffffff url('<c:url value='/resources/images/logo/logo_small.png'/>') no-repeat scroll center center}
</style>
There is no error in this code or project this is working fine.
What i need is that, my css files need to be loaded by a link tag in header. something like this:
<link rel="stylesheet" href="/mysite/resource/css/sitemap/index.css" type="text/css">
This will speed up by catching in browser.
What i done up to now:
I created a url it points to a jsp.
<c:if test="${branch == 'sitemap'}">
<c:if test="${page == 'index'}">
<%#include file="/myfile/dynamic/css/layout/index.jsp" %>
</c:if>
</c:if>
This code may? works, but there is a problem. I need to replace style type start tag and end tag.
I done that by, Importing and replacing by this code:
<c:set var="my_css">
<c:if test="${branch == 'sitemap'}">
<c:if test="${page == 'index'}">
<%#include file="/WEB-INF/common/css/index.jsp" %>
</c:if>
</c:if>
</c:set>
<c:set var="css" value='${fn:replace(fn:replace(fn:replace(my_css,"<style type=\\\"text/css\\\">", ""),"</style>", ""),"\'", "99999")}'/>
<compress:css enabled="true">
<c:out value='${css}'/>
</compress:css>
Here 99999 location is causing problem. Actually i need to replace it with & #39;.
The above code works fine and replaces ' with 9999. But after replace with &.. it not working. The & itself again changing to & amp;
Information :
Its a completed project. More css will be generated dynamically. All in jsp pages.
Goodluck is that each jsp page ouput only css code. Badluck is that it contains script tag at top and bottom. One more bad luck is on url('').
This ' code is doing the problem in fn:replace tag.
Or if you have a better suggestion please let me know.
I think there will be an easy option. Please let me know your suggestions, advice and help.
I achieved this.
I created a new route /resource/css|js , I use internal resource view resolver - (folder).
My link url is moething like /resource/css/qtn/page1.css.
In controller /resources/{type}/{page}.css.
Here i get type and page values and used this in my dynamic jsp page to achieve my result.
For security i checked the url is it comes from my own page or not.
Hint :
While using internal resource view resolver it will throw error when you pass page values directly to resource url because sometimes page url will be /page1/block1 so our controller throws error.
To solve this i passed page values as /resource/css/qtn/page1.css?sub=${page}.
In controller we can easily cath this sub value and send to our dynamic jsp as model.

ASP.NET MVC 3: Stack Overflow on a Html.Action?

By definition I had to post this question. I received the error on this line using ASP.NET MVC 3 and ASPX form. Where's my typo?
<a href="<%= Html.Action("About", "Home") %>">
<img src="<%= Url.Content("~/Content/images/newfront_04.jpg") %>" /></a>
I created a blank project to compare:
Web Config is identical minus connection strings (including Views web.config)
Global.asax.cs including routes is identical minus namespace
Page directive is identical
Home Controller code is identical minus namespace
Taking this line out makes everything work
The entire page is html with the exception of the page directive and ContentPlaceHolders
This is the Site.Master file
Html.Action is actually rendering that action where you are putting that code, and it's causing reentrancy there. That is: it's calling the whole action and outputting the resulting view... not outputting the url.
What you probably wanted was Html.ActionLink (which renders the whole A tag for you), instead, or Url.Action, to just output the URL - rather than the action result again.
Try Url.Action instead of Html.Action
<a href="<%= Url.Action("About", "Home") %>">
<img src="<%= Url.Content("~/Content/images/newfront_04.jpg") %>" /></a>

Load JSP:Include Based on Session Parameters (Using an MVC/Model 2 Approach)

I am doing some server side form validation and in the case that one or more of the fields is incorrectly filled out, an array gets populated with all of the error messages. On the client side, I have a scriplet that checks for the existence of any error messages and if there are any, it displays them. When the page comes from the servlet it knows if it has failed or not because on a successful submission, it would not reload the form jsp page at all.
This is how I am displaying the error:
<%if(request.getSession().getAttribute("errors") != null){ %>
<jsp:include page="error.jsp"></jsp:include>
<br>
<% } %>
And the error.jsp page is:
<%# page import="java.util.ArrayList" %>
<h3>Oops...We Have a Problem</h3>
Please review and fix the following errors.
<br>
<%
ArrayList errMessages = (ArrayList)request.getSession().getAttribute("errors");
for(int i=0; i<errMessages.size(); i++){
out.println(errMessages.get(i));
%>
<br>
This all works fine, but I am following the MVC/Model 2 Paradigm approach in where I keep the code confined to servlets and the html (display objects) confined to jsp pages. Obviously, this small example breaks the rules.
Is there a way to "pre-build" the jsp page on the servlet so it knows to display the error.jsp and I can do the whole array abstraction on the server? In this example it only seems like a tiny bit of code in the jsp that can't hurt, but in other examples I can see this code becoming a much larger section of the page and that is what I would like to avoid.
Just use taglibs instead of scriptlets to control the flow in JSP. JSTL is a standard JSP taglib and it offers flow control tags.
<c:if test="${not empty errors}">
<jsp:include page="error.jsp" />
</c:if>
and
<c:forEach items="${errors}" var="error">
<c:out value="${error}" /><br/>
</c:forEach>
See also:
How to avoid Java code in JSP files?

How to create hyperlink in Spring + JSP

What's the proper way to create a hyperlink in Spring+JSP? There must be a better way than just coding in the <a href="..."> tag. Take for example a page that displays people. The URL is people.htm. The corresponding controller gets people from the database and performs optional column sorting. The JSP might look like:
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>Address</td>
</tr>
...
This seems bad as the URL people.htm is hardcoded in the JSP. There should be a way to have Spring automatically build the <a> tag using the URL defined in servlet.xml.
Edit: Maybe I should be using a Spring form.
The only thing that comes to mind is the JSTL standard tag <c:url>. For example:
<c:url var="thisURL" value="homer.jsp">
<c:param name="iq" value="${homer.iq}"/>
<c:param name="checkAgainst" value="marge simpson"/>
</c:url>
Next
Now this won't get you servlet mapping or the like but nothing will. It's not something you could really do programmatically (after all, a servlet can and usually does map to a range of URLs). But this will take care of escaping for you.
I haven't seen this kind of functionality in pure spring (although grails offers things like that).
For your specific case you might consider removing the file part and only using the query string as the href attribute:
<td>Name</td>
<td>Age</td>
<td>Address</td>
These links append the query string to the path component of the current url.
In Spring MVC in jsp:
You can use:
General Hyperlink:
Click Here
If passing from controller:
Click Here
Jsp tags
<c:url var="URL" value="login">
<c:param name="param" value="${parameter}"/>
</c:url>
Click Here
Hope it Helps.. :)
Better way to create link is:
Name
<%=request.getContextPath() %> makes sure that correct URI will be taken into account.
"sort" parameter you can get over with hidden field and change a value with a little bit of javascript:
<input type="hidden" name="sort" id="sort" value="name">
And controller method should look like this:
#RequestMapping("/people")
public String createUser(String sort) {
...
}
Import this package in your jsp file
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
when you want to redirect new page or url then use for eg.
<a href='<c:url value="url of next page" />'>Home</a>

Resources