Thursday, July 25, 2013

ASP MVC and Spring.Net basic example

1. First step, launch Manage NuGet Packages

2. Search for Spring and install the features presented below



3. Now all references you need are added to your project for using Spring.Net, but I prefer to do something more and add Spring.CodeConfig



4. By using Spring.CodeConfig, we have the chance to change xml configurations with .Net code configurations


4.1.Create a HelloService interface

    public interface HelloService
    {
        string sayHello(string name);
    }

4.2. The implementation of HelloService

    public class HelloServiceImpl:HelloService
    {
        public string sayHello(string name)
        {
            return "Hello " + name;
        }
    }

4.3. The last step...create the application context and inject the service in you controller


**Create the configuration for Service injection
    [Configuration]
    public class ServiceInjectorConfiguration
    {
        [Definition]
        public virtual HelloService GetHelloService()
        {
            return new HelloServiceImpl();
        }
    }

**Update Global.aspx

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));

            var appContext = new CodeConfigApplicationContext();

            appContext.ScanAllAssemblies();
            appContext.Refresh();

            Application["appContext"] = appContext;
        }
    }

**Use your HelloService in controller
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        private HelloService service;
        private GenericApplicationContext appContext;

        public ActionResult Index()
        {
            appContext = (CodeConfigApplicationContext)HttpContext.Application["appContext"];

            service = (HelloService)appContext.GetObject("GetHelloService");

            ViewBag.HelloMessage = service.sayHello("Alex");
            return View();
        }

    }

ASP.NET MVC, .Net, MVC, HTML helpers, Spring.net, Spring, services, ViewBag, applicationContext, dependency injection, spring code config

Tuesday, July 23, 2013

Wicket+Spring Basic Example

Welcome to my first post on this blog!
The purpose of  my first tutorial will be to present a basic example of how to use some of the most popular Java frameworks, at the same time: Spring & Wicket. So we start step by step...

1. We need to create a Maven-webapp



2. Update Maven dependencies

Open your pom.xml file and update your dependencies section as below:



    
      junit
      junit
      3.8.1
      test
    
    
     org.apache.wicket
     wicket
     6.9.1
     pom
    
    
     javax.servlet
     javax.servlet-api
     3.1.0
    
    
     org.springframework
     spring-context
     3.2.3.RELEASE
    
    
     org.springframework
     spring-web
     3.2.3.RELEASE
    
    
     org.apache.wicket
     wicket-spring
     6.9.1
    
    
     org.apache.wicket
     wicket-request
     6.9.1
    
    
     org.slf4j
     slf4j-log4j12
     1.7.5
    
  
    


3. Now take a look on the project structure to make things a little bit clear


4. Last thing about configuration is the spring application context file and then everything will be great and we'll start talking about code, but we have to agree that in this case the configuration is a very important part of our project and we need to do it very carefully


WEB-INF/applicationContext.xml file should be something like this

 
 
 


5. Now it's code time...

First, please update the main web application file and override the init method from org.apache.wicket.protocol.http.WebApplication class and then  the web.xml file:
public class WicketApp extends WebApplication{

 @Override
 public Class getHomePage() {
  // TODO Auto-generated method stub
  return Index.class;
 }

 @Override
 protected void init()
 {
  super.init();
  //getDebugSettings().setDevelopmentUtilitiesEnabled(true);
  getComponentInstantiationListeners().add(new SpringComponentInjector(this));
 }
}

File: web.xml

 Wicket Web Application
 
 
  wicket.wicketTest
  org.apache.wicket.protocol.http.WicketFilter
  
   applicationClassName
   com.wicket.tutorials.blogspot.WicketApp
  
 
 
 
  wicket.wicketTest
  /*
 
 
  
  
           org.springframework.web.context.ContextLoaderListener
        
 

Next I will create a very simple service example, with only one method which will return a Hello entity

**Service interface
public interface HelloService {

 Hello getHelloMessage(String name); 
}

**Service implementation
@Service
public class HelloServiceImpl implements HelloService {

 public Hello getHelloMessage(String name) {
  // TODO Auto-generated method stub
  
  return new Hello(name);
 }

}


Notes
*You can also create other components writing your own beans in applicationContext.xml file, or using annotations like @Repository or @Component and inject them in the same way, with @SpringBean

We are so close to finish this long example and for this we need only web pages and everything will be done. I will not start to explain to much the wicket code, how can we add page parameters or how can we add events on input for example, but Index page is an example of how to use this wicket features

File: Index.html
<html>
<head>
 
</head>
<body>
</body> </html>

File: Index.java
public class Index extends WebPage{
 
 public Index()
 {
  this(new PageParameters());
 }
 
 public Index(PageParameters parameters)
 {
  final PageParameters helloPage_Parameters=new PageParameters();
  helloPage_Parameters.add("message", "");
  
  add(new Label("PageTitle", "Index Page"));
  
        Form form = new Form("form");
        add(form);

        final TextField field = new TextField("person", new Model(""));
        form.add(field);
  
        
        OnChangeAjaxBehavior onChangeAjaxBehavior = new OnChangeAjaxBehavior()
        {
            @Override
            protected void onUpdate(AjaxRequestTarget target)
            {
                helloPage_Parameters.set("message", field.getValue());
            }
        };
        field.add(onChangeAjaxBehavior);
        
  Link link=new Link("action-link") {

   @Override
   public void onClick() {
      
       setResponsePage(new HelloPage(helloPage_Parameters));
    
   }
  };
  
  link.add(new Label("message","Say Hello"));
  
  add(link);
 }
}

File: HelloPage.html
<html>
<head>
 
</head>
<bodyl>

</body>
</html>



File: HelloPage.java


public class HelloPage extends WebPage{

 @SpringBean
 private HelloService helloService;
 
 public HelloPage()
 {
  
 }
 
 public HelloPage(PageParameters pageParameters)
 {
  add(new Label("PageTitle", "Hello Page"));
  
  Hello hello=helloService.getHelloMessage(pageParameters.get("message").toString());
  
  add(new Label("hello-message",hello.toString()));
 }
}


And here we have a great example of using dependency injection with Wicket and Spring. We can refer every bean we created,  using just @SpringBean annotation




Have a nice day with Java Frameworks!