Including a page using spring - java

I'm using spring to display a jsp page. That's fine. Now I'd like to include another page in it. I know I can use the <jsp:include> tag in my page however I'd like to use a controller to pass some logic to the page which is to be included. Is it possible please?
Thanks,
Krt_Malta

You might want to checkout a template engine like Freemarker or Velocity. Here's a description of how Spring integrates with view technologies.

Your controller can add objects to the Model and Spring will add them to the HTTPRequest as attributes, is that what you mean? Including a jsp fragment doesn't affect that, your jsp fragment can access the request attributes. Otherwise it's unclear to me what you mean by "passing some logic to the page".

Look into JSTL (Jsp Standard Tag Library).
You can implement conditional logic in your JSP using the JSTL <c:if> or <c:choose> tags. Then, instead of splitting up the logic into multiple files and using <jsp:include> to include the logic you want, you can build all the logic into your page and the controller can set request (or other scope) attributes to turn on the logic you desire.
For example:
<c:if test="${Order66}"
&ltc:forEach items="${JediMembership}" var="jedi">
kill ${jedi}
&lt/c:forEach>
</c:if>
<c:if test="${Order67}"
two large pizza, extra cheese.
</c:if>
The controller then set "Order66" and / or "Order67" in the request (or any other scope).

Related

ESAPI implementation for spring form tags

How can we implement ESAPI output encoding in an application using java and spring-mvc.
Read many posts and saw this:
<%# page import="org.owasp.esapi.*" %>
<input type="hidden" name="hidden" value="<%out.print(ESAPI.encoder().encodeForHTML(content));%>"/>
But, in my application all the jsps use spring form tags like the following,
<td>Number:
<form:input path="someNo" size="20" maxlength="18" id="firstfield" onkeypress="return PressAButton('submithidden');"/></td>
How can I have ESAPI implementation for above code? is there any other way of implementing output encoding like creating a filter or something? Any suggestions are greatly appreciated!
After researching spring tags a bit, it appears that the data-binding happens in framework code thus preventing you from applying any escaping in the jsp.
One, semi-quick win could be defaulting all output to escape HTML. Add this entry in web.xml:
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
The only problem here is that output-escaping is a BIG pain... the rules for html escaping are different when your value is going to be passed as data to an HTML attribute or a Javascript function. And there could be some parts of your application where you DO NOT want to html escape, but you should be able to override those with the form tag attribute htmlEscape="false" when you need to.
What you need is to be able to hook the part of Spring tags where it is binding the HTML to the form, but you need to be able to do it so you can escape based on where its being placed. Escaping rules are different for an HTMLAttribute as opposed to plain HTML and if the value is going to be passed as data to a javascript function. So Spring's solution only defends one category of attack.
These are the only ways out I see, all of them will require work:
Use JSTL tags instead of Spring tags so you can write your variables with ${thisSyntax} and wrap them in esapi tags like this:
<c:out value="<esapi:encodeForHTML>${variable}</esapi:encodeForHTML>"/>
Follow a solution like what #A. Paul put forward, where you do your context escaping back on the controller side. I'm aware you feel that this isn't an option, but the next solution I'm putting forward is untested.
Implement your own tag library that subclasses [org.springframework.web.servlet.tags.form.InputTag][1], specifically the method writeValue. While esapi prevents alot, I would recommend looking at owasp's new Encoder project to show you exactly how tricky output encoding is. Ideally your tag library will allow you to utilize either esapi's Encoder or this new API.
Just a thought not sure if this is what you are looking for.
Can you use the below code in Java and change the data in the bean itself and then send in the user interface.
if ( ESAPI.securityConfiguration().getLogEncodingRequired() ) {
data = ESAPI.encoder().encodeForHTML(message);
}
You can check the below url.
http://www.jtmelton.com/tag/esapi/

Can a JSP template be used from within Java?

I'm pretty new to JSP. So far it seems that the flow of processing is very much Java runs first, then populates a JSP template.
I am wondering if there is a way from within Java to utilize a JSP template. What I mean is, imagine I had a simple "SimpleDiv.jsp" template on classpath like this:
<div id="${id}" class="${class}">
${content}
</div>
And then from within an arbitrary Java file (perhaps not even running on a servlet), I could do something like this:
private String getDivHtml( id, html ) {
Template simpleDiv = TemplateLoader.load("SimpleDiv.jsp");
simpleDiv.set("id", id);
simpleDiv.set("class", Whatever.CLASS_NAME);
simpleDiv.set("content", html);
return simpleDiv.toString();
}
This is a pretty simplistic example so don't get caught up on the details of that. Main question is -- can I pull in a JSP template in Java and cause it to generate HTML inline?
Freemarker and Velocity are very popular for generating content from templates, you might try one of them. Since JSPs are implemented as servlets (and the JSP spec defines them as webcomponents) they are tied to the servlet container.
There's no simple way to accomplish this using plain JSP. There are related Q/As in the site explaining how to do it:
What is the best way to create JSP layout template?
JSP tricks to make templating easier?
Another option using plain JSP would be using external frameworks to accomplish the task like Apache Tiles and SiteMesh (mentioned here: JSP template implementation (Composite View Pattern)).
If you can, upgrade to Facelets, the current view technology since Java EE 6. This technology already provides built-in template system as explained here and here.
Consider this subset of JSP which has no dependency on servlet:
http://jstp.sourceforge.net/manual.html
Jsp is a inner servelt, a java class, normally, it outputs HTML when it finishes executing.
Maybe you should just treat the jsp file as a pure string, the "simpeDiv.set" method just do replacing works: replace ${key} to ${value}

How can I make Spring-MVC output HTML

How can I make Spring-MVC output HTML. Right now I have Spring-MVC filling in data in a List like the one below:
<ul>
<li><c:out value="${memberrequest.name}"/></li>
<li><c:out value="${memberrequest.title}"/></li>
<li>District: <c:out value="${memberrequest.district}"/></li>
<li><c:out value="${memberrequest.school}"/></li>
<li><c:out value="${memberrequest.requestor}"/></li>
</ul>
the out put looks like:
But if the data is blank like title, school etc I don't want a line to blank so I was thinking that I could creating this list in the spring code and then pass the html back to the JSP page but it looks like Spring will not let you do it
Returning HTML from your controller defeats the very idea of MVC, because your controller takes over the responsibility of the view.
Instead, use the <c:if> tag within your JSP. More information here: http://docs.oracle.com/javaee/1.4/tutorial/doc/JSTL4.html#wp74001 (note: the first paragraph of this explanation seems to indicate that you should use a scriptlet; it really doesn't, and if you read down you'll see the JSTL approach).
If you really want to do this you can use the escapeXml="false" attribute on c:out like so:
<c:out value="${myHtmlString}" escapeXml="false"/>
But as parsifal says, it's best to construct your HTML in your view if you can.

Spring MVC htmlspecialchars() alternative

I'm looking for an alternative to PHP's htmlspecialchars() or even better, for a global solution using Spring MVC. For example, it would be great if data passed from Controller to View using ModelAndView or ModelMap was automatically processed so I could be sure that I'm working with safe strings inside jsp View.
If you're using JSPs to display your data, all you need to do is use the JSTL's <c:out> tag, or fn:escapeXml() function to escame the HTML special chars:
Last Name : <c:out value="${someBean.lastName}"/>
First Name : ${fn:escapeXml(someBean.firstName)}
I would definitely not do this in the controller. This is one of the view's jobs.

How do I pass information from a servlet to a JSP page

Is it possible to have a servlet that contains an object (an ArrayList in this case) that then does the equivalent of displaying a jsp page and passing that object to the jsp page. In this case the ArrayList contains database results an I want to iterate through and display the results on the JSP page.
I am not using any MVC framework, is it possible to do this with the basic Servlet/JSP architecture.
Yes.
in the servlet call request.setAttribute("result", yourArrayList);
then forward to the jsp:
getServletContext().getRequestDispatcher("your.jsp")
.forward(request, response);
using JSTL, in the jsp:
<c:forEach items="${result}" var="item">
...
</c:forEach>
If you don't want to use JSTL (but I recommend using it), then you can get the value using request.getAttribute("result") in the JSP as well.
Alternatively, but not recommended, you can use request.getSession().setAttribute(..) instead, if you want to redirect() rather than forward().
You can pass objects to jsp's by embedding them within the Request.
request.setAttribute("object", object);
and within the jsp:
request.getAttribute("object");
You can put it using request.setAttribute("myobj", myObj); see javadoc
If you are trying to make some kind of "component" then it's better to convert the JSP page into a custom tag. Here is excellent article about that: http://onjava.com/pub/a/onjava/2004/05/12/jsp2part4.html

Categories

Resources