How to create hyperlink in Spring + JSP - spring

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>

Related

correct use of getContextPath() on jsp

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.

How to mix href within jstl code

When I use the below jstl code
<a href="http://mysite.com?id="<c:out value="${myid}"/>/><c:out value="${myid}"/></a>
the output is :
"1234"
The value 1234 corresponds to the variable value of myid but the url being generated is
"http://mysite.com?id=" so no value for myid is being generated as part of the href.
How can I amend the href so that entire href is displayed :
"http://mysite.com?id=1234"
instead of :
"http://mysite.com?id="
Ultimately, JSP/JSTL generates HTML. You're familiar with basic HTML, right?
Look closer at the generated HTML output by rightclick, View Source in browser. You'll see:
<a href="http://mysite.com?id="1234/>1234</a>
Is that valid HTML? No, you're closing the attribute value too soon with " at wrong place and you're closing the tag too soon with />. Look, the Stack Overflow HTML syntax highlighter also got confused. Instead, it should have been:
1234
Fix the HTML generator (i.e. the JSP/JSTL code) accordingly so that it generates the desired HTML:
<c:out value="${myid}"/>
Unrelated to the concrete problem, the <c:out> is only helpful in preventing XSS attack holes when redisplaying user-controlled input and actually the wrong tool to inline URL parameters. If you can guarantee that ${myid} is always a number (because it's a Long or Integer), you can even just leave it entirely out, making the code prettier to read:
${myid}
If the ${myid} is however not a guaranteed to be a number (because it's a String), then you should use <c:url> and <c:param> to properly URL-encode it:
<c:url value="http://mysite.com" var="myURL">
<c:param name="id" value="${myid}" />
</c:url>
<c:out value="${myid}" />
<c:url> tag is used to create an url. It is helpful in the case when cookies is turned off by the client, and you would be required to rewrite URLs that will be returned from a jsp page.
<c:param> tag may used as a subtag of to add the parameters in the returned URL. Using these parameters encodes the URL.
<c:url value="http://mysite.com" var="myURL">
<c:param name="id" value="${myid}" />
</c:url>
<a href="${myURL}" />${myURL}</a>
Read more from here.

Unable to use JSTL format taglib with Spring MVC form

I am changing some code from a home grown MVC to Spring 2.5 MVC. We have a form to edit an object, so I am using formBackingObject() in my controller to populate the form fields with the current values. In the old MVC, we used the JSTL fmt taglib to format date and money fields. This was nice because the formatting was in the presentation layer.
Now with Spring, the fields are populated correctly with formBackingObject(), but Spring doesn't recognize the the value attribute in the form:input element:
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<form:form method="post" commandName="editProgramCommand" name="editTitleForm">
<fmt:formatNumber type="NUMBER" value="${program.price}" var="formattedPrice" minFractionDigits="2" />
<form:input path="price" id="price" value="${formattedPrice}" />
... other fields
</form:form>
Thoughts on how to properly format values in a Spring form? I'm not finding much on the web, so I figure its either a really simple syntax error, or I'm completely on the wrong track.
Spring form:input recognize the value of the input from its path attribute and not from the value attribute. If you see the spring form tld, there is no attribute value for the form input tag.
One way which i think is format the values in the back end and bring and set it in the front end.
Otherwise you can use the conventional spring:bind instead of spring form. Spring Bind Reference

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?

spring validation: cleanest way to makeup accompanying labels of the validated input

I'm validating the input field that's bound to path. I'm using hibernate-validator 4 for this.
Now I'd like to highlight the age label so it pops out of the page (bold, red colour etc.).
However I'm wondering what the cleanest way to do this is.
<spring:hasBindErrors name="*"/> seems to be for the whole form object instead of for a specific field. Any input is appreciated.
Spring provides special jsp tags for forms, which support this task (highlighing in case of error):
For example this jsp
...
<%# taglib prefix='form' uri='http://www.springframework.org/tags/form'%>
...
<form:form method="post"
commandName="myCommand">
<form:input path="name"
cssClass="normalLayout"
cssErrorClass="normalLayout error"/>
<form:errors path="name"
cssClass="errorMessage"/>
</form:form>
...
In this case: the input field uses the css class "normalLayout" if every thing is ok, and the css classes "normalLayout" and "name" if there is a validation error for the field.
form:errors is to print the error message generated while validation.
#see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-jsp-formtaglib

Resources