<?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>Lucky Ryan</title>
	<atom:link href="http://www.luckyryan.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.luckyryan.com</link>
	<description></description>
	<lastBuildDate>Mon, 17 Jun 2013 05:28:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Apache CXF with Spring Integration</title>
		<link>http://www.luckyryan.com/2013/06/15/apache-cxf-with-spring-integration/</link>
		<comments>http://www.luckyryan.com/2013/06/15/apache-cxf-with-spring-integration/#comments</comments>
		<pubDate>Sun, 16 Jun 2013 06:54:25 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Apache CXF]]></category>
		<category><![CDATA[Tech Stuff]]></category>

		<guid isPermaLink="false">http://www.luckyryan.com/?p=179</guid>
		<description><![CDATA[<p>Apache CXF is an easy way to expose a business class as a web service via REST (jaxrs) or SOAP (jaxws). In some cases you may just want to separate the client and business logic across multiple servers. Spring Integration<span class="ellipsis">&#8230;</span><div class="read-more"><a href="http://www.luckyryan.com/2013/06/15/apache-cxf-with-spring-integration/">Read more &#8250;</a></div><!-- end of .read-more --></p><p>The post <a href="http://www.luckyryan.com/2013/06/15/apache-cxf-with-spring-integration/">Apache CXF with Spring Integration</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://cxf.apache.org" title="Apache CXF">Apache CXF</a> is an easy way to expose a business class as a web service via REST (jaxrs) or SOAP (jaxws). In some cases you may just want to separate the client and business logic across multiple servers. <a href="http://www.springsource.org/spring-integration" title="Spring Integration">Spring Integration</a> comes into play because it will add a nice abstraction from the web service interface into your core classes. The goal is to layer the web service on top of existing classes without the need for any changes to existing code. </p>
<div class="info-box information">
<strong>Application Setup</strong><br/><br />
This example is based on a <a href="http://www.luckyryan.com/2013/02/20/spring-mvc-with-basic-persistence-spring-data-jpa-hibernate/">previous post using Spring Data</a>. For this example that app was split into two project, CXF-client &#038; CXF-service. All web files retained for Client. Service has the DAO and models. Exceptions, DTO and new services are in each.
</div>
<h3>Dependencies</h3>
<p>The first step is to add the Apache and Spring dependencies to the project pom.xml. SI and Dozer are only needed for the service side.</p>
<pre class="brush: xml; title: pom.xml; notranslate">
  &lt;dependency&gt;
      &lt;groupId&gt;org.apache.cxf&lt;/groupId&gt;
      &lt;artifactId&gt;cxf-rt-frontend-jaxws&lt;/artifactId&gt;
      &lt;version&gt;2.7.5&lt;/version&gt;
  &lt;/dependency&gt;
  
  &lt;dependency&gt;
      &lt;groupId&gt;org.apache.cxf&lt;/groupId&gt;
      &lt;artifactId&gt;cxf-rt-frontend-jaxrs&lt;/artifactId&gt;
      &lt;version&gt;2.7.5&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;dependency&gt;
      &lt;groupId&gt;javax.ws.rs&lt;/groupId&gt;
      &lt;artifactId&gt;javax.ws.rs-api&lt;/artifactId&gt;
      &lt;version&gt;2.0-m10&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;dependency&gt;
      &lt;groupId&gt;org.springframework.integration&lt;/groupId&gt;
      &lt;artifactId&gt;spring-integration-xml&lt;/artifactId&gt;
      &lt;version&gt;2.2.3.RELEASE&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;!-- This will be used by SI to transform messages --&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;net.sf.dozer&lt;/groupId&gt;
      &lt;artifactId&gt;dozer&lt;/artifactId&gt;
      &lt;version&gt;5.4.0&lt;/version&gt;
  &lt;/dependency&gt;
</pre>
<p>Next define the interface for the web service. Although it&#8217;s possible to directly annotate your business class it&#8217;s good practice to keep them separate. This will allow you to only expose those methods you need and make it flexible to change the method parameters. </p>
<div class="info-box information">
<strong>Design Consideration</strong><br/><br />
This example interface is the defined interface that apache CXF will use to build the endpoints. If you are splitting an application client/service and using CXF for both sides, then the easy path would be to use this interface for both. One option is to copy the file and manually keep them in sync after changes. Another (my preferred) would be to put the interface and any dependent types in a new module then include the jar in the client and service app.
</div>
<h3>Service Interfaces</h3>
<pre class="brush: java; title: SampleServiceREST.java; notranslate">
// REST Setup (Follows JAX-RS)
@Path(&quot;/sampleService&quot;)
@Produces(&quot;application/json&quot;)
public interface SampleServiceREST {

    @POST
    @Consumes(&quot;application/json&quot;)
    @Produces(&quot;application/json&quot;)
    @Path(&quot;/saveForm&quot;)
    public SignupForm saveFrom(SignupForm signupForm);

}
</pre>
<p><strong>REST</strong><br />
@Path is the URL that will serve the resource. @Produces is the response type, @POST = Http POST verb, @Consumes is the expected content type and @Path extends the URL to expose this method.</p>
<pre class="brush: java; title: SampleServiceSOAP.java; notranslate">

// SOAP Setup (Follows JAX-WS)
@WebService
public interface SampleServiceSOAP {

    public SignupForm saveFrom(@WebParam(name=&quot;signupForm&quot;) SignupForm signupForm) throws InvalidUserException;
}
</pre>
<p><strong>SOAP</strong><br />
@WebService is used by CXF to expose this interface as a WSDL. @WebParam give the parameter a friendly name in the WSDL. The default is arg0. More info can be found on the <a href="http://cxf.apache.org/docs/a-simple-jax-ws-service.html">apache site</a> about the annotations. Specific reference to the InvalidUserException is needed to jaxws will send the correct exception. Any undefined exceptions will be translated to a SOAPFault. If you do use a custom exception then make sure it exists in both the service and client application.</p>
<p>Now we have a nice interface but it doesn&#8217;t do anything yet and nothing implements it. Before exposing it as a CXF servlet we are going to use Spring Integration to implement the interface and route the calls to our business layer. At first pass these routes will be simple but could always be extended to do transformations, logging or anything else you may need. </p>
<h3>Spring Integration Setup</h3>
<p>Link the Service Interface to the business service methods</p>
<pre class="brush: xml; title: applicationContext-si-cxf.xml; notranslate">
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:int=&quot;http://www.springframework.org/schema/integration&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd&quot;&gt;

    &lt;!-- wire rest with SI --&gt;
    &lt;int:gateway id=&quot;sampleServiceRESTGateway&quot;
                 service-interface=&quot;com.luckyryan.sample.ws.SampleServiceREST&quot;
                 default-request-channel=&quot;saveFormChannelREST&quot;&gt;
        &lt;int:method name=&quot;saveForm&quot; request-channel=&quot;saveFormChannelREST&quot; /&gt;
    &lt;/int:gateway&gt;

    &lt;!-- wire soap with SI --&gt;
    &lt;int:gateway id=&quot;sampleServiceSOAPGateway&quot;
                 service-interface=&quot;com.luckyryan.sample.ws.SampleServiceSOAP&quot;
                 default-request-channel=&quot;saveFormChannelSOAP&quot;&gt;

        &lt;int:method name=&quot;saveForm&quot; request-channel=&quot;saveFormChannelSOAP&quot;/&gt;
    &lt;/int:gateway&gt;

    &lt;int:channel id=&quot;saveFormChannelSOAP&quot;/&gt;
    &lt;int:channel id=&quot;saveFormChannelREST&quot;/&gt;

    &lt;int:chain input-channel=&quot;saveFormChannelSOAP&quot;&gt;
        &lt;int:transformer ref=&quot;userTransformer&quot; method=&quot;signupFormToUser&quot;/&gt;
        &lt;int:service-activator ref=&quot;sampleService&quot; method=&quot;saveUser&quot;/&gt;
        &lt;int:transformer ref=&quot;userTransformer&quot; method=&quot;userToSignupForm&quot;/&gt;
    &lt;/int:chain&gt;

    &lt;int:chain input-channel=&quot;saveFormChannelREST&quot;&gt;
        &lt;int:transformer ref=&quot;userTransformer&quot; method=&quot;signupFormToUser&quot;/&gt;
        &lt;int:service-activator ref=&quot;sampleService&quot; method=&quot;saveUser&quot;/&gt;
        &lt;int:transformer ref=&quot;userTransformer&quot; method=&quot;userToSignupForm&quot;/&gt;
    &lt;/int:chain&gt;

&lt;/beans&gt;

</pre>
<p>Note that we only need one Spring integration file to handle both SOAP &#038; REST. Just like any spring config each file can support multiple bean definitions. In this case we want both the SOAP &#038; REST calls to call the same business service method but use independent routes and processing chains.</p>
<p>Spring Integration Gateways become and implementation of an interface. SampleServiceSOAP or SampleServiceREST both are only interfaces with let CXF know that to expect and how to act. Spring Integration will automatically create bean implementations of those interfaces for us. But since it won&#8217;t know what to do for each service call, then we direct SI to put the massage (payload) on a set channel then direct it to our business class for processing. The chain is a connivence spring offers that saves XML. Without it each step, transformation, service, logging would need to follow channels. When using the chain SI infers the channels automatically for us. Note that message processing is sequential and synchronous. The message payload will start at the first chain entry and work down until the end at which point it is sent back to the web service. </p>
<h4>Example Chain</h4>
<p>SampleForm is posted from the client. Our business class needs a User object for persistence. So it needs transformation first, then the correct service method can be called us the user object. The service will return back a User object updated with the DB id. It then needs to be transformed back into a SampleForm so the client will know how to handle it.</p>
<p>The transformations are done with Dozer. <a href="http://dozer.sourceforge.net" title="Dozer">Dozer</a> out of the box will copy any duplicate named properties between two POJO&#8217;s. Since SampleForm and User have the same field names we can use the easy setup of dozer. This makes it easy to separate object &#038; concerns across layers of the application. A lot of times it is easy to just use the same POJO all the way through the app which can make things messy as an application grows.</p>
<pre class="brush: java; title: UserTransformer; notranslate">
private DozerBeanMapper mapper = new DozerBeanMapper();

public User signupFormToUser(SignupForm signupForm) {
    User user = mapper.map(signupForm, User.class);
    return user;
}

public SignupForm userToSignupForm(User user) {
    SignupForm signupForm = mapper.map(user, SignupForm.class);
    return signupForm;
}
</pre>
<h3>Link CXF Services to Spring Integration</h3>
<p>At this point the interfaces are now backed by SI and both when invoked will forward the payload to the business class. The next step is to wire the newly defined gateways into CXF which will expose them as a web servlet. </p>
<p>Define the CXF servlet in the WEB-INF folder</p>
<pre class="brush: xml; title: cxf-servlet.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:jaxws=&quot;http://cxf.apache.org/jaxws&quot;
       xmlns:jaxrs=&quot;http://cxf.apache.org/jaxrs&quot;
       xsi:schemaLocation=&quot;
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd&quot;&gt;

    &lt;!-- these are included in the dependency jar --&gt;
    &lt;import resource=&quot;classpath:META-INF/cxf/cxf.xml&quot;/&gt;
    &lt;import resource=&quot;classpath:META-INF/cxf/cxf-servlet.xml&quot;/&gt;

    &lt;!-- rest container --&gt;
    &lt;jaxrs:server id=&quot;sampleSerivceREST&quot; address=&quot;/rest&quot;&gt;
        &lt;jaxrs:serviceBeans&gt;
            &lt;ref bean=&quot;sampleServiceRESTGateway&quot;/&gt;
        &lt;/jaxrs:serviceBeans&gt;
        &lt;jaxrs:providers&gt;
            &lt;bean class=&quot;org.codehaus.jackson.jaxrs.JacksonJsonProvider&quot;/&gt;
            &lt;bean class=&quot;com.luckyryan.sample.service.ExceptionHandler&quot;/&gt;
        &lt;/jaxrs:providers&gt;
    &lt;/jaxrs:server&gt;

    &lt;!-- soap container --&gt;
    &lt;jaxws:endpoint
            id=&quot;sampleServiceSOAP&quot;
            implementor=&quot;#sampleServiceSOAPGateway&quot;
            address=&quot;/soap&quot;
            serviceName=&quot;sampleSoapService&quot;/&gt;
&lt;/beans&gt;
</pre>
<p>Here we define two endpoints with a unique URL that will invoke out SI gateways when called. Notice the SOAP container uses the #bean ref to access the spring bean. That is not needed for the REST container since it has the ref tag.</p>
<p>Next add the CXF servlet to the web.xml so we can expose the endpoints.</p>
<pre class="brush: xml; title: web.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;2.5&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt;

    &lt;display-name&gt;Sample App&lt;/display-name&gt;
    &lt;distributable/&gt;

    &lt;context-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;
            classpath:/applicationContext.xml
            classpath:/applicationContext-dao.xml
            classpath:/applicationContext-si-cxf.xml
            WEB-INF/cxf-servlet.xml
        &lt;/param-value&gt;
    &lt;/context-param&gt;

    &lt;listener&gt;
        &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
    &lt;/listener&gt;

    &lt;servlet&gt;
        &lt;description&gt;Apache CXF Endpoint&lt;/description&gt;
        &lt;display-name&gt;cxf&lt;/display-name&gt;
        &lt;servlet-name&gt;cxf&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.apache.cxf.transport.servlet.CXFServlet&lt;/servlet-class&gt;
        &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;cxf&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/services/*&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;

&lt;/web-app&gt;

</pre>
<p>Now the app should start and we can verify that the services are now exposed.</p>
<p><a href="http://cdn.luckyryan.com/wp-content/uploads/2013/06/cxf-service-index.png" rel="lightbox[179]"><img src="http://cdn.luckyryan.com/wp-content/uploads/2013/06/cxf-service-index.png" alt="cxf-service-index" width="500" class="alignnone size-medium wp-image-182" /></a></p>
<p>You can test the interface with a REST client (FireFox plugin or curl) or SOAP UI and see that the business service is invoked as expected.</p>
<h3>Setup the client</h3>
<p>The client application is a Spring MVC app that uses Java Config. Below is the entry to load a jaxrs &#038; jaxws client service as a spring bean.</p>
<pre class="brush: java; title: appConfig.xml; notranslate">
@Bean
public JacksonJsonProvider getJacksonJsonProvider() {
    return new JacksonJsonProvider();
}

@Bean
public ExceptionHandler getExceptionHandler() {
    return new ExceptionHandler();
}

@Bean
public SampleServiceREST getSampleServiceRestClient() {
    List providers = new ArrayList();
    providers.add(getJacksonJsonProvider());
    providers.add(getExceptionHandler());
    return JAXRSClientFactory.create(&quot;http://localhost:8090/services/rest&quot;,SampleServiceREST.class,providers);
}

@Bean
public SampleServiceSOAP getSampleServiceSoapClient() {
    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setServiceClass(SampleServiceSOAP.class);
    factory.setAddress(&quot;http://localhost:8090/services/soap&quot;);
    return (SampleServiceSOAP) factory.create();
}
</pre>
<p>The xml equivalent is </p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- rest container --&gt;
&lt;jaxrs:client id=&quot;sampleServiceREST&quot;
              serviceClass=&quot;com.luckyryan.sample.ws.SampleServiceREST&quot;
              address=&quot;http://localhost:8090/services/rest&quot;&gt;
    &lt;jaxrs:providers&gt;
        &lt;bean class=&quot;org.codehaus.jackson.jaxrs.JacksonJsonProvider&quot;/&gt;
		&lt;bean class=&quot;com.luckyryan.sample.exception.ExceptionHandler&quot;/&gt;
    &lt;/jaxrs:providers&gt;
&lt;/jaxrs:client&gt;

&lt;!-- soap container --&gt;
&lt;jaxws:client id=&quot;sampleServiceSOAP&quot;
              serviceClass=&quot;com.luckyryan.sample.ws.SampleServiceSOAP&quot;
              address=&quot;http://localhost:8090/services/soap&quot;/&gt;
</pre>
<p>This is about it for the client. It will also need the POM dependencies listed above but not the controller can use these services instead of &#8220;sampleService&#8221;. </p>
<div class="info-box information">
<strong>JAXRS Exception Handling</strong><br/><br />
There is some special considerations if using custom exceptions with REST/jaxrs. See this post (<a href="http://www.luckyryan.com/2013/06/15/apache-cxf-exception-handler-for-jaxrs-rest/" title="apache cxf exception handler">Apache CXF Exception Handler</a>) about an option to pass exceptions via rest.
</div>
<h3>Project Files</h3>
<div id='wpdm_file_2' class='wpdm_file wpdm-only-button'><div class='cont'><div class='btn_outer'><div class='btn_outer_c' style='background-image: url("http://cdn.luckyryan.com/wp-content/plugins/download-manager/icon/arrow down.png");'><a class='btn_left  ' rel='2' title='Sample Spring MVC + CXF Project Source' href='http://www.luckyryan.com/?wpdmact=process&did=Mi5ob3RsaW5r'  >Download Project Source Code</a><span class='btn_right'>&nbsp;</span></div></div><div class='clear'></div></div></div>
<p>The post <a href="http://www.luckyryan.com/2013/06/15/apache-cxf-with-spring-integration/">Apache CXF with Spring Integration</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.luckyryan.com/2013/06/15/apache-cxf-with-spring-integration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apache CXF exception handler for jaxrs (REST)</title>
		<link>http://www.luckyryan.com/2013/06/15/apache-cxf-exception-handler-for-jaxrs-rest/</link>
		<comments>http://www.luckyryan.com/2013/06/15/apache-cxf-exception-handler-for-jaxrs-rest/#comments</comments>
		<pubDate>Sat, 15 Jun 2013 23:06:59 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Apache CXF]]></category>
		<category><![CDATA[Tech Stuff]]></category>

		<guid isPermaLink="false">http://www.luckyryan.com/?p=174</guid>
		<description><![CDATA[<p>In another post (Apache CXF with Spring Integration) I covered splitting an application into a client/service structure using Apache CXF. In that project the business service would throw a custom exception if a certain user tried to register. The problem<span class="ellipsis">&#8230;</span><div class="read-more"><a href="http://www.luckyryan.com/2013/06/15/apache-cxf-exception-handler-for-jaxrs-rest/">Read more &#8250;</a></div><!-- end of .read-more --></p><p>The post <a href="http://www.luckyryan.com/2013/06/15/apache-cxf-exception-handler-for-jaxrs-rest/">Apache CXF exception handler for jaxrs (REST)</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>In another post (<a href="http://www.luckyryan.com/2013/06/15/apache-cxf-with-spring-integration/" title="Apache CXF with Spring Integration">Apache CXF with Spring Integration</a>) I covered splitting an application into a client/service structure using <a href="http://cxf.apache.org" title="Apache CXF">Apache CXF</a>. In that project the business service would throw a custom exception if a certain user tried to register. The problem is that without any special handing CXF will return a 500 error and lose the custom exception. The client will see the 500 response code and throw it&#8217;s own exception which is ambiguous. The result is broken logic in the Spring MVC controller which expected the custom exception. To solve this and restore the original functionality I implemented CXF exception handlers to set appropriate headers which the client can use to map back to the original custom exception and message. </p>
<p>Below is the service class that is throwing the custom exception:</p>
<pre class="brush: java; title: SampleServiceImpl.java; notranslate">
@Service(&quot;sampleService&quot;)
public class SampleServiceImpl implements SampleService {

    @Autowired
    UserDao userDao;

    public User saveUser(User user) throws InvalidUserException{

        String firstName = user.getFirstName();

        if(!StringUtils.isEmpty(firstName) &amp;&amp; &quot;Dave&quot;.equalsIgnoreCase(firstName)) {
            throw new InvalidUserException(&quot;Sorry Dave&quot;);
        }

        return userDao.save(user);

    }
}
</pre>
<p>Below is the original controller that would handle the InvalidUserException. The goal is to not change the controller method at all and still use CXF to make a REST call for the form creation.</p>
<pre class="brush: java; title: IndexController.java; notranslate">
@RequestMapping(value = &quot;/create&quot;, method = RequestMethod.POST)
public String search(Model model, @Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) {

    String returnPage = PAGE_INDEX;

    if (!result.hasErrors()) {
        try {
            model.addAttribute(&quot;form&quot;, sampleService.saveFrom(signupForm));
            returnPage = PAGE_SHOW;
        } catch (InvalidUserException e) {
            model.addAttribute(&quot;page_error&quot;, e.getMessage());
        }
    }
    return returnPage;
}
</pre>
<p>The first step is to implement a jaxrs exception handler that will modify the response. The CXF Exception Handler class lives on the service side and is responsible for setting the response. </p>
<pre class="brush: java; title: ExceptionHandler.java; notranslate">
import com.luckyryan.sample.exception.InvalidUserException;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

public class ExceptionHandler implements ExceptionMapper&lt;InvalidUserException&gt; {
    public Response toResponse(InvalidUserException exception) {
        Response.Status status;

        status = Response.Status.INTERNAL_SERVER_ERROR;

        return Response.status(status).header(&quot;exception&quot;, exception.getMessage()).build();
    }
}
</pre>
<p>Once this is registered in the jaxrs service provider list, it will be called automatically when the InvalidUserException is thrown. </p>
<p>This handler will set a 500 response code. That tells the rest client that an exception happened and will let us wire up a handler in the client. A custom header &#8220;exception&#8221; is also set with the original exception message so we can crab it from the client.</p>
<p>Add the ExceptionHandler to the service provider list in the server definition. This is set in cxf-servlet.xml.</p>
<pre class="brush: xml; title: cxf-servlet.xml; notranslate">
&lt;!-- rest container --&gt;
&lt;jaxrs:server id=&quot;sampleSerivceREST&quot; address=&quot;/rest&quot;&gt;
    &lt;jaxrs:serviceBeans&gt;
        &lt;ref bean=&quot;sampleServiceRESTGateway&quot;/&gt;
    &lt;/jaxrs:serviceBeans&gt;
    &lt;jaxrs:providers&gt;
        &lt;bean class=&quot;org.codehaus.jackson.jaxrs.JacksonJsonProvider&quot;/&gt;
        &lt;bean class=&quot;com.luckyryan.sample.service.ExceptionHandler&quot;/&gt;
    &lt;/jaxrs:providers&gt;
&lt;/jaxrs:server&gt;
</pre>
<p>At this point the service will now respond with a 500 response and custom header with the exception message. Next the client will need to translate that combo into the custom exception for the controller.</p>
<p>The CXF Exception Handler class lives in the client.</p>
<pre class="brush: java; title: ExceptionHandler.java; notranslate">
import org.apache.cxf.jaxrs.client.ResponseExceptionMapper;

import javax.ws.rs.core.Response;

public class ExceptionHandler implements ResponseExceptionMapper {

    @Override
    public Throwable fromResponse(Response response) {
        throw new InvalidUserException(response.getHeaderString(&quot;exception&quot;));
    }
}
</pre>
<p>This implements ResponseExceptionMapper which will give access to the Response object. Once this handler is added to the provider list it will be invoked for any 500 response for the service call.</p>
<p>Next it&#8217;s wired into the provider list.</p>
<div class="info-box information">
<strong>Spring Java Config &#038; Application Context XML</strong><br/><br />
This example app uses Spring with CXF. There are two examples below, one for Java Config and the other for xml. Only use the one relevant to your application.
</div>
<p>Spring Java Config</p>
<pre class="brush: java; title: appConfig.java; notranslate">
@Bean
public JacksonJsonProvider getJacksonJsonProvider() {
    return new JacksonJsonProvider();
}

@Bean
public ExceptionHandler getExceptionHandler() {
    return new ExceptionHandler();
}

@Bean
public SampleServiceREST getSampleServiceRestClient() {
    List providers = new ArrayList();
    providers.add(getJacksonJsonProvider());
    providers.add(getExceptionHandler());
    return JAXRSClientFactory.create(&quot;http://localhost:8090/services/rest&quot;,SampleServiceREST.class,providers);
}
</pre>
<p>Spring XML version</p>
<pre class="brush: xml; title: applicationContext-cxf.xml; notranslate">
&lt;!-- rest container --&gt;
&lt;jaxrs:client id=&quot;sampleServiceREST&quot;
              serviceClass=&quot;com.luckyryan.sample.ws.SampleServiceREST&quot;
              address=&quot;http://localhost:8090/services/rest&quot;&gt;
    &lt;jaxrs:providers&gt;
        &lt;bean class=&quot;org.codehaus.jackson.jaxrs.JacksonJsonProvider&quot;/&gt;
		&lt;bean class=&quot;com.luckyryan.sample.exception.ExceptionHandler&quot;/&gt;
    &lt;/jaxrs:providers&gt;
&lt;/jaxrs:client&gt;
</pre>
<p>That&#8217;s it! Now the application will handle the exception as before until it&#8217;s refactored into a better REST model.</p>
<p>The post <a href="http://www.luckyryan.com/2013/06/15/apache-cxf-exception-handler-for-jaxrs-rest/">Apache CXF exception handler for jaxrs (REST)</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.luckyryan.com/2013/06/15/apache-cxf-exception-handler-for-jaxrs-rest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring MVC with basic object persistence using Spring Data JPA and Hibernate</title>
		<link>http://www.luckyryan.com/2013/02/20/spring-mvc-with-basic-persistence-spring-data-jpa-hibernate/</link>
		<comments>http://www.luckyryan.com/2013/02/20/spring-mvc-with-basic-persistence-spring-data-jpa-hibernate/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 07:37:29 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Spring Data]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Tech Stuff]]></category>
		<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.luckyryan.com/?p=120</guid>
		<description><![CDATA[<p>In an previous post we created a Sample Spring MVC project that didn&#8217;t do much except have a simple form. In this example we will add a basic service to process the form input and then save it to the<span class="ellipsis">&#8230;</span><div class="read-more"><a href="http://www.luckyryan.com/2013/02/20/spring-mvc-with-basic-persistence-spring-data-jpa-hibernate/">Read more &#8250;</a></div><!-- end of .read-more --></p><p>The post <a href="http://www.luckyryan.com/2013/02/20/spring-mvc-with-basic-persistence-spring-data-jpa-hibernate/">Spring MVC with basic object persistence using Spring Data JPA and Hibernate</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>In an previous post we created a <a href="http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/" title="Sample Spring MVC app" target="_blank">Sample Spring MVC</a> project that didn&#8217;t do much except have a simple form. In this example we will add a basic service to process the form input and then save it to the database. For the database I am using MySQL, layered with Hibernate as the object mapper and then <a href="http://www.springsource.org/spring-data/jpa" title="Spring Data JPA" target="_blank">Spring Data JPA</a> for abstraction and some nice boilerplate crud operations. </p>
<p>The first step is creating our service to handle the business the logic. I am a firm believer in <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" title="Separation of Concerns" title="_blank">separation of concerns</a> and the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" title="Law of Demeter">law of demeter</a>. I interpret it here as using Spring MVC for Model=Forms, Views=JSP, Controller=View Processor &#038; link to the business service. This means that <strong>NO</strong> business logic is in the controller. Only code relevant to rendering the views or models goes here. These three things should be able to maintained by a front-end developer. The business logic could be in one or more services which could either reside in the application or external service accessed via REST or SOAP.</p>
<p>For this case we&#8217;ll setup the service in the application and its first purpose is to reject any user named &#8220;Dave&#8221; (sorry Dave&#8230;), then it will convert the form into a DB model for saving. The object ID from the database will be added to the form and returned back for display on the confirmation page.</p>
<p>Create the Service interface:</p>
<pre class="brush: java; title: SampleService.java; notranslate">
public interface SampleService {

    public SignupForm saveFrom(SignupForm signupForm) throws InvalidUserException;

}
</pre>
<p>Create the service implementation:</p>
<pre class="brush: java; title: SampleServiceImpl.java; notranslate">
@Service(&quot;sampleService&quot;)
public class SampleServiceImpl implements SampleService {

    public SignupForm saveFrom(SignupForm signupForm) throws InvalidUserException{

        String firstName = signupForm.getFirstName();

        if(StringUtils.isEmpty(firstName) || &quot;Dave&quot;.equalsIgnoreCase(firstName)) {
            throw new InvalidUserException(&quot;Sorry Dave&quot;);
        }

		// TODO: Save the form

        return signupForm;
    }
}

</pre>
<p>Notice the @Service annotation at the top. This is the same as @Component and will automatically be added to the Spring application context at startup. Make sure the component scan includes the base package with your services.</p>
<p>Next add the dependencies for spring data, jpa and hibernate to the <strong>pom.xml</strong></p>
<pre class="brush: xml; title: pom.xml; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;
    &lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt;
    &lt;version&gt;1.2.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.hibernate.javax.persistence&lt;/groupId&gt;
    &lt;artifactId&gt;hibernate-jpa-2.0-api&lt;/artifactId&gt;
    &lt;version&gt;1.0.1.Final&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
    &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
    &lt;version&gt;4.1.9.Final&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
    &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;
    &lt;version&gt;4.1.9.Final&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
    &lt;artifactId&gt;hibernate-ehcache&lt;/artifactId&gt;
    &lt;version&gt;4.1.9.Final&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
      &lt;groupId&gt;com.jolbox&lt;/groupId&gt;
      &lt;artifactId&gt;bonecp&lt;/artifactId&gt;
      &lt;version&gt;0.7.1.RELEASE&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;mysql&lt;/groupId&gt;
    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
    &lt;version&gt;5.1.22&lt;/version&gt;
	&lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;

</pre>
<div class="info-box information">
<strong>JDBC Driver/Connection Pool</strong><br />
<a href="http://jolbox.com" title="BoneCP" target="_blank">BoneCP</a> was added for the JDBC driver and connection pool. This could be swapped out for <a href-"http://commons.apache.org/dbcp/" title="Apache DBCP" target="_blank">Apache commons DBCP</a>, <a href="http://www.mchange.com/projects/c3p0/" title="C3P0" target="_blank">C3P0</a> or any other you prefer.
</div>
<p>Next create the DB model and add annotations that will instruct hibernate how to persist the object. Since the form allows a user to signup we will create a <strong>user</strong> class. This is created in <strong>com.luckyryan.sample.dao.model</strong></p>
<pre class="brush: java; title: user.java; notranslate">
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue
    private Long id;
    
    private String firstName;
    private String lastName;
    private String email;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
</pre>
<p>Now we need a <strong>UserDao</strong> to manage the User objects. This is were the cool stuff happens. Spring Data JPA makes this extremely easy. All we need in an interface and it will do the implementation for us. Even better is that there already is a <a href="http://static.springsource.org/spring-data/commons/docs/1.2.0.RELEASE/api/org/springframework/data/repository/CrudRepository.html" title="CrudRepository" target="_blank"> CrudRepository</a> interface that can be extended that will give you the basic operations for free. The <strong>UserDao</strong> is created in the <strong>dao</strong> package</p>
<pre class="brush: java; title: UserDao.java; notranslate">
import org.springframework.data.repository.CrudRepository;

public interface UserDao extends CrudRepository&lt;User, Integer&gt; {
}
</pre>
<div class="info-box information">
<strong>DAO Interface</strong><br />
There is no need to annotate the class. We will set the JPA scan path in the spring config so it will automatically be picked up and added to the application context.
</div>
<p>Create a property file for the db settings<br />
<strong>jdbc.properties</strong></p>
<pre>
jdbc.url=${jdbc.url}
jdbc.username=${jdbc.username}
jdbc.password=${jdbc.password}
</pre>
<p>This above property file is using a reference to pom.xml properties. This is accomplished using the resources plugin. If you get errors with this see the note at the bottom of the page. You could alternatively just specify the properties here if you don&#8217;t need to use profile or environment specific settings. </p>
<p>Configure JPA, Hibernate and BoneCP with Spring Data. The XML and Java Config options are listed below, you only need the style relevant to your project, not both. </p>
<p><strong>xml</strong></p>
<pre class="brush: xml; title: applicationContext-dao.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xmlns:util=&quot;http://www.springframework.org/schema/util&quot;
       xmlns:jpa=&quot;http://www.springframework.org/schema/data/jpa&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
           http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd&quot;&gt;

    &lt;context:annotation-config/&gt;
    &lt;context:component-scan base-package=&quot;com.luckyryan.sample&quot;/&gt;

    &lt;!-- BoneCP configuration --&gt;
    &lt;bean id=&quot;mainDataSource&quot; class=&quot;com.jolbox.bonecp.BoneCPDataSource&quot; destroy-method=&quot;close&quot;&gt;
        &lt;property name=&quot;driverClass&quot; value=&quot;com.mysql.jdbc.Driver&quot; /&gt;
        &lt;property name=&quot;jdbcUrl&quot; value=&quot;${jdbc.url}&quot; /&gt;
        &lt;property name=&quot;username&quot; value=&quot;${jdbc.username}&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;${jdbc.password}&quot;/&gt;
        &lt;property name=&quot;idleConnectionTestPeriodInMinutes&quot; value=&quot;60&quot;/&gt;
        &lt;property name=&quot;idleMaxAgeInMinutes&quot; value=&quot;240&quot;/&gt;
        &lt;property name=&quot;maxConnectionsPerPartition&quot; value=&quot;30&quot;/&gt;
        &lt;property name=&quot;minConnectionsPerPartition&quot; value=&quot;10&quot;/&gt;
        &lt;property name=&quot;partitionCount&quot; value=&quot;3&quot;/&gt;
        &lt;property name=&quot;acquireIncrement&quot; value=&quot;5&quot;/&gt;
        &lt;property name=&quot;statementsCacheSize&quot; value=&quot;100&quot;/&gt;
        &lt;property name=&quot;releaseHelperThreads&quot; value=&quot;3&quot;/&gt;
    &lt;/bean&gt;

    &lt;!-- SPRING - JPA --&gt;
    &lt;jpa:repositories
            base-package=&quot;com.luckyryan.sample.dao&quot; /&gt;

    &lt;bean class=&quot;org.springframework.orm.jpa.JpaTransactionManager&quot;
          id=&quot;transactionManager&quot;&gt;
        &lt;property name=&quot;entityManagerFactory&quot;
                  ref=&quot;entityManagerFactory&quot; /&gt;
        &lt;property name=&quot;jpaDialect&quot;&gt;
            &lt;bean class=&quot;org.springframework.orm.jpa.vendor.HibernateJpaDialect&quot; /&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;entityManagerFactory&quot;
          class=&quot;org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean&quot;&gt;
        &lt;property name=&quot;dataSource&quot; ref=&quot;mainDataSource&quot; /&gt;
        &lt;property name=&quot;packagesToScan&quot; value=&quot;com.luckyryan.sample.dao.model&quot;/&gt;
        &lt;property name=&quot;jpaVendorAdapter&quot;&gt;
            &lt;bean class=&quot;org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter&quot;&gt;
                &lt;property name=&quot;generateDdl&quot; value=&quot;true&quot; /&gt;
                &lt;property name=&quot;showSql&quot; value=&quot;false&quot;/&gt;
                &lt;property name=&quot;databasePlatform&quot; value=&quot;org.hibernate.dialect.MySQLDialect&quot;/&gt;
                &lt;property name=&quot;database&quot; value=&quot;MYSQL&quot;/&gt;
            &lt;/bean&gt;
        &lt;/property&gt;
        &lt;property name=&quot;jpaProperties&quot;&gt;
            &lt;value&gt;
                hibernate.cache.use_second_level_cache = true
                hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
                hibernate.cache.use_query_cache = true
                hibernate.generate_statistics = true
            &lt;/value&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>The xml can be included in the project <strong>web.xml</strong> or as an include in another applcationContext.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;context-param&gt;
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
    &lt;param-value&gt;
        classpath:applicationContext-dao.xml
    &lt;/param-value&gt;
&lt;/context-param&gt;
</pre>
<p><strong>Java Config</strong></p>
<pre class="brush: java; title: dbConfig.java; notranslate">
package com.luckyryan.sample.config;


import com.jolbox.bonecp.BoneCPDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import java.util.Properties;

@PropertySource(value = &quot;classpath:db.properties&quot;)
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(&quot;com.luckyryan.sample.dao&quot;)
@Configuration
public class dbConfig {

    @Autowired
    Environment env;

    @Bean
    public BoneCPDataSource boneCPDataSource() {

        BoneCPDataSource boneCPDataSource = new BoneCPDataSource();
        boneCPDataSource.setDriverClass(&quot;com.mysql.jdbc.Driver&quot;);
        boneCPDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.url&quot;));
        boneCPDataSource.setUsername(env.getProperty(&quot;jdbc.username&quot;));
        boneCPDataSource.setPassword(env.getProperty(&quot;jdbc.password&quot;));
        boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60);
        boneCPDataSource.setIdleMaxAgeInMinutes(420);
        boneCPDataSource.setMaxConnectionsPerPartition(30);
        boneCPDataSource.setMinConnectionsPerPartition(10);
        boneCPDataSource.setPartitionCount(3);
        boneCPDataSource.setAcquireIncrement(5);
        boneCPDataSource.setStatementsCacheSize(100);
        boneCPDataSource.setReleaseHelperThreads(3);

        return boneCPDataSource;

    }

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator() {
        return new HibernateExceptionTranslator();
    }

    @Bean
    @Autowired
    public EntityManagerFactory entityManagerFactory(BoneCPDataSource dataSource) {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(false);
        vendorAdapter.setDatabasePlatform(&quot;org.hibernate.dialect.MySQL5InnoDBDialect&quot;);
        vendorAdapter.setDatabase(Database.MYSQL);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan(&quot;com.luckyryan.sample.dao.model&quot;);
        factory.setDataSource(dataSource);

        Properties properties = new Properties();
        properties.setProperty(&quot;hibernate.cache.use_second_level_cache&quot;, &quot;true&quot;);
        properties.setProperty(&quot;hibernate.cache.region.factory_class&quot;, &quot;org.hibernate.cache.ehcache.EhCacheRegionFactory&quot;);
        properties.setProperty(&quot;hibernate.cache.use_query_cache&quot;, &quot;true&quot;);
        properties.setProperty(&quot;hibernate.generate_statistics&quot;, &quot;true&quot;);

        factory.setJpaProperties(properties);

        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    @Autowired
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager txManager = new JpaTransactionManager();
        JpaDialect jpaDialect = new HibernateJpaDialect();
        txManager.setEntityManagerFactory(entityManagerFactory);
        txManager.setJpaDialect(jpaDialect);
        return txManager;
    }

}
</pre>
<p>This file config can be added to the main config with the import annotation.</p>
<pre>
@Configuration
@Import(dbConfig.class)
public class appConfig {
	...
}

</pre>
<div class="info-box information">
<strong>HibernateExceptionTranslator</strong><br />
Notice that a HibernateExceptionTranslator is specified in the Java Config and not in the xml. This was an xml freebie and needs specific declaration for the java config.
</div>
<p>The Java Config version takes advantage of the environment feature introduced in Spring 3.1. This is a great feature that allows you to change profiles at runtime which would allow changes to the db properties and which database was being used. In the XML version this still used db.properties and maven resources plugin to set this at build time.</p>
<p>The first part is BoneCP. This is the data source and connection pool that will talk to mysql. We tell BoneCP to use the MySQL driver and set options for pooling and connection settings. </p>
<p>Next tell Spring Data to scan a package for repository interfaces. No specific class annotation is needed for this to work.</p>
<pre class="brush: java; title: ; notranslate">
&lt;jpa:repositories base-package=&quot;com.luckyryan.sample.dao&quot; /&gt;
or
@EnableJpaRepositories(&quot;com.luckyryan.sample.dao&quot;)
</pre>
<p>We need a transaction manager, give it the entity manager bean and the dialect that we are using. </p>
<p>The entity manger is core. This is were we tell it the data source and that we want to use Hibernate as the JPA implementation.<br />
<strong>packagesToScan</strong> is the scan path of the annotated models. Instead of annotations you can skip this property and define a mapping file.<br />
<strong>jpaVendorAdapter</strong> is were we set hibernate. There are properties that we can add here that are good time savers for testing. <strong>generateDdl</strong> will automatically update the schema to match the declared models at startup. Awesome for testing but I suggest revising this setting in production, sometimes automatic column changes are not desirable. <strong>showSql</strong> will output the sql string to the log, great for debugging but also something that should not hit production. You will also need to tell hibernate which database you are using so it can map and build the sql appropriately.<br />
<strong>jpaProperties</strong> is an a generic property list. The XML makes this nice because a key value pair is automatically converted to the correct type where it&#8217;s explicit declaration in the java config. For this app we are passing in hibernate properties which also removed the need for a persistence.xml since we already have annotated models and now global properties like caching are declared.  </p>
<p>Now we can autowire the Dao into the service and save the user form.</p>
<pre class="brush: java; title: sampleService.java; notranslate">
@Service
public class SampleServiceImpl implements SampleService {

    @Autowired
    UserDao userDao;

    public SignupForm saveFrom(SignupForm signupForm) throws InvalidUserException{

        String firstName = signupForm.getFirstName();

        if(StringUtils.isEmpty(firstName) || &quot;Dave&quot;.equalsIgnoreCase(firstName)) {
            throw new InvalidUserException(&quot;Sorry Dave&quot;);
        }

        // Shown for example only, you could use a constructor, builder pattern or Dozer
        // point is that the DAO only knows and cares about users and not any UI form.
        User user = new User();
        user.setFirstName(signupForm.getFirstName());
        user.setEmail(signupForm.getEmail());
        user.setLastName(signupForm.getLastName());

        user = userDao.save(user);

        signupForm.setId(user.getId());

        return signupForm;

    }
}
</pre>
<p>The above will show that saves the form and the updated signupForm now has an id that we can use in the jsp to build CRUD links. Overall the above method is crap for design but at least shows the concept. I know it a few days I won&#8217;t be able to sleep because I wrote this method this way&#8230;</p>
<p>Now create a local schema (with what ever name you defined in the property file) and start the app. It will automatically create the table and columns for you. Enter some test data, submit and you will see a new row in the database.</p>
<p>Next steps would be showing the updated form on the completion page or adding an edit method to the form.</p>
<div class="info-box information">
<strong>Build Error &#8211; Stack overflow</strong><br />
If you get a build error because the property file resulting in a stack overflow error. It is probably because the maven resources plugin is trying to replace circular references. To fix it you can update the resources part of the build section of the pom.xml to exclude the applicationContext*.xml files.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;resources&gt;
    &lt;resource&gt;
        &lt;directory&gt;src/main/resources&lt;/directory&gt;
        &lt;excludes&gt;
            &lt;exclude&gt;*.xml&lt;/exclude&gt;
        &lt;/excludes&gt;
        &lt;filtering&gt;true&lt;/filtering&gt;
    &lt;/resource&gt;
    &lt;resource&gt;
        &lt;directory&gt;src/main/resources&lt;/directory&gt;
        &lt;includes&gt;
            &lt;include&gt;*.xml&lt;/include&gt;
        &lt;/includes&gt;
        &lt;filtering&gt;false&lt;/filtering&gt;
    &lt;/resource&gt;
&lt;/resources&gt;
</pre>
</div>
<div id='wpdm_file_1' class='wpdm_file wpdm-only-button'><div class='cont'><div class='btn_outer'><div class='btn_outer_c' style='background-image: url("http://cdn.luckyryan.com/wp-content/plugins/download-manager/icon/arrow down.png");'><a class='btn_left  ' rel='1' title='Sample Spring MVC + JPA Project Source' href='http://www.luckyryan.com/?wpdmact=process&did=MS5ob3RsaW5r'  >Download Project Source Code</a><span class='btn_right'>&nbsp;</span></div></div><div class='clear'></div></div></div>
<p>The post <a href="http://www.luckyryan.com/2013/02/20/spring-mvc-with-basic-persistence-spring-data-jpa-hibernate/">Spring MVC with basic object persistence using Spring Data JPA and Hibernate</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.luckyryan.com/2013/02/20/spring-mvc-with-basic-persistence-spring-data-jpa-hibernate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Create a Maven Archetype from an existing project</title>
		<link>http://www.luckyryan.com/2013/02/15/create-maven-archetype-from-existing-project/</link>
		<comments>http://www.luckyryan.com/2013/02/15/create-maven-archetype-from-existing-project/#comments</comments>
		<pubDate>Sat, 16 Feb 2013 07:16:50 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Maven]]></category>
		<category><![CDATA[Tech Stuff]]></category>
		<category><![CDATA[Archetype]]></category>

		<guid isPermaLink="false">http://www.luckyryan.com/?p=106</guid>
		<description><![CDATA[<p>Maven archetypes are project templates that can quickly jump start new projects that are based on a set of core files. One of my favorite examples is AppFuse. Matt has created archetypes for a variety of projects that will get<span class="ellipsis">&#8230;</span><div class="read-more"><a href="http://www.luckyryan.com/2013/02/15/create-maven-archetype-from-existing-project/">Read more &#8250;</a></div><!-- end of .read-more --></p><p>The post <a href="http://www.luckyryan.com/2013/02/15/create-maven-archetype-from-existing-project/">Create a Maven Archetype from an existing project</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Maven archetypes are project templates that can quickly jump start new projects that are based on a set of core files. One of my favorite examples is <a title="AppFuse" href="www.appfuse.org">AppFuse</a>. Matt has created archetypes for a variety of projects that will get you up and running with a basic app that has user management built in. For this example my goal is to turn the <a title="Simple MVC Project" href="http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/">simple Spring MVC</a> project into a template to create new example projects.</p>
<p>There are two ways to kickoff an archetype project:<br />
1. Build the project layout by scratch and add files as need<br />
2. Run the <a title="maven archetype plugin" href="http://maven.apache.org/archetype/maven-archetype-plugin/index.html">Maven archetype plugin</a> on an existing project and configure from there.</p>
<p>Since we already have a sample project I&#8217;m going to cover option two.</p>
<p>First navigate to the root directory of the source project and run the following maven command</p>
<pre>mvn archetype:create-from-project</pre>
<p>After some maven magic you should see &#8220;BUILD SUCCESS&#8221;.</p>
<pre>[INFO] 
[INFO] --- maven-archetype-plugin:2.2:jar (default-jar) @ TestProject-archetype ---
[INFO] Building archetype jar: /Users/ryan/projects/SampleMVC/target/generated-sources/archetype/target/SampleMVC-archetype-1.0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 19.660s
[INFO] Finished at: Fri Feb 15 21:58:42 PST 2013
[INFO] Final Memory: 10M/554M
[INFO] ------------------------------------------------------------------------
[INFO] Archetype created in /Users/ryan/projects/SampleMVC/target/generated-sources/archetype
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 22.853s
[INFO] Finished at: Fri Feb 15 21:58:43 PST 2013
[INFO] Final Memory: 8M/554M
[INFO] ------------------------------------------------------------------------</pre>
<p>The first success is the packaged archetype. This packages a jar file which can be used in a maven repo when generating new projects. Since we need to make modifications we&#8217;ll skip that for now. The second success id the archetype project.</p>
<p>Copy the <strong>target/generated-sources/archetype</strong> to a new directory and evaluate for changes.</p>
<p>The root structure is<br />
- pom.xml<br />
- src/<br />
- target/</p>
<p>Target can me removed with <strong>mvn clean</strong><strong></strong></p>
<p><strong>pom.xml</strong> is the pom of the archetype and only has those things needed to build the archetype jar. We&#8217;ll only need to change to a 1.0-SNAPSHOT version since the first release is not final yet.</p>
<p><strong>src/</strong> is the archetype project source. This only has a few required components. main &amp; test are standard. <strong>test/resources</strong><strong> was created for us and has entries for integration testing.</strong></p>
<div class="info-box information"><strong>Testing Archetypes</strong></div>
<p>There is support for running integration tests which will verify project creating and even compare the generated project to a reference one. This is useful when building up a project. See <a title="archetype:integration-test" href="http://maven.apache.org/archetype/maven-archetype-plugin/integration-test-mojo.html">archetype:integration-test</a><a> for more information.<br />
</a></p>
<p><strong>main/resources</strong> has two folders:<br />
1. <strong>archetype-resources</strong> &#8211; this is the project template and what will be generated when the archetype is run<br />
2. <strong>META-INF/maven</strong> &#8211; this contains the archetype-metadata.xml file which has the settings and options when generating a new project.</p>
<p><a href="http://cdn.luckyryan.com/wp-content/uploads/2013/02/archetype_layout.png" rel="lightbox"><img class="alignnone size-medium wp-image-107" alt="archetype_layout" src="http://cdn.luckyryan.com/wp-content/uploads/2013/02/archetype_layout-300x232.png" width="300" height="232" /></a></p>
<p>Looking through the <strong>src/main/java</strong> folder we see that all the packages from the original project are gone. This is because maven will add it back from the groupId or package variable when generating a new project. Anything from this root will still be retained in the new project. For example is the package is &#8220;com.luckyryan.sample&#8221; then webapp would become /src/main/java/com/luckyryan/sample/webapp. Anything under webapp with be stored respective to that folder.</p>
<p>After a quick look all seems to be in order so let&#8217;s look at the project options.</p>
<pre class="brush: xml; title: archetype-metadata.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;archetype-descriptor xsi:schemaLocation=&quot;http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0 http://maven.apache.org/xsd/archetype-descriptor-1.0.0.xsd&quot; name=&quot;SampleMVC&quot;
    xmlns=&quot;http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;
    &lt;requiredProperties&gt;
        &lt;requiredProperty key=&quot;groupId&quot;&gt;
            &lt;defaultValue&gt;com.luckyryan&lt;/defaultValue&gt;
        &lt;/requiredProperty&gt;
        &lt;requiredProperty key=&quot;artifactId&quot;/&gt;
        &lt;requiredProperty key=&quot;version&quot;&gt;
            &lt;defaultValue&gt;1.0-SNAPSHOT&lt;/defaultValue&gt;
        &lt;/requiredProperty&gt;
        &lt;requiredProperty key=&quot;package&quot;&gt;
            &lt;defaultValue&gt;com.luckyryan.sample&lt;/defaultValue&gt;
        &lt;/requiredProperty&gt;
    &lt;/requiredProperties&gt;
  &lt;fileSets&gt;
    &lt;fileSet filtered=&quot;true&quot; packaged=&quot;true&quot; encoding=&quot;UTF-8&quot;&gt;
      &lt;directory&gt;src/main/java&lt;/directory&gt;
      &lt;includes&gt;
        &lt;include&gt;**/*.java&lt;/include&gt;
      &lt;/includes&gt;
    &lt;/fileSet&gt;
    &lt;fileSet filtered=&quot;true&quot; encoding=&quot;UTF-8&quot;&gt;
      &lt;directory&gt;src/main/webapp&lt;/directory&gt;
      &lt;includes&gt;
        &lt;include&gt;**/*.jsp&lt;/include&gt;
        &lt;include&gt;**/*.xml&lt;/include&gt;
      &lt;/includes&gt;
    &lt;/fileSet&gt;
    &lt;fileSet filtered=&quot;true&quot; encoding=&quot;UTF-8&quot;&gt;
      &lt;directory&gt;src/main/resources&lt;/directory&gt;
      &lt;includes&gt;
        &lt;include&gt;**/*.xml&lt;/include&gt;
      &lt;/includes&gt;
    &lt;/fileSet&gt;
  &lt;/fileSets&gt;
&lt;/archetype-descriptor&gt;
</pre>
<p>I added the required properties at the top of the file. <strong>groupId</strong>,<strong>artifactId</strong>, <strong>package</strong> &amp; <strong>version</strong> are used by default. I define them here to give default values since in my scenario they won&#8217;t change.</p>
<div class="info-box information"><strong>Custom Variables</strong></div>
<p>You can define custom variables in this section. For each variable you will also need to add it in <strong>src/test/resources/projects/basic/archetype.properties</strong> as a key/value pair. The helpful part of required variable definition is maven will prompt the user to enter the value during project creation.</p>
<p>File that contain variables must be in a fileSet with filtered=&#8221;true&#8221;. The default in file syntax is like a Velocity template &#8220;${varName}&#8221; but they can also be used in directory names as &#8220;__varname__&#8221; (two _ before and after the var name).</p>
<p>Filesets tell maven what needs to be coped and how. The <strong>filtered</strong> flag indicates that those files will be processed by the Velocity engine and any matching variables will be replaced. So if you have a need to change a value in a file or config the use the &#8220;${varName}&#8221; syntax and make sure it is in a file set with filtered=&#8221;true&#8221;. The <strong>packaged</strong> flag will copy those filed into a structure prefixed with the package property.</p>
<p>An excellent description of metadata files options can be found on the <a title="archetype-metadata.xml" href="http://maven.apache.org/archetype/maven-archetype-plugin/specification/archetype-metadata.html">maven site</a>.</p>
<p>Once the archetype matches what we want. It&#8217;s time to install it locally and generate a sample project.<br />
1. From the archetype root run <strong>mvn install</strong><br />
2. Create a new project directory <strong>/Users/ryan/projects/new_sample</strong><br />
3. Run the generate command <strong>mvn archetype:generate -DarchetypeCatalog=local</strong>. Local tells maven to look to the local repo for all archetypes and present with a list to pick one.<br />
4. Enter the required parameters and the project is created.<br />
5. cd into the project directory and run </strong><strong>mvn jetty:run</strong><br />
6. Preview the new app</p>
<div class="info-box information"><strong>Archetype Deployments</strong>Once you want to share the archetype then the packaged jar will need to be deployed to a maven repo. From there you can use the following command to generate a new project.</p>
<pre>mvn archetype:generate 
    -DarchetypeGroupId=you_archetype_group_id 
    -DarchetypeArtifactId=sample-spring-mvc-archetype 
    -DarchetypeVersion=1.0-SNAPSHOT -DgroupId=new.project.id 
    -DartifactId=sample 
    -DarchetypeRepository=path_to_maven_repo_with_archetype_jar</pre>
</div>
<p>This was a quick example to get exposure to creating archetypes. For more Maven information I recommend reviewing the <a title="Apache Maven" href="http://maven.apache.org">Apache Maven</a> site and the <a title="Maven: The Complete Reference" href="http://www.sonatype.com/books/mvnref-book/reference/public-book.html">Sonatype Maven Guide</a>.</p>
<p>The post <a href="http://www.luckyryan.com/2013/02/15/create-maven-archetype-from-existing-project/">Create a Maven Archetype from an existing project</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.luckyryan.com/2013/02/15/create-maven-archetype-from-existing-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring MVC form validation with HDIV (HTTP Data Integrity Validator)</title>
		<link>http://www.luckyryan.com/2013/02/14/spring-mvc-form-validation-with-hdiv-http-data-integrity-validator/</link>
		<comments>http://www.luckyryan.com/2013/02/14/spring-mvc-form-validation-with-hdiv-http-data-integrity-validator/#comments</comments>
		<pubDate>Fri, 15 Feb 2013 06:26:46 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Tech Stuff]]></category>
		<category><![CDATA[HDIV]]></category>

		<guid isPermaLink="false">http://www.luckyryan.com/?p=96</guid>
		<description><![CDATA[<p>HDIV is a cool site addition to help secure web applications. Out of the box it will help prevent cross site request forgery (CSRF), remove the ability to alter non-editable data (hidden fields, params&#8230;) and even has options to limit<span class="ellipsis">&#8230;</span><div class="read-more"><a href="http://www.luckyryan.com/2013/02/14/spring-mvc-form-validation-with-hdiv-http-data-integrity-validator/">Read more &#8250;</a></div><!-- end of .read-more --></p><p>The post <a href="http://www.luckyryan.com/2013/02/14/spring-mvc-form-validation-with-hdiv-http-data-integrity-validator/">Spring MVC form validation with HDIV (HTTP Data Integrity Validator)</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.hdiv.org" title="HTTP Data Integrity Validator">HDIV</a> is a cool site addition to help secure web applications. Out of the box it will help prevent cross site request forgery (CSRF), remove the ability to alter non-editable data (hidden fields, params&#8230;) and even has options to limit characters globally across form fields. Having used it a project I found that the documentation can be hard to follow and there are implications when attempting to mix in Spring validation via the @Valid annotation. This is a quick guide to setup the basic features and tips when wanting to extending into custom field validation.</p>
<p>This is based on a very simple sample Spring MVC app referenced in <a href="http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/" title="Setup a simple Spring MVC site with Maven">an earlier post</a>. </p>
<p>Our goal will be to secure the site so only the form page can be directly accessed. The success page should redirect to the form with an error if the first page is skipped. We will also add a global filter to prevent unauthorized characters (SQL injection, XSS, bad data&#8230;) from being entered into any field using the @Valid annotation.</p>
<p>First add the required dependencies to the project <strong>pom.xml</strong>. For this example we will use HDIV version 2.1.3. 2.1.4-SNAPSHOT has some nice enhancements but changes and considerations are necessary.  </p>
<pre class="brush: xml; title: pom.xml; notranslate">
&lt;!-- HDIV --&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;org.hdiv&lt;/groupId&gt;
      &lt;artifactId&gt;hdiv-core&lt;/artifactId&gt;
      &lt;version&gt;2.1.3&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;dependency&gt;
      &lt;groupId&gt;org.hdiv&lt;/groupId&gt;
      &lt;artifactId&gt;hdiv-config&lt;/artifactId&gt;
      &lt;version&gt;2.1.3&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;dependency&gt;
      &lt;groupId&gt;org.hdiv&lt;/groupId&gt;
      &lt;artifactId&gt;hdiv-spring-mvc&lt;/artifactId&gt;
      &lt;version&gt;2.1.3&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;dependency&gt;
      &lt;groupId&gt;org.hdiv&lt;/groupId&gt;
      &lt;artifactId&gt;hdiv-jstl-taglibs-1.2&lt;/artifactId&gt;
      &lt;version&gt;2.1.3&lt;/version&gt;
  &lt;/dependency&gt;

&lt;!-- Validation JSR-303 support for @Valid --&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;javax.validation&lt;/groupId&gt;
      &lt;artifactId&gt;validation-api&lt;/artifactId&gt;
      &lt;version&gt;1.0.0.GA&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;
      &lt;version&gt;4.3.1.Final&lt;/version&gt;
  &lt;/dependency&gt;
</pre>
<p>Create the <strong>hdiv-config.xml</strong> file in /src/main/resources/</p>
<pre class="brush: xml; title: hdiv-config.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:hdiv=&quot;http://www.hdiv.org/schema/hdiv&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.hdiv.org/schema/hdiv http://www.hdiv.org/schema/hdiv/hdiv.xsd&quot;&gt;


    &lt;hdiv:config excludedExtensions=&quot;css,png,gif,jpeg,jpg,js&quot; errorPage=&quot;/security-error&quot; randomName=&quot;true&quot;&gt;
        &lt;hdiv:startPages&gt;/,/index&lt;/hdiv:startPages&gt;
    &lt;/hdiv:config&gt;

    &lt;!-- Accepted pattern within the application for all editable parameters (generated from textbox and textarea) --&gt;
    &lt;hdiv:validation id=&quot;safeText&quot;&gt;
        &lt;hdiv:acceptedPattern&gt;&lt;![CDATA[^[a-zA-Z0-9@.-_]*$]]&gt;&lt;/hdiv:acceptedPattern&gt;
    &lt;/hdiv:validation&gt;

    &lt;!-- Finally, it's necessary to define editable data validation list for
         the application --&gt;
    &lt;hdiv:editableValidations&gt;
        &lt;hdiv:validationRule url=&quot;/.*&quot;&gt;safeText&lt;/hdiv:validationRule&gt;
    &lt;/hdiv:editableValidations&gt;


&lt;/beans&gt;
</pre>
<p>The documentation on the <a href="http://www.hdiv.org" title="HTTP Data Integrity Validator">HDIV</a> site is good for creating this file. </p>
<p>This file defines a few beans for with easy syntax. The config class is set to exclude common static files (css,png&#8230;) from the security filter, errorPage is where the 301 redirect will send the client when a HDIV violation is detected. RandomName refers to the parameter name that HDIV will use to track the page token. On forms this is the last hidden input in the form, on regular pages it&#8217;s appended to the param string. </p>
<p>Start pages will generate the CSRF token and allow users to directly load the page without needing the token first.</p>
<div class="info-box information">
The random name does make it a little harder to load test with JMeter as you will need to use an XPath extractor with a value of &#8220;//input[@type="hidden"][last()]/@value&#8221; to get the token. With JMeter 2.9 you can use the CSS/jQuery extractor with expression &#8220;input[type=hidden]&#8220;, attribute &#8220;value&#8221; and match number to last hidden index. Then you will need to use the token &#038; param name to pass in on the next request.
</div>
<p>The next beans are for field validation. This gives all the features for SQL injection &#038; XSS prevention. The id of the validation declaration is used to map urls. The acceptedPattern above is the default/recommended for text boxes. </p>
<p>Editable validation defines the URL&#8217;s that will filter all form input. This is at best restricted to a page, field level would need to be handled in the controller to bindings. </p>
<p>At this stage it&#8217;s defined but not active until we setup the HDIV filter in <strong>web.xml</strong> and wire it up to Spring in the servlet-config.</p>
<pre class="brush: xml; title: web.xml; notranslate">
&lt;context-param&gt;
       &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
       &lt;param-value&gt;
           classpath*:/applicationContext.xml
           classpath:/hdiv-config.xml
       &lt;/param-value&gt;
   &lt;/context-param&gt;

....

&lt;!-- HDIV Filters --&gt;
    &lt;filter&gt;
        &lt;filter-name&gt;ValidatorFilter&lt;/filter-name&gt;
        &lt;filter-class&gt;org.hdiv.filter.ValidatorFilter&lt;/filter-class&gt;
    &lt;/filter&gt;

    &lt;filter-mapping&gt;
        &lt;filter-name&gt;ValidatorFilter&lt;/filter-name&gt;
        &lt;servlet-name&gt;app&lt;/servlet-name&gt;
    &lt;/filter-mapping&gt;

....

&lt;!-- HDIV Listener --&gt;
&lt;listener&gt;
    &lt;listener-class&gt;org.hdiv.listener.InitListener&lt;/listener-class&gt;
&lt;/listener&gt;
</pre>
<p>Add <strong>hdiv-config.xml</strong> to the contextConfigLocation params. This will let Spring load the beans. Next add the filters so HDIV can interact with the session and params. Lastly add the listener and this file is done.</p>
<p>Next wire the text validations into Spring. This will get the hasErrors() to respond and get the HDIV message out to the form:errors tag.</p>
<pre class="brush: xml; title: app-servlet.xml; notranslate">

&lt;bean id=&quot;editableValidator&quot; class=&quot;org.hdiv.web.validator.EditableParameterValidator&quot;/&gt;

&lt;mvc:annotation-driven validator=&quot;editableValidator&quot; /&gt;

</pre>
<p>This above will enable @Valid to use HDIV instead of the default hibernate validator. The hibernate validator is loaded automatically from the classpath and gives you access to javax JSR-303 validation annotations. But in this case we will not be using them and delegate it all to HDIV.</p>
<div class="info-box notice">
<strong>Java Config Update (4/8/13)</strong><br />
I have another post about converting the servlet &#038; web.xml to use springs new java config option. If you want to port HDIV over to use that method then follow the steps in the <a href="http://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/" title="servlet.xml to java config">Servlet to Java Config</a> post and apply the following:</p>
<pre class="brush: java; title: appConfig.java; notranslate">

// This overrides the javax field validator with HDIV
// Remove this block to disable HDIV field validation
@Override
public Validator getValidator() {
    return getParameterValidator();
}

@Bean
public EditableParameterValidator getParameterValidator() {
    return new EditableParameterValidator();
}

</pre>
</div>
<div class="info-box information">
<strong>HDIV Version 2.1.4</strong></p>
<p>This config changes with HDIV version 2.1.4-SNAPSHOT. The editableValidator is already registered as a bean named &#8220;hdivEditableValidator&#8221; so only adding the validation to the mvc tag is necessary. Also worth noting that the new version will check for a JSR-303 validation in the classpath and if it exists it will delegate successful validations to it (like a validation chain of 2). Only frustrating this is that there is no way at this time to specify order or priority so if you have a nice email field validation message but another field fails HDIV validation, then only the HDIV message is shown. For small apps I suggest using HDIV for all except field validation, instead use the hibernate validator and javax annotations. This adds risk as you will need to ensure all fields are handled properly but the tradeoff is more control over the user experience.
</p></div>
<p>Update the controller form post method to check validations. The second method is the HDIV redirect on error which adds a basic message to the model.</p>
<pre class="brush: java; title: IndexController.java; notranslate">
@RequestMapping(value = &quot;/create&quot;, method = RequestMethod.POST)
public String search(Model model, @Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) {

    if (result.hasErrors()) {
        return &quot;index&quot;;
    }
    
	// Process or save the form here
	
	return &quot;show&quot;;
}

...

@RequestMapping(value = &quot;/security-error&quot;, method = RequestMethod.GET)
public String securityError(RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute(&quot;page_error&quot;, &quot;You do have have permission to do that!&quot;);
    return &quot;redirect:/&quot;;
}

</pre>
<p>Here is the simple form. Notice there is no declaration for HDIV specifically in the form. This will be added dynamically so we don&#8217;t need to worry about it. </p>
<p>The first part will check for a page level error and display the text if necessary.</p>
<pre class="brush: xml; title: simple form; notranslate">
&lt;c:if test=&quot;${page_error != null }&quot;&gt;
       &lt;div class=&quot;alert alert-error&quot;&gt;
           &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;alert&quot;&gt;&amp;times;&lt;/button&gt;
           &lt;h4&gt;Error!&lt;/h4&gt;
               ${page_error}
       &lt;/div&gt;
&lt;/c:if&gt;

&lt;form:form method=&quot;post&quot; modelAttribute=&quot;signupForm&quot; action=&quot;create&quot; id=&quot;signupForm&quot; cssClass=&quot;form-horizontal&quot;
           autocomplete=&quot;off&quot;&gt;
    &lt;fieldset&gt;
        &lt;legend&gt;Enter Your Information&lt;/legend&gt;

        &lt;c:set var=&quot;emailErrors&quot;&gt;&lt;form:errors path=&quot;email&quot;/&gt;&lt;/c:set&gt;
        &lt;div class=&quot;control-group&lt;c:if test=&quot;${not empty emailErrors}&quot;&gt; error&lt;/c:if&gt;&quot;&gt;
            &lt;label class=&quot;control-label&quot; for=&quot;field-email&quot;&gt;Email&lt;/label&gt;

            &lt;div class=&quot;controls&quot;&gt;
                &lt;form:input path=&quot;email&quot; id=&quot;field-email&quot; tabindex=&quot;1&quot; maxlength=&quot;45&quot; placeholder=&quot;Email&quot;/&gt;
                &lt;form:errors path=&quot;email&quot; cssClass=&quot;help-inline&quot; element=&quot;span&quot;/&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;c:set var=&quot;firstNameErrors&quot;&gt;&lt;form:errors path=&quot;firstName&quot;/&gt;&lt;/c:set&gt;
        &lt;div class=&quot;control-group&lt;c:if test=&quot;${not empty firstNameErrors}&quot;&gt; error&lt;/c:if&gt;&quot;&gt;
            &lt;label class=&quot;control-label&quot; for=&quot;field-firstName&quot;&gt;First Name&lt;/label&gt;
            &lt;div class=&quot;controls&quot;&gt;
                &lt;form:input path=&quot;firstName&quot; id=&quot;field-firstName&quot; tabindex=&quot;2&quot; maxlength=&quot;35&quot; placeholder=&quot;First Name&quot;/&gt;
                &lt;form:errors path=&quot;firstName&quot; cssClass=&quot;help-inline&quot; element=&quot;span&quot;/&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;c:set var=&quot;lastNameErrors&quot;&gt;&lt;form:errors path=&quot;lastName&quot;/&gt;&lt;/c:set&gt;
        &lt;div class=&quot;control-group&lt;c:if test=&quot;${not empty lastNameErrors}&quot;&gt; error&lt;/c:if&gt;&quot;&gt;
            &lt;label class=&quot;control-label&quot; for=&quot;field-lastName&quot;&gt;Last Name&lt;/label&gt;
            &lt;div class=&quot;controls&quot;&gt;
                &lt;form:input path=&quot;lastName&quot; id=&quot;field-lastName&quot; tabindex=&quot;3&quot; maxlength=&quot;35&quot; placeholder=&quot;Last Name&quot;/&gt;
                &lt;form:errors path=&quot;lastName&quot; cssClass=&quot;help-inline&quot; element=&quot;span&quot;/&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;form-actions&quot;&gt;
            &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Sign up&lt;/button&gt;
            &lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;Cancel&lt;/button&gt;
        &lt;/div&gt;
    &lt;/fieldset&gt;
&lt;/form:form&gt;
</pre>
<p>When the app is run and the /create is accessed without the form you will get the following error message at the top of the page. This will also show up for any other HDIV non field error like form tampering or bad sessions. </p>
<p><a href="http://cdn.luckyryan.com/wp-content/uploads/2013/02/hdiv_security_error.png" rel="lightbox[96]"><img src="http://cdn.luckyryan.com/wp-content/uploads/2013/02/hdiv_security_error-1024x638.png" alt="hdiv_security_error" width="550" height="342" class="alignnone size-large wp-image-97" /></a></p>
<p>Try entering a script and it will return a field error</p>
<p><a href="http://cdn.luckyryan.com/wp-content/uploads/2013/02/hdiv_field_error.png" rel="lightbox[96]"><img src="http://cdn.luckyryan.com/wp-content/uploads/2013/02/hdiv_field_error-300x191.png" alt="hdiv_field_error" width="300" height="191" class="alignnone size-medium wp-image-98" /></a></p>
<p>The post <a href="http://www.luckyryan.com/2013/02/14/spring-mvc-form-validation-with-hdiv-http-data-integrity-validator/">Spring MVC form validation with HDIV (HTTP Data Integrity Validator)</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.luckyryan.com/2013/02/14/spring-mvc-form-validation-with-hdiv-http-data-integrity-validator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Migrate Spring MVC servlet.xml to Java Config</title>
		<link>http://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/</link>
		<comments>http://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/#comments</comments>
		<pubDate>Fri, 08 Feb 2013 07:12:16 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Java Config]]></category>

		<guid isPermaLink="false">http://luckyryan.com/?p=34</guid>
		<description><![CDATA[<p>Since Spring 3, Java configuration (@Configuration) has been moved into spring-core and has caught my attention. This is a quick sample of how to convert an existing servlet.xml file into a java config file. Beginning xml 1. Create the configuration<span class="ellipsis">&#8230;</span><div class="read-more"><a href="http://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/">Read more &#8250;</a></div><!-- end of .read-more --></p><p>The post <a href="http://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/">Migrate Spring MVC servlet.xml to Java Config</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Since Spring 3, Java configuration (@Configuration) has been moved into spring-core and has caught my attention. This is a quick sample of how to convert an existing servlet.xml file into a java config file.</p>
<p>Beginning xml</p>
<pre class="brush: xml; title: sample-servlet.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:mvc=&quot;http://www.springframework.org/schema/mvc&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd&quot;&gt;

    &lt;!-- Scan for spring annotated components --&gt;
    &lt;context:component-scan base-package=&quot;com.luckyryan.sample&quot;/&gt;

    &lt;!-- Process annotations on registered beans like @Autowired... --&gt;
    &lt;context:annotation-config/&gt;

    &lt;!-- This tag registers the DefaultAnnotationHandlerMapping and
         AnnotationMethodHandlerAdapter beans that are required for Spring MVC  --&gt;
    &lt;mvc:annotation-driven/&gt;

    &lt;!-- Exception Resolver that resolves exceptions through @ExceptionHandler methods --&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver&quot;/&gt;

    &lt;!-- View Resolver for JSPs --&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
        &lt;property name=&quot;prefix&quot; value=&quot;/WEB-INF/pages/&quot;/&gt;
        &lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot;/&gt;
    &lt;/bean&gt;

    &lt;!-- This tag allows for mapping the DispatcherServlet to &quot;/&quot; --&gt;
    &lt;mvc:default-servlet-handler/&gt;

    &lt;!-- resources exclusions from servlet mapping --&gt;
    &lt;mvc:resources mapping=&quot;/assets/**&quot; location=&quot;classpath:/META-INF/resources/webjars/&quot;/&gt;
    &lt;mvc:resources mapping=&quot;/css/**&quot; location=&quot;/css/&quot;/&gt;
    &lt;mvc:resources mapping=&quot;/img/**&quot; location=&quot;/img/&quot;/&gt;
    &lt;mvc:resources mapping=&quot;/js/**&quot; location=&quot;/js/&quot;/&gt;

&lt;/beans&gt;
</pre>
<p>1. Create the configuration class, I like to create a &#8220;config&#8221; package with a class named appConfig.java<br />
2. Add @Configuration, this will let spring know this contains bean definitions.</p>
<pre class="brush: java; highlight: [5]; title: appConfig.java; notranslate">
package com.luckyryan.sample.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class appConfig {

}
</pre>
<p>3. Add @EnableWebMVC, this is the same as &lt;mvc:annotation-driven/&gt;</p>
<pre class="brush: java; highlight: [1]; title: appConfig.java; notranslate">
@EnableWebMvc
@Configuration
public class appConfig {

}
</pre>
<p>4. Add @ComponentScan(basePackages = {&#8220;com.luckyryan.sample&#8221;}), this is the same as &lt;context:component-scan base-package=&#8221;com.luckyryan.sample&#8221;/&gt;</p>
<pre class="brush: java; highlight: [2]; title: appConfig.java; notranslate">
@EnableWebMvc
@ComponentScan(basePackages = {&quot;com.luckyryan.sample&quot;})
@Configuration
public class appConfig {

}
</pre>
<p>5. Extend the class to use WebMvcConfigurerAdapter. This adds stub implementations from the WebMvcConfigurer interface which is used by @EnableWebMVC. It also gives us a chance to override resources and the default handler.</p>
<pre class="brush: java; highlight: [4]; title: appConfig.java; notranslate">
@EnableWebMvc
@ComponentScan(basePackages = {&quot;com.luckyryan.sample&quot;})
@Configuration
public class appConfig extends WebMvcConfigurerAdapter {

}
</pre>
<p>6. Declare our static resources. I added cache to the java config but it&#8217;s not required.</p>
<pre class="brush: java; highlight: [6,7,8,9,10,11,12]; title: appConfig.java; notranslate">
@EnableWebMvc
@ComponentScan(basePackages = {&quot;com.luckyryan.sample&quot;})
@Configuration
public class appConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	registry.addResourceHandler(&quot;/assets/**&quot;).addResourceLocations(&quot;classpath:/META-INF/resources/webjars/&quot;).setCachePeriod(31556926);
    	registry.addResourceHandler(&quot;/css/**&quot;).addResourceLocations(&quot;/css/&quot;).setCachePeriod(31556926);
    	registry.addResourceHandler(&quot;/img/**&quot;).addResourceLocations(&quot;/img/&quot;).setCachePeriod(31556926);
    	registry.addResourceHandler(&quot;/js/**&quot;).addResourceLocations(&quot;/js/&quot;).setCachePeriod(31556926);
 	}

}
</pre>
<p>7. Set default servlet handler, this is the same as &lt;mvc:default-servlet-handler/&gt;</p>
<pre class="brush: java; highlight: [14,15,16,17]; title: appConfig.java; notranslate">
@EnableWebMvc
@ComponentScan(basePackages = {&quot;com.luckyryan.sample&quot;})
@Configuration
public class appConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(&quot;/assets/**&quot;).addResourceLocations(&quot;classpath:/META-INF/resources/webjars/&quot;).setCachePeriod(31556926);
        registry.addResourceHandler(&quot;/css/**&quot;).addResourceLocations(&quot;/css/&quot;).setCachePeriod(31556926);
        registry.addResourceHandler(&quot;/img/**&quot;).addResourceLocations(&quot;/img/&quot;).setCachePeriod(31556926);
        registry.addResourceHandler(&quot;/js/**&quot;).addResourceLocations(&quot;/js/&quot;).setCachePeriod(31556926);
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix(&quot;/WEB-INF/pages/&quot;);
        resolver.setSuffix(&quot;.jsp&quot;);
        return resolver;
    }
}

</pre>
<p>8. Add bean for InternalResourceViewResolver</p>
<pre class="brush: java; highlight: [30,31,32,33,34,35,36]; title: appConfig.java; notranslate">
package com.luckyryan.sample.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@EnableWebMvc
@ComponentScan(basePackages = {&quot;com.luckyryan.sample&quot;})
@Configuration
public class appConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(&quot;/assets/**&quot;).addResourceLocations(&quot;classpath:/META-INF/resources/webjars/&quot;).setCachePeriod(31556926);
        registry.addResourceHandler(&quot;/css/**&quot;).addResourceLocations(&quot;/css/&quot;).setCachePeriod(31556926);
        registry.addResourceHandler(&quot;/img/**&quot;).addResourceLocations(&quot;/img/&quot;).setCachePeriod(31556926);
        registry.addResourceHandler(&quot;/js/**&quot;).addResourceLocations(&quot;/js/&quot;).setCachePeriod(31556926);
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix(&quot;/WEB-INF/pages/&quot;);
        resolver.setSuffix(&quot;.jsp&quot;);
        return resolver;
    }
}

</pre>
<p>9. Update the servlet declaration in web.xml for the new config class and annotation conf. Note: this replaces the need for &lt;context:annotation-config/&gt; which was not featured in the servlet.xml example.</p>
<pre class="brush: xml; title: web.xml; notranslate">
...
...
&lt;servlet&gt;
    &lt;servlet-name&gt;sample&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;contextClass&lt;/param-name&gt;
        &lt;param-value&gt;
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        &lt;/param-value&gt;
    &lt;/init-param&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;
            com.luckyryan.sample.config.appConfig
        &lt;/param-value&gt;
    &lt;/init-param&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;sample&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;

</pre>
<p>The post <a href="http://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/">Migrate Spring MVC servlet.xml to Java Config</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Setup a simple Spring MVC site with Maven</title>
		<link>http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/</link>
		<comments>http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/#comments</comments>
		<pubDate>Wed, 06 Feb 2013 08:41:39 +0000</pubDate>
		<dc:creator>Ryan</dc:creator>
				<category><![CDATA[Maven]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Tech Stuff]]></category>

		<guid isPermaLink="false">http://www.luckyryan.com/?p=76</guid>
		<description><![CDATA[<p>There are already a lot of good tutorials on setting up MVC apps, and if you are starting a real project with Spring MVC I would suggest AppFuse. This guide is a basic setup which I use as a base<span class="ellipsis">&#8230;</span><div class="read-more"><a href="http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/">Read more &#8250;</a></div><!-- end of .read-more --></p><p>The post <a href="http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/">Setup a simple Spring MVC site with Maven</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></description>
				<content:encoded><![CDATA[<div class="info-box information">
There are already a lot of good tutorials on setting up MVC apps, and if you are starting a real project with Spring MVC I would suggest <a href="http://www.appfuse.org/display/APF/Home" title="AppFuse">AppFuse</a>. This guide is a basic setup which I use as a base example for other articles. It covers a few core concepts.
</div>
<h2>Maven</h2>
<h3>Project layout</h3>
<p>The first step is to create a basic <a href="http://maven.apache.org/" title="Apache Maven">Maven project</a>. If you are not using eclipse or IntelliJ which can generate the project for you then create the following structure.</p>
<pre>
SampleProject
->    src
-->       main
--->          java	
--->          resources
--->          webapp
-->       test
--->          java
--->          resources
-     pom.xml
</pre>
<ul>
<li><strong>src</strong> is the source to your project.</li>
<li><strong>pom.xml</strong> is the build and dependency file used by Maven. </li>
<li><strong>main &#038; test</strong> are source folders and should mirror in child folder structure. Main is your live code, Test is you junit, selenium, mocks or whatever you need to prove the app is stable. </li>
<li><strong>java</strong> contains the source java classes</li>
<li><strong>resource</strong>s will have property files, config files and other non java classes needed for your code</li>
<li><strong>webapp</strong> (only under main) is were the web files css, js, jsp, servlet.xml or web.xml, WEB-INF and all other web display assets.</li>
</ul>
<h3>Setup a basic pom</h3>
<p>Below is the <strong>pom</strong> for this sample application. Detailed information on the sections are available on the <a href="http://maven.apache.org/pom.html" title="Maven Pom">Maven site.</a> </p>
<pre class="brush: xml; title: pom.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;SampleMVC&lt;/groupId&gt;
    &lt;artifactId&gt;SampleMVC&lt;/artifactId&gt;
    &lt;version&gt;1.0&lt;/version&gt;
    &lt;packaging&gt;war&lt;/packaging&gt;

    &lt;properties&gt;
        &lt;!-- Build Properties --&gt;
        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;

        &lt;!-- Dependency Versions --&gt;
        &lt;spring.version&gt;3.2.1.RELEASE&lt;/spring.version&gt;
        &lt;jstl.version&gt;1.2&lt;/jstl.version&gt;
        &lt;servlet.version&gt;2.5&lt;/servlet.version&gt;
        &lt;bootstrap.version&gt;2.2.2&lt;/bootstrap.version&gt;
        &lt;jquery.version&gt;1.9.0&lt;/jquery.version&gt;
        &lt;sitemesh.version&gt;2.5-atlassian-5&lt;/sitemesh.version&gt;
        &lt;commons-lang.version&gt;2.6&lt;/commons-lang.version&gt;
    &lt;/properties&gt;

    &lt;build&gt;
    &lt;/build&gt;

    &lt;dependencies&gt;

        &lt;!-- Servlet &amp; JSTL --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
            &lt;artifactId&gt;jstl&lt;/artifactId&gt;
            &lt;version&gt;${jstl.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
            &lt;artifactId&gt;servlet-api&lt;/artifactId&gt;
            &lt;version&gt;${servlet.version}&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;!-- Display template &amp; layout --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;opensymphony&lt;/groupId&gt;
            &lt;artifactId&gt;sitemesh&lt;/artifactId&gt;
            &lt;version&gt;${sitemesh.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.webjars&lt;/groupId&gt;
            &lt;artifactId&gt;bootstrap&lt;/artifactId&gt;
            &lt;version&gt;${bootstrap.version}&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;!-- Spring --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-beans&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;!-- Apache lang utils --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;commons-lang&lt;/groupId&gt;
            &lt;artifactId&gt;commons-lang&lt;/artifactId&gt;
            &lt;version&gt;${commons-lang.version}&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;profiles&gt;
        &lt;profile&gt;
            &lt;id&gt;jetty&lt;/id&gt;
            &lt;activation&gt;
                &lt;activeByDefault&gt;true&lt;/activeByDefault&gt;
            &lt;/activation&gt;
            &lt;build&gt;
                &lt;plugins&gt;
                    &lt;plugin&gt;
                        &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt;
                        &lt;artifactId&gt;maven-jetty-plugin&lt;/artifactId&gt;
                        &lt;version&gt;6.1.26&lt;/version&gt;
                        &lt;configuration&gt;
                            &lt;useTestClasspath&gt;true&lt;/useTestClasspath&gt;
                            &lt;contextPath&gt;/app&lt;/contextPath&gt;
                            &lt;stopKey&gt;1&lt;/stopKey&gt;
                            &lt;stopPort&gt;9999&lt;/stopPort&gt;
                        &lt;/configuration&gt;
                        &lt;executions&gt;
                            &lt;execution&gt;
                                &lt;id&gt;start-jetty&lt;/id&gt;
                                &lt;phase&gt;pre-integration-test&lt;/phase&gt;
                                &lt;goals&gt;
                                    &lt;goal&gt;run&lt;/goal&gt;
                                &lt;/goals&gt;
                                &lt;configuration&gt;
                                    &lt;daemon&gt;true&lt;/daemon&gt;
                                &lt;/configuration&gt;
                            &lt;/execution&gt;
                            &lt;execution&gt;
                                &lt;id&gt;stop-jetty&lt;/id&gt;
                                &lt;phase&gt;post-integration-test&lt;/phase&gt;
                                &lt;goals&gt;
                                    &lt;goal&gt;stop&lt;/goal&gt;
                                &lt;/goals&gt;
                            &lt;/execution&gt;
                        &lt;/executions&gt;
                    &lt;/plugin&gt;
                &lt;/plugins&gt;
            &lt;/build&gt;
        &lt;/profile&gt;
    &lt;/profiles&gt;
&lt;/project&gt;
</pre>
<ul>
<li><strong>groupId, artifactId and version</strong> are used to identify the project for Maven.</li>
<li><strong>Properties</strong> allows you to define values that can be used in the pom, works great to reduce repeating versions with syntax <strong>${value}</strong>. You can also use the resource settings to populate property files (spring, application.properties&#8230;).
</li>
<li><strong>Build</strong> we don&#8217;t use here but it&#8217;s the place for plugins, build tasks and anything you need to get the app packaged just the way you want. In this case we just run jetty so nothing special is needed.
</li>
<li><strong>Dependencies</strong> are all the dependent java classes needed to run the app. There are different scopes allowed that tell Maven when to load them. Typically <strong>compile</strong> (the default) is fine, the next most common I use is <strong>test</strong>. Maven will load the dependency only for testing and exclude it from the deployment package. Another thing to note is <a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Transitive_Dependencies" title="Maven Transitive Dependencies" target="_blank">transitive dependencies</a>. Maven 2.0 will automatically pull in dependencies of the declared project dependencies to save you from having to find them all on you own. Maven is fairly good about resolving conflicts in versions but it may be necessary to &#8220;exclude&#8221; certain artifacts from declared dependencies. If that gets messy then checkout the <a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management" title="Maven Dependency Management" target="_blank">dependency management</a> which can set default versions and override transitive dependencies. It also useful in parent poms or multi-module structures (later topic).
<ul>Dependency overview for this project</p>
<li><strong>jstl &#038; servlet-api</strong> &#8211; These are used for the servlet and jsp pages. This is not specific to MVC but required for a webapp.</li>
<li><strong>sitemesh</strong> &#8211; Template engine for the site UI.  </li>
<li><strong>bootstrap</strong> &#8211; Twitter bootstrap that also includes jQuery. Both help to make quick layouts. This is provided by <a href="http://www.webjars.org" title="WebJars">WebJars</a>, which allows us to treat the boilerplate layout code as a jar dependency and keeps the webapp clean. There are a lot of other packages available for extending the UI. </li>
<li><strong>spring-core</strong> &#8211; name says it all. </li>
<li><strong>spring-beans</strong> &#8211; bean definitions.</li>
<li><strong>spring-context</strong> &#8211; bean registration (component scan, annotation config&#8230;)</li>
<li><strong>spring-web</strong> &#8211; base web properties, RequestMapping&#8230;</li>
<li><strong>spring-webmvc</strong> &#8211; MVC components, Controllers, DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter </li>
<li><strong>commons-lang</strong> &#8211; Using this for StringUtils</li>
</ul>
</li>
<li><strong>Profile</strong> is the last part for this file. Profiles can be enabled by default (as seen here) or loaded via the <strong>-P</strong> flag when invoking maven. This is great when using build servers where environment specific packages or special testing should to be turned on or off. However this is does affect the packaged artifact at build time. If you need runtime profiles then the <a href="http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/core/env/Environment.html" title="Spring Environment" target="_blank">Spring Environment</a> addition in version 3.1 can help. The profile defined here is for running Jetty so we can quickly test the app locally.</li>
</ul>
<h2>Servlet and Web files</h2>
<h3>web.xml</h3>
<p>Create <strong>web.xml</strong> and parent folders in src/main/webapp/WEB-INF/web.xml</p>
<pre class="brush: xml; title: web.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;2.5&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt;

    &lt;display-name&gt;Sample App&lt;/display-name&gt;

    &lt;context-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;
            &lt;!--classpath resource of spring configs or other required configs go here --&gt;
        &lt;/param-value&gt;
    &lt;/context-param&gt;

    &lt;filter&gt;
        &lt;filter-name&gt;sitemesh&lt;/filter-name&gt;
        &lt;filter-class&gt;com.opensymphony.sitemesh.webapp.SiteMeshFilter&lt;/filter-class&gt;
    &lt;/filter&gt;

    &lt;!-- Filter Mappings --&gt;
    &lt;filter-mapping&gt;
        &lt;filter-name&gt;sitemesh&lt;/filter-name&gt;
        &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
        &lt;dispatcher&gt;FORWARD&lt;/dispatcher&gt;
        &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt;
    &lt;/filter-mapping&gt;

    &lt;!-- Default Page Support --&gt;
    &lt;welcome-file-list&gt;
        &lt;welcome-file&gt;index&lt;/welcome-file&gt;
    &lt;/welcome-file-list&gt;

    &lt;listener&gt;
        &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
    &lt;/listener&gt;

    &lt;!-- MVC Servlet - see sample-servlet.xml for specific config --&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;sample&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;      
    &lt;/servlet&gt;

    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;sample&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
&lt;/web-app&gt;
</pre>
<p>The web.xml file instructs the servlet container (in our case it&#8217;s jetty) how to start up and what to load. This is for servlet 2.5, in servlet 3.0 this file is not necessary and annotations can be used (later topic).</p>
<ul>
<li><strong>context-param</strong> &#8211; defines resources that are used by the servlet. Typically an applicationContext.xml for Spring would be listed here and used by the ContextLoaderListener</li>
<li><strong>filter</strong> &#8211; filters make up a filter chain so order is important. In this case we are only using one. Each filter will have a definition and a corresponding mapping (defined by same name) that tells the servlet when to apply it. This filter is used by sitemesh to build out web template. </li>
<li><strong>listener</strong> &#8211; invoked when the application starts. This listener will look for a spring config and initialize the ApplicationContext. By convention it will look for <strong>sample-servlet.xml</strong> in the classpath where &#8220;<strong>sample</strong>&#8221; is the servlet name. You can also specify one or more in the contextConfigLocation section.</li>
<li><strong>servlet</strong> &#8211; Spring web magic. This defines a servlet that will process all requests through Spring MVC.
</li>
<li><strong>servlet-mapping</strong> &#8211; defines the url pattern that this servlet listen on. I chose to make it root and use Spring MVC resource definitions (in sample-servlet.xml) to exclude non Spring MVC components like CSS, JS &#038; images</li>
<p>. </ul>
<h3>sample-servlet.xml</h3>
<p>Create the <strong>sample-servlet.xml</strong> in the same location as <strong>web.xml</strong>.</p>
<pre class="brush: xml; title: sample-servlet.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:mvc=&quot;http://www.springframework.org/schema/mvc&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd&quot;&gt;

    &lt;!-- Scan for spring annotated components --&gt;
    &lt;context:component-scan base-package=&quot;com.luckyryan.sample&quot;/&gt;

    &lt;!-- Process annotations on registered beans like @Autowired... --&gt;
    &lt;context:annotation-config/&gt;

    &lt;!-- This tag registers the DefaultAnnotationHandlerMapping and
         AnnotationMethodHandlerAdapter beans that are required for Spring MVC  --&gt;
    &lt;mvc:annotation-driven/&gt;

    &lt;!-- Exception Resolver that resolves exceptions through @ExceptionHandler methods --&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver&quot;/&gt;

    &lt;!-- View Resolver for JSPs --&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
        &lt;property name=&quot;prefix&quot; value=&quot;/WEB-INF/pages/&quot;/&gt;
        &lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot;/&gt;
    &lt;/bean&gt;

    &lt;!-- This tag allows for mapping the DispatcherServlet to &quot;/&quot; --&gt;
    &lt;mvc:default-servlet-handler/&gt;

    &lt;!-- resources exclusions from servlet mapping --&gt;
    &lt;mvc:resources mapping=&quot;/assets/**&quot; location=&quot;classpath:/META-INF/resources/webjars/&quot;/&gt;
    &lt;mvc:resources mapping=&quot;/css/**&quot; location=&quot;/css/&quot;/&gt;
    &lt;mvc:resources mapping=&quot;/img/**&quot; location=&quot;/img/&quot;/&gt;
    &lt;mvc:resources mapping=&quot;/js/**&quot; location=&quot;/js/&quot;/&gt;

&lt;/beans&gt;
</pre>
<h3>Sitemesh</h3>
<p>Create the required <strong>sitemesh</strong> files. This defines our decorators &#038; parsers. See <a href="http://wiki.sitemesh.org/display/sitemesh/Home" title="sitemesh">sitemesh</a> for more info. </p>
<pre class="brush: xml; title: sitemesh.xml; notranslate">
&lt;sitemesh&gt;
    &lt;property name=&quot;decorators-file&quot; value=&quot;/WEB-INF/decorators.xml&quot;/&gt;
    &lt;excludes file=&quot;${decorators-file}&quot;/&gt;
    &lt;page-parsers&gt;
        &lt;parser default=&quot;true&quot; class=&quot;com.opensymphony.module.sitemesh.parser.HTMLPageParser&quot;/&gt;
        &lt;parser content-type=&quot;text/html&quot; class=&quot;com.opensymphony.module.sitemesh.parser.HTMLPageParser&quot;/&gt;
        &lt;parser content-type=&quot;text/html;charset=ISO-8859-1&quot; class=&quot;com.opensymphony.module.sitemesh.parser.HTMLPageParser&quot;/&gt;
    &lt;/page-parsers&gt;

    &lt;decorator-mappers&gt;
        &lt;mapper class=&quot;com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper&quot;&gt;
            &lt;param name=&quot;config&quot; value=&quot;${decorators-file}&quot;/&gt;
        &lt;/mapper&gt;
    &lt;/decorator-mappers&gt;
&lt;/sitemesh&gt;
</pre>
<pre class="brush: xml; title: decorators.xml; notranslate">
&lt;decorators defaultdir=&quot;/decorators&quot;&gt;
    &lt;excludes&gt;
        &lt;pattern&gt;/resources/*&lt;/pattern&gt;
    &lt;/excludes&gt;
    &lt;decorator name=&quot;default&quot; page=&quot;default.jsp&quot;&gt;
        &lt;pattern&gt;/*&lt;/pattern&gt;
    &lt;/decorator&gt;
&lt;/decorators&gt;
</pre>
<p>Create the decorators folder and <strong>default.jsp</strong>. (src/main/webapp/decorators/default.jsp). &lt;decorator-title/&gt; &#038;  &lt;decorator-body/&gt; will pull in the respective sections of the child page.</p>
<pre class="brush: xml; title: default.jsp; notranslate">
&lt;%@ page language=&quot;java&quot; pageEncoding=&quot;UTF-8&quot; contentType=&quot;text/html;charset=utf-8&quot; %&gt;
&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot; %&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt; %@ taglib prefix=&quot;decorator&quot; uri=&quot;http://www.opensymphony.com/sitemesh/decorator&quot; %&gt;

    &lt;meta charset=&quot;utf-8&quot;/&gt;

    &lt;title&gt;&lt;decorator:title&gt;&lt;/decorator:title&gt;&lt;/title&gt;

    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot;
          href=&quot;${pageContext.request.contextPath}/assets/bootstrap/2.2.2/css/bootstrap.min.css&quot; media=&quot;all&quot;/&gt;

    &lt;!-- HTML5 shim, for IE6-8 support of HTML5 elements --&gt;
    &lt;!--[if lt IE 9]&gt;
    &lt;script src=&quot;https://html5shim.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt;
    &lt; ![endif]--&gt;

    &lt;decorator:head&gt;&lt;/decorator:head&gt;

    &lt;style&gt;
        body {
            padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div class=&quot;navbar navbar-inverse navbar-fixed-top&quot;&gt;
    &lt;div class=&quot;navbar-inner&quot;&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;a class=&quot;btn btn-navbar&quot; data-toggle=&quot;collapse&quot; data-target=&quot;.nav-collapse&quot;&gt;
                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;
                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;
                &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;
            &lt;/a&gt;
            &lt;a class=&quot;brand&quot; href=&quot;#&quot;&gt;Sample App&lt;/a&gt;

            &lt;div class=&quot;nav-collapse collapse&quot;&gt;
                &lt;ul class=&quot;nav&quot;&gt;
                    &lt;li class=&quot;active&quot;&gt;&lt;a href=&quot;${pageContext.request.contextPath}/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
                &lt;/ul&gt;
            &lt;/div&gt;
            &lt;!--/.nav-collapse --&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;div class=&quot;container&quot;&gt;

    &lt;c:if test=&quot;${page_error != null }&quot;&gt;
        &lt;div class=&quot;alert alert-error&quot;&gt;
            &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;alert&quot;&gt;&amp;times;&lt;/button&gt;
            &lt;h4&gt;Error!&lt;/h4&gt;
                ${page_error}
        &lt;/div&gt;
    &lt;/c:if&gt;

    &lt;decorator:body&gt;&lt;/decorator:body&gt;

    &lt;footer&gt;

    &lt;/footer&gt;
&lt;/div&gt;


&lt;script type=&quot;text/javascript&quot;
        src=&quot;${pageContext.request.contextPath}/assets/jquery/1.8.2/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;
        src=&quot;${pageContext.request.contextPath}/assets/bootstrap/2.2.2/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>JSP Pages</h3>
<p>Create an <strong>index.jsp</strong> and <strong>show.jsp</strong> in src/main/webapp/WEB-INF/pages/*.</p>
<pre class="brush: xml; title: index.jsp; notranslate">
&lt; %@ page language=&quot;java&quot; pageEncoding=&quot;UTF-8&quot; contentType=&quot;text/html;charset=utf-8&quot; %&gt;
&lt; %@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot; %&gt;
&lt; %@ taglib prefix=&quot;form&quot; uri=&quot;http://www.springframework.org/tags/form&quot; %&gt;
&lt; %@ taglib prefix=&quot;spring&quot; uri=&quot;http://www.springframework.org/tags&quot; %&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Sample App Sign-up Page&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;Sign Up Here!&lt;/h1&gt;

&lt;form:form method=&quot;post&quot; modelAttribute=&quot;signupForm&quot; action=&quot;create&quot; id=&quot;signupForm&quot; cssClass=&quot;form-horizontal&quot;
           autocomplete=&quot;off&quot;&gt;
    &lt;fieldset&gt;
        &lt;legend&gt;Enter Your Information&lt;/legend&gt;

        &lt;c:set var=&quot;emailErrors&quot;&gt;&lt;form:errors path=&quot;email&quot;&gt;&lt;/form:errors&gt;&lt;/c:set&gt;
        &lt;div class=&quot;control-group&lt;c:if test=&quot;${not empty emailErrors}&quot;&gt; error&quot;&gt;
            &lt;label class=&quot;control-label&quot; for=&quot;field-email&quot;&gt;Email&lt;/label&gt;

            &lt;div class=&quot;controls&quot;&gt;
                &lt;form:input path=&quot;email&quot; id=&quot;field-email&quot; tabindex=&quot;1&quot; maxlength=&quot;45&quot; placeholder=&quot;Email&quot;&gt;&lt;/form:input&gt;
                &lt;form:errors path=&quot;email&quot; cssClass=&quot;help-inline&quot; element=&quot;span&quot;&gt;&lt;/form:errors&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;c:set var=&quot;firstNameErrors&quot;&gt;&lt;form:errors path=&quot;firstName&quot;&gt;&lt;/form:errors&gt;&lt;/c:set&gt;
        &lt;div class=&quot;control-group&lt;c:if test=&quot;${not empty firstNameErrors}&quot;&gt; error&quot;&gt;
            &lt;label class=&quot;control-label&quot; for=&quot;field-firstName&quot;&gt;First Name&lt;/label&gt;
            &lt;div class=&quot;controls&quot;&gt;
                &lt;form:input path=&quot;firstName&quot; id=&quot;field-firstName&quot; tabindex=&quot;2&quot; maxlength=&quot;35&quot; placeholder=&quot;First Name&quot;&gt;&lt;/form:input&gt;
                &lt;form:errors path=&quot;firstName&quot; cssClass=&quot;help-inline&quot; element=&quot;span&quot;&gt;&lt;/form:errors&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;c:set var=&quot;lastNameErrors&quot;&gt;&lt;form:errors path=&quot;lastName&quot;&gt;&lt;/form:errors&gt;&lt;/c:set&gt;
        &lt;div class=&quot;control-group&lt;c:if test=&quot;${not empty lastNameErrors}&quot;&gt; error&quot;&gt;
            &lt;label class=&quot;control-label&quot; for=&quot;field-lastName&quot;&gt;Last Name&lt;/label&gt;
            &lt;div class=&quot;controls&quot;&gt;
                &lt;form:input path=&quot;lastName&quot; id=&quot;field-lastName&quot; tabindex=&quot;3&quot; maxlength=&quot;35&quot; placeholder=&quot;Last Name&quot;&gt;&lt;/form:input&gt;
                &lt;form:errors path=&quot;lastName&quot; cssClass=&quot;help-inline&quot; element=&quot;span&quot;&gt;&lt;/form:errors&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;form-actions&quot;&gt;
            &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Sign up&lt;/button&gt;
            &lt;button type=&quot;button&quot; class=&quot;btn&quot;&gt;Cancel&lt;/button&gt;
        &lt;/div&gt;
    &lt;/fieldset&gt;
&lt;/form:form&gt;


&lt;/body&gt;
&lt;/html&gt;
</pre>
<pre class="brush: xml; title: show.jsp; notranslate">
&lt; %@ page language=&quot;java&quot; pageEncoding=&quot;UTF-8&quot; contentType=&quot;text/html;charset=utf-8&quot; %&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Sample App Sign-up Page&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;Sign Up Complete!&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Spring MVC</h2>
<h3>Controllers</h3>
<p>Now we have an app with pages but nothing to actually handle the request and map to a page. </p>
<p>The next step is to create a Controller and register it with Spring.</p>
<p>Create <strong>IndexController.java</strong> in src/main/java/com/luckyryan/sample/webapp/controller/IndexController.java. NOTE: this is <strong>NOT</strong> the same webapp folder used with the jsp files, this is under the package structure of java.</p>
<pre class="brush: java; title: IndexController.java; notranslate">
package com.luckyryan.sample.webapp.controller;

import com.luckyryan.sample.model.SignupForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class IndexController {

    @RequestMapping(value = &quot;/&quot;, method = RequestMethod.GET)
    public ModelAndView index() {
        return new ModelAndView(&quot;index&quot;, &quot;signupForm&quot;, new SignupForm());
    }

    @RequestMapping(value = &quot;/create&quot;, method = RequestMethod.POST)
    public String create(Model model, SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) {

        if (result.hasErrors()) {
            return &quot;index&quot;;
        }

        return &quot;show&quot;;
    
    }

    @RequestMapping(value = &quot;/security-error&quot;, method = RequestMethod.GET)
    public String securityError(RedirectAttributes redirectAttributes) {
        redirectAttributes.addFlashAttribute(&quot;page_error&quot;, &quot;You do have have permission to do that!&quot;);
        return &quot;redirect:/&quot;;
    }

}
</pre>
<p>The @Controller annotation indicates that this class is a MVC controller. Spring will use the request mappings to figure out what url will hit which controller and method. Since we only have one controller using a mapping of &#8220;/&#8221; will capture root requests. If we had multiple controllers then RequestMapping could be defined for the entire class e.g. &#8220;registration&#8221; or &#8220;account&#8221; and any method on that controller would inherit the path. For this case I expect http://localhost:8080/sample/ would invoke IndexController.index(). In the example of &#8220;registration&#8221; then I would expect http://localhost:8080/sample/registration/ would invoke index.</p>
<p>Each method can return either a ModelAndView or just a string. The return value will use the ViewResolver to locate the proper jsp page to load. In our case we had</p>
<pre class="brush: xml; title: sample-servlet.xml; notranslate">
&lt;!-- View Resolver for JSPs --&gt;
&lt;bean class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
    &lt;property name=&quot;prefix&quot; value=&quot;/WEB-INF/pages/&quot;/&gt;
    &lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot;/&gt;
&lt;/bean&gt;
</pre>
<p>This means that a method return of &#8220;index&#8221; would resolve to /WEB-INF/pages/index.jsp. In the case of jsp, json and other views, View resolvers can be chained and ordered until a desired view is found. Acceptable return values are set by the ViewResolver. For this method we only want to show a blank for, to do that we instantiate a new SignupForm object (to be created next) and assign it to &#8220;signupForm&#8221; in the model. This allows use to access that object in the jsp via jstl or spring tags. Spring tags make it easy and do the work for you.</p>
<p>The create method only returns a string. Since model is available as a parameter we can directly access or set necessary values. The method signatures for controller request method can vary greatly based on what you need, just pay attention to order as some parameters do better when left as the last one.</p>
<p>There is a lot of opportunity for configuration here. <a href="http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html" title="Spring MVC Doc page">Spring has excellent documentation</a> when wanting to go beyond the basic.</p>
<h3>Form Model</h3>
<p>Create the <strong>SignupForm.java</strong> class src/main/java/com/luckyryan/sample/model/SignupForm.java</p>
<pre class="brush: java; title: SignupForm.java; notranslate">
package com.luckyryan.sample.model;

public class SignupForm {

    private String firstName;
    private String lastName;
    private String email;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
</pre>
<p>Spring can bind models to the request automatically so we don&#8217;t need to mess with parameter mapping. Enhancements such as validation are also possible and make life easy.</p>
<p>Now we can start up the servlet container and app from Maven with the following command: <strong>mvn clean jetty:run</strong></p>
<p>The app should start up and be accessible at http://localhost:8080/sample/</p>
<p>The simple form will display, enter any values and we get the confirmation page. </p>
<p><a href="http://cdn.luckyryan.com/wp-content/uploads/2013/02/signup_page.png" rel="lightbox[76]"><img src="http://cdn.luckyryan.com/wp-content/uploads/2013/02/signup_page-300x153.png" alt="signup_page" width="300" height="153" class="alignnone size-medium wp-image-84" border="1" /></a></p>
<p><a href="http://cdn.luckyryan.com/wp-content/uploads/2013/02/signup_complete.png" rel="lightbox[76]"><img src="http://cdn.luckyryan.com/wp-content/uploads/2013/02/signup_complete-300x140.png" alt="signup_complete" width="300" height="140" class="alignnone size-medium wp-image-83" border="1" /></a></p>
<p>This covers the basics of the app. Other topics will cover where to go from here and handle common tasks when building apps. </p>
<p>The post <a href="http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/">Setup a simple Spring MVC site with Maven</a> appeared first on <a href="http://www.luckyryan.com">Lucky Ryan</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.luckyryan.com/2013/02/06/setup-a-simple-spring-mvc-site-with-maven/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using apc
Database Caching 27/47 queries in 0.007 seconds using apc
Object Caching 3735/3758 objects using apc
Content Delivery Network via Amazon Web Services: CloudFront: cdn.luckyryan.com
Application Monitoring using New Relic

 Served from: www.luckyryan.com @ 2013-06-19 12:07:23 by W3 Total Cache -->