<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Smartkey - Java Software Consultancy &#187; JSP</title>
	<atom:link href="http://blog.smartkey.co.uk/tag/jsp/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smartkey.co.uk</link>
	<description></description>
	<lastBuildDate>Tue, 13 Dec 2011 15:03:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>What info can you get from an HttpServletRequest?</title>
		<link>http://blog.smartkey.co.uk/2011/02/httpservletrequestmethods/</link>
		<comments>http://blog.smartkey.co.uk/2011/02/httpservletrequestmethods/#comments</comments>
		<pubDate>Tue, 01 Feb 2011 13:17:44 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[servlet]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=883</guid>
		<description><![CDATA[There are many methods on an HttpServletRequest, and if you&#8217;re anything like me, you&#8217;ll forget exactly what each of them returns. Rather than a long winded investigation into them all, here&#8217;s a sample URL:

https://localhost:8443/test/welcome?a=1&#038;b=2

The &#8216;/test&#8217; in the URL will map to a servlet called test. The servlet will dispatch the request to a JSP for [...]]]></description>
			<content:encoded><![CDATA[<p>There are many methods on an HttpServletRequest, and if you&#8217;re anything like me, you&#8217;ll forget exactly what each of them returns. Rather than a long winded investigation into them all, here&#8217;s a sample URL:<br />
<code><br />
https://localhost:8443/test/welcome?a=1&#038;b=2<br />
</code></p>
<p>The &#8216;/test&#8217; in the URL will map to a servlet called test. The servlet will dispatch the request to a JSP for rendering that has the following scriplet code in it:</p>
<pre class="brush: php">
RequestURL: &lt;%= request.getRequestURL() %&gt; &lt;br&gt;
RequestURI: &lt;%= request.getRequestURI() %&gt; &lt;br&gt;
QueryString: &lt;%= request.getQueryString() %&gt; &lt;br&gt;
ServletPath: &lt;%= request.getServletPath() %&gt; &lt;br&gt;
PathInfo: &lt;%= request.getPathInfo() %&gt; &lt;br&gt;
PathTranslated: &lt;%= request.getPathTranslated() %&gt;&lt;br&gt;
AuthType: &lt;%= request.getAuthType() %&gt; &lt;br&gt;
LocalAddress: &lt;%= request.getLocalAddr() %&gt; &lt;br&gt;
Method: &lt;%= request.getMethod() %&gt; &lt;br&gt;
RemoteUser: &lt;%= request.getRemoteUser() %&gt; &lt;br&gt;
</pre>
<p>this is the output generated:</p>
<pre class="brush: php">
RequestURL: https://localhost:8443/test/welcome
RequestURI: /test/welcome
QueryString: a=1&amp;b=2
ServletPath: /test
PathInfo: /welcome
PathTranslated: C:\projects\testproj\out\artifacts\testapp_war_exploded\welcome
AuthType: CLIENT_CERT
LocalAddress: 127.0.0.1
Method: GET
RemoteUser: Steve
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2011/02/httpservletrequestmethods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing Flash Scope in Java Web Applications</title>
		<link>http://blog.smartkey.co.uk/2011/01/implementing-flash-scope-in-java-web-applications/</link>
		<comments>http://blog.smartkey.co.uk/2011/01/implementing-flash-scope-in-java-web-applications/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 19:20:29 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Flash scope]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[Request]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=828</guid>
		<description><![CDATA[While working recently on a Spring MVC project I found myself wishing it supported flash scope. I hunted around for a simple solution but couldn&#8217;t find anything that didn&#8217;t rely on having to import large framework libraries. After a little thought I came up with the following simple and lightweight solution that has worked really [...]]]></description>
			<content:encoded><![CDATA[<p>While working recently on a Spring MVC project I found myself wishing it supported flash scope. I hunted around for a simple solution but couldn&#8217;t find anything that didn&#8217;t rely on having to import large framework libraries. After a little thought I came up with the following simple and lightweight solution that has worked really well for me. I&#8217;ve included the code for this below so feel free to try it out.</p>
<h3>What is Flash Scope</h3>
<p>Flash scope is a useful part of many web frameworks. It allows the use of the <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get">post/redirect/get</a> design pattern to alleviate many of the problems associated with handling multiple submits or resubmission of data in browser requests to the server.</p>
<p>Flash scope is an additional scope to those provided in a standard Java Web application (page, request, session and application). Any attributes held in flash scope will be available for the duration of the current request, and the subsequent request too.</p>
<h3>My Implementation</h3>
<p>To implement flash scope in my application, I added a servlet filter that checks for request attribute names starting with &#8216;<strong>flash.</strong>&#8216;. When it finds such an attribute, it ensures that it is made available in the subsequent request by temporarily storing it in the user&#8217;s session, and then reinstating it when the next request is received.</p>
<p>For example, to add a message to flash scope, just use the regular syntax for adding a request scoped attribute and let the fiter take care of it:</p>
<pre class="brush: php">
request.setAttribute(&quot;flash.message&quot;, &quot;Here is the news...&quot;);
</pre>
<p>The above attribute can then be accessed in the redirect target JSP using EL or scriptlet syntax (omitting the &#8216;<strong>flash.</strong>&#8216; prefix):</p>
<pre class="brush: php">
${message}
or
&lt;%= request.getAttribute(&quot;message&quot;)  %&gt;
</pre>
<p>Here&#8217;s the code for the filter:</p>
<pre class="brush: php">
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Ensures that any request parameters whose names start
 * with &#039;flash.&#039; are available for the next request too.
 */
public class FlashScopeFilter implements Filter {

    private static final String FLASH_SESSION_KEY = &quot;FLASH_SESSION_KEY&quot;;

    @SuppressWarnings(&quot;unchecked&quot;)
    public void doFilter(ServletRequest request, ServletResponse response,
					FilterChain chain) throws IOException, ServletException {

        //reinstate any flash scoped params from the users session
		//and clear the session
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                Map&lt;String, Object&gt; flashParams = (Map&lt;String, Object&gt;)
									session.getAttribute(FLASH_SESSION_KEY);
                if (flashParams != null) {
                    for (Map.Entry&lt;String, Object&gt; flashEntry : flashParams.entrySet()) {
                        request.setAttribute(flashEntry.getKey(), flashEntry.getValue());
                    }
                    session.removeAttribute(FLASH_SESSION_KEY);
                }
            }
        }

        //process the chain
        chain.doFilter(request, response);

        //store any flash scoped params in the user&#039;s session for the
		//next request
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            Map&lt;String, Object&gt; flashParams = new HashMap();
			Enumeration e = httpRequest.getAttributeNames();
            while (e.hasMoreElements()) {
                String paramName = (String) e.nextElement();
                if (paramName.startsWith(&quot;flash.&quot;)) {
                    Object value = request.getAttribute(paramName);
                    paramName = paramName.substring(6, paramName.length());
                    flashParams.put(paramName, value);
                }
            }
            if (flashParams.size() &gt; 0) {
                HttpSession session = httpRequest.getSession(false);
                session.setAttribute(FLASH_SESSION_KEY, flashParams);
            }
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        //no-op
    }

    public void destroy() {
        //no-op
    }
}
</pre>
<p>You can see from the listing, that the filter stores the flash scoped parameters in a session scoped  map called FLASH_SESSION_KEY. Before the request is processed by the filter chain, the flash attributes are retrieved from the session and added to request scope; after the chain has finished, any new flash scoped parameters are stored in a new session scoped map.</p>
<p>Note that the attributes have the &#8216;<strong>flash.</strong>&#8216; prefix removed when added to the session scoped map &#8211; this not only ensures that they can be accessed using their &#8217;short name&#8217;, but that they are only kept in the session for one extra request.</p>
<p>This approach is not Spring specific and should work with and Java Web framework. I&#8217;ve omitted the configuration for the filter as there are loads of examples of how to do this on the Internet already.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2011/01/implementing-flash-scope-in-java-web-applications/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Open Session in View Pattern for Spring and JPA</title>
		<link>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/</link>
		<comments>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 18:13:24 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[Open]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Transaction]]></category>
		<category><![CDATA[View]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=676</guid>
		<description><![CDATA[The Open Session in View Pattern is well publicised in Hibernate circles as the best practice approach to presenting data in the Web tier of an application. In this article I'll demonstrate how simple it is to configure a Spring application to do the same thing with the Java Persistence API (JPA).]]></description>
			<content:encoded><![CDATA[<p>The Open Session in View Pattern is a well publicised <a href="https://www.hibernate.org/43.html" target="_blank">design pattern</a> for Hibernate applications and is considered the best practice approach to presenting data within the Web tier of an application. In this article I&#8217;ll demonstrate how simple it is to configure a Spring application to work the same way when JPA is used for the persistence technology. The exact same principles apply for a plain Spring/Hibernate application that does not use JPA.</p>
<h3>What is Open Session in View?</h3>
<p>The Java Persistence API (JPA) allows an object oriented model to be mapped to a relational database. JPA is a standard specification for Java based Object Relational Mapping frameworks &#8211; in order to use JPA an underlying implementation must be available; the most common choice being Hibernate.</p>
<p>Both JPA an Hibernate support lazy loading of data to restrict the number of queries fired off to the database. In general this means that data will be loaded on demand when methods are called, on a loaded object, that require more data to be loaded. In order for this to work, the object that the method is called on must have been loaded by JPA and be part of the current running transaction.</p>
<p>In a Spring application, calls to demarcate transactions are generally handled by the Spring interceptors.Transactions are normally started when a method call is made on a Spring managed object and committed once that method call ends. This means that if a JSP page requests data by calling a transactional method on a Spring managed bean, then it can only access the data in that bean that has already been loaded within that call. Any calls for data that might be loaded lazily will fail because the object is no longer attached to a JPA transaction after that method call has returned.</p>
<p>Hibernate developers solved this problem using the Open Session in View design, which associates the active session (and hence it&#8217;s transaction) with the thread that makes the call. In this design, the transaction will be committed when the thread completed processing the request, rather than when a method call completes. This allows lazily loaded data to be loaded within the JSP page not just within Spring managed objects.</p>
<h3>Providing Request Scoped Transactions</h3>
<p>A standard way to intercept requests in any Java Web application is to use a web filter. Spring provide an out-of-the-box Web filters that implement the Open Session in View design for both Hibernate and JPA. We will see the JPA version here, but the Hibernate one works in just the same way; just change the class name in the configuration file.</p>
<p>In web.xml:</p>
<pre class="brush: xml">
&lt;filter&gt;
    &lt;filter-name&gt;oemInViewFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;
        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
    &lt;/filter-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;entityManagerFactoryBeanName&lt;/param-name&gt;
        &lt;param-value&gt;reportsEntityManagerFactory&lt;/param-value&gt;
    &lt;/init-param&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
    &lt;filter-name&gt;oemInViewFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</pre>
<p>The filter class is from the Spring framework libraries. The filter mapping, in this example, applies this filter to all URLs ending with &#8216;.jsp&#8217;; this means that all JSPs that retrieve a lazily loaded object form the service tier of the application are now free to read any data members from it &#8211; any unloaded data will be loaded from the database when calls are made to access it. </p>
<p>Be aware that the filter turns off the auto-flush behaviour of the standard entity manager. This means that any changes that are made to the data in the JSP will not be persisted. The filter can be configured to flush these if requested.</p>
<p>Finally, the init-param that&#8217;s provided to the filter is optional and can be used to explicitly name the entity manager factory that will be used. The example shows how to use an entity manager named &#8216;reportsEntityManagerFactory&#8217; in the Spring configuration files; the default value for this is &#8216;entityManagerFactory&#8217;.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Access the Size of a Collection in a JSP Page Using JSTL-EL</title>
		<link>http://blog.smartkey.co.uk/2009/01/how-to-access-the-size-of-a-collection-in-a-jsp-page-using-jstl-el/</link>
		<comments>http://blog.smartkey.co.uk/2009/01/how-to-access-the-size-of-a-collection-in-a-jsp-page-using-jstl-el/#comments</comments>
		<pubDate>Fri, 09 Jan 2009 14:48:46 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[EL]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSP]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=83</guid>
		<description><![CDATA[A common and frustrating problem that many programmers encounter when first working with JSPs is how to access the size of a Collection using the JavaServer Pages Standard Tag Library (JSTL) and the Expression Language (EL). This article discusses this problem and illustrates a best practice solution.
The Problem
The JSTL and EL greatly reduce the amount [...]]]></description>
			<content:encoded><![CDATA[<p>A common and frustrating problem that many programmers encounter when first working with JSPs is how to access the size of a Collection using the JavaServer Pages Standard Tag Library (JSTL) and the Expression Language (EL). This article discusses this problem and illustrates a best practice solution.</p>
<h3>The Problem</h3>
<p>The JSTL and EL greatly reduce the amount of Java code in a JSP and as a result, can be used improve its maintainability. The EL provides a syntax for working with Java objects and allows an object&#8217;s properties to be accessed using a simple dot notation. So, for example, in order to access the size of a collection, we might assume that we could use an expression like this:</p>
<pre class="brush: xml">
${collectionName.size}
</pre>
<p>Unfortunately this will not work. In order to access a property in this way the object to which the property belongs must be implemented as a JavaBean component and it&#8217;s methods must adhere to the conventions described in the JavaBeans specification.</p>
<p>In short, to read the size property of a collection, the EL requires that the collection implements a getSize method; the bad news for us is that no such method exists in the Collections API.</p>
<h3>Hack 1 &#8211; Use Scriptlets</h3>
<p>The most common work-around to this problem is to simply fall back to using Java in a scriptlet in the JSP instead of the EL and to cast the request attribute to a collection:</p>
<pre class="brush: xml">
&lt;%=((Collection)request.getAttribute(&quot;collectionName&quot;)).size()%&gt;
</pre>
<p>This work-around produces some quite ugly code and becomes even worse when we use it as part of another expression; for example, to test the size within an if tag:</p>
<pre class="brush: xml">
&lt;c:if test=&quot;&lt;%= ((Collection) request.getAttribute(&quot;collectionName&quot;)).size() == 1 %&gt;&quot;&gt;
...
&lt;/c:if&gt;
</pre>
<h3>Hack 2 &#8211; Provide a JavaBeans Compliant Collection Wrapper</h3>
<p>A more elegant solution is to wrap the Collection with an object that implements the Collection interface and delegates all calls to the real collection:</p>
<pre class="brush: java">
public class JSTLCollectionWrapper implements Collection {
    //the underlying collection that is being wrapped
    private final Collection realCollection;

    //constructor
    public JSTLCollectionWrapper(Collection c) {
        realCollection = c;
    }

    //implement Collection interface and delegate all calls to realCollection

    //provide a JavaBeans getter method for the size property
    public int getSize() {
        return realCollection.size();
    }
}
</pre>
<p>Then in your controller class, wrap all collections before adding them to the request or the users session:</p>
<pre class="brush: java">
Collection wrapped = new JSTLCollectionWrapper(realCollection);
request.setAttrubute(&quot;collectionName&quot;, wrapped);
</pre>
<p>The JSTL expressions can now access the size property of the collection as the wrapper class implements this according to the JavaBeans specification:</p>
<pre class="brush: xml">

${collectionName.size}
</pre>
<p>The downside to this approach is that it requires you write the wrapper class, and that you must remember to use it wherever you add a collection as an attribute to an HTTP request or session in your controller classes.</p>
<h3>The Best Practice Approach</h3>
<p>Just so long as you&#8217;re using an application server that supports JSTL 1.1 or later (and you really should be), there&#8217;s a much neater solution available: use the functions tags.<br />
The functions tags can be used in a JSP just like any other tag library, but rather than providing tags to use, the library extends the capabilities of the EL by providing some simple functions for you to use. Here&#8217;s how you can check the size of a collection using the functions tags:</p>
<pre class="brush: java">
&lt;%-- declare that we intend to use the functions taglib --%&gt;
&lt;%@ taglib prefix=&#039;fn&#039; uri=&#039;http://java.sun.com/jsp/jstl/functions&#039; %&gt;

&lt;%-- use it --%&gt;
${fn:length(collectionName)}
</pre>
<p>The first line here is just a standard taglib directive telling the application server that we would like to use the functions tags. The second line illustrates how the length function can then be used to return the size of a collection.</p>
<p>As you can see, the syntax is pretty simple, far less intrusive than using a scriptlet, and does not require any special coding in your controller classes. It also has the added advantage that it works for arrays too, and will even return the length of a String should you need to figure that out.<br />
This solution retains much of its simplicity even when used in more complex expressions:</p>
<p>So there you have it. If you&#8217;ve been trying to figure out how to work with collection&#8217;s sizes in your JSPs, or maybe you&#8217;ve just been praying that Sun would rename the size method to getSize, then the functions tag library can offer a neat and simple solution to this common programming pitfall.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/01/how-to-access-the-size-of-a-collection-in-a-jsp-page-using-jstl-el/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>

