<?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; Session</title>
	<atom:link href="http://blog.smartkey.co.uk/tag/session/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>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>
	</channel>
</rss>

