How to create dynamic UI with database config

Hi all here is a small post how to make your user interface(html) dynamically. In the sense just change your database and your user interface changes. the technologies used here are Spring3.x, hibernate3.x and Freemarker
and the specialty here is there is not even a single xml configuration involved.

below are the classes for the spring configuration.

/**
 * 
 */
package com.spark.spring.config;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
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;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

/**
 * @author PavanKumar Mantha
 *
 */
@Configuration
@EnableTransactionManagement
@EnableWebMvc
@Import({})
@ComponentScan(basePackages="com.spark.spring")
public class WebApplicationConfig extends WebMvcConfigurerAdapter{

	@Bean
	public FreeMarkerViewResolver getFreeMarkerViewResolver(){
		FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
		freeMarkerViewResolver.setPrefix("");
		freeMarkerViewResolver.setSuffix(".ftl");
		
		return freeMarkerViewResolver;
	}
	
	@Bean
	public FreeMarkerConfigurer getFreeMarkerConfigurer(){
		FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
		freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/ftl/");
		return freeMarkerConfigurer;
	}
	
	/*@Bean
	public InternalResourceViewResolver getInternalResourceViewResolver(){
	
		InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
		internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
		internalResourceViewResolver.setSuffix(".jsp");
		
		return internalResourceViewResolver;
	}*/
	
	@Bean
	public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer(){
		
		PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
		placeholderConfigurer.setLocation(new ClassPathResource("application.properties"));
		placeholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
		return placeholderConfigurer;
	}
	
	public void addResourceHandler(ResourceHandlerRegistry resourceHandlerRegistry){
		resourceHandlerRegistry.addResourceHandler("/resources/**").addResourceLocations("/resources");
	}
}

/**
 * 
 */
package com.spark.spring.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author PavanKumar Mantha
 *
 */
public class WebAppInitializer implements WebApplicationInitializer{

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
		annotationConfigWebApplicationContext.register(WebApplicationConfig.class);
		annotationConfigWebApplicationContext.setServletContext(servletContext);
		
		Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(annotationConfigWebApplicationContext));
		dynamic.addMapping("/");
		dynamic.setLoadOnStartup(1);
	}

}

/**
 * 
 */
package com.spark.spring.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

/**
 * @author PavanKumar Mantha
 * 
 */
@Configuration
public class HibernateConfiguration {

	@Value("${database.driver}")
	private String driverClassName;
	@Value("${database.url}")
	private String url;
	@Value("${database.user}")
	private String username;
	@Value("${database.password}")
	private String password;

	@Value("${hibernate.dialect}")
	private String hibernateDialect;
	@Value("${hibernate.show_sql}")
	private String hibernateShowSql;
	@Value("${hibernate.hbm2ddl.auto}")
	private String hibernateHbm2ddlAuto;

	@Bean
	public DataSource getDataSource() {

		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);

		return dataSource;
	}

	@Bean
	public AnnotationSessionFactoryBean getAnnotationSessionFactoryBean() {
		AnnotationSessionFactoryBean annotationSessionFactoryBean = new AnnotationSessionFactoryBean();
		annotationSessionFactoryBean.setDataSource(getDataSource());
		annotationSessionFactoryBean
				.setHibernateProperties(getHibernateProperties());
		annotationSessionFactoryBean
				.setPackagesToScan(new String[] { "com.spark.spring" });
		return annotationSessionFactoryBean;
	}

	@Bean
	@Autowired
	public HibernateTransactionManager transactionManager(
			SessionFactory sessionFactory) {
		HibernateTransactionManager htm = new HibernateTransactionManager();
		htm.setSessionFactory(sessionFactory);
		return htm;
	}

	@Bean
	@Autowired
	public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory) {
		HibernateTemplate hibernateTemplate = new HibernateTemplate(
				sessionFactory);
		return hibernateTemplate;
	}

	@Bean
	public Properties getHibernateProperties() {
		Properties properties = new Properties();
		properties.put("hibernate.dialect", hibernateDialect);
		properties.put("hibernate.show_sql", hibernateShowSql);
		properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);

		return properties;
	}

}

Below is the controller that handles the request and deligate the data to freemarker template

/**
 * 
 */
package com.spark.spring.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.spark.spring.bo.FormFieldsBo;
import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
@Controller
@RequestMapping("/controller")
public class UIRenderingController {

	@Autowired
	FormFieldsBo formFieldsBo;

	@RequestMapping(value = "/renderUi", method = RequestMethod.GET)
	public ModelAndView getTestHit() {
		System.out
				.println("-------------------inside the test hit method-----------------");

		List<FormFieldsModel> formFieldsModels = formFieldsBo.getFormFields("login_form");
		ModelAndView modelAndView = new ModelAndView("login", "formFieldsModels", formFieldsModels);
		return modelAndView;
	}
}

below are the service(BO) object and DataAccess Layer(DAO)

Please note that the below code as both interface and its implementation.

/**
 * 
 */
package com.spark.spring.bo;

import java.util.List;

import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
public interface FormFieldsBo {

	public List<FormFieldsModel> getFormFields(String formId);
}


/**
 * 
 */
package com.spark.spring.bo.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spark.spring.bo.FormFieldsBo;
import com.spark.spring.dao.FormFieldsDao;
import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
@Service(value="formFieldsBo")
public class FormFieldsBoImpl implements FormFieldsBo{

	@Autowired
	FormFieldsDao formFieldsDao;
	
	@Override
	@Transactional
	public List<FormFieldsModel> getFormFields(String formId) {
		System.out.println("---------------------- inside the BoImpl ----------------------");
		return formFieldsDao.getFormFields(formId);
	}

	
}

/**
 * 
 */
package com.spark.spring.dao;

import java.util.List;

import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
public interface FormFieldsDao {

	public List<FormFieldsModel> getFormFields(String formId);
}

/**
 * 
 */
package com.spark.spring.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.spark.spring.dao.FormFieldsDao;
import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
@Repository(value="formFieldsDao")
public class FormFieldsDaoImpl implements FormFieldsDao{

	@Autowired
	HibernateTemplate hibernateTemplate;
	
	@Override
	public List<FormFieldsModel> getFormFields(String formId) {

		Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery("from FormFieldsModel f where f.formId = :formId ");
		query.setParameter("formId", formId);
		List<FormFieldsModel> formFields = query.list();
		
		return formFields;
	}

	
}

now here is the freemarker template that gets redered dynamically

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
table a:link {
		color: #666;
		font-weight: bold;
		text-decoration:none;
	}
	table a:visited {
		color: #999999;
		font-weight:bold;
		text-decoration:none;
	}
	table a:active,
	table a:hover {
		color: #bd5a35;
		text-decoration:underline;
	}
	table {
		font-family:Arial, Helvetica, sans-serif;
		color:#666;
		font-size:12px;
		text-shadow: 1px 1px 0px #fff;
		background:#eaebec;
		margin:20px;
		border:#ccc 1px solid;
	
		-moz-border-radius:3px;
		-webkit-border-radius:3px;
		border-radius:3px;
	
		-moz-box-shadow: 0 1px 2px #d1d1d1;
		-webkit-box-shadow: 0 1px 2px #d1d1d1;
		box-shadow: 0 1px 2px #d1d1d1;
		margin-left:auto;
		margin-right:auto;
		margin-top:120px;
	}
	table th {
		padding:21px 25px 22px 25px;
		border-top:1px solid #fafafa;
		border-bottom:1px solid #e0e0e0;
	
		background: #ededed;
		background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#ebebeb));
		background: -moz-linear-gradient(top,  #ededed,  #ebebeb);
	}
	table th:first-child {
		text-align: left;
		padding-left:20px;
	}
	table tr:first-child th:first-child {
		-moz-border-radius-topleft:3px;
		-webkit-border-top-left-radius:3px;
		border-top-left-radius:3px;
	}
	table tr:first-child th:last-child {
		-moz-border-radius-topright:3px;
		-webkit-border-top-right-radius:3px;
		border-top-right-radius:3px;
	}
	table tr {
		text-align: center;
		padding-left:20px;
	}
	table td:first-child {
		text-align: left;
		padding-left:20px;
		border-left: 0;
	}
	table td {
		padding:18px;
		border-top: 1px solid #ffffff;
		border-bottom:1px solid #e0e0e0;
		border-left: 1px solid #e0e0e0;
	
		background: #fafafa;
		background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));
		background: -moz-linear-gradient(top,  #fbfbfb,  #fafafa);
	}
	table tr.even td {
		background: #f6f6f6;
		background: -webkit-gradient(linear, left top, left bottom, from(#f8f8f8), to(#f6f6f6));
		background: -moz-linear-gradient(top,  #f8f8f8,  #f6f6f6);
	}
	table tr:last-child td {
		border-bottom:0;
	}
	table tr:last-child td:first-child {
		-moz-border-radius-bottomleft:3px;
		-webkit-border-bottom-left-radius:3px;
		border-bottom-left-radius:3px;
	}
	table tr:last-child td:last-child {
		-moz-border-radius-bottomright:3px;
		-webkit-border-bottom-right-radius:3px;
		border-bottom-right-radius:3px;
	}
	table tr:hover td {
		background: #f2f2f2;
		background: -webkit-gradient(linear, left top, left bottom, from(#f2f2f2), to(#f0f0f0));
		background: -moz-linear-gradient(top,  #f2f2f2,  #f0f0f0);	
	}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="javascript">
	$( document ).ready(function() {
		console.log( "ready!" );
		$("#loginButton").click(function(){
			alert('button clicked !');
		});
	});
</script>
</head>
<body>
	<table class="pretty">
		<#list formFieldsModels as formField>
		<tr>
			<#if formField.fieldType == 'text'>
				<td>${formField.fieldLabel}:</td><td><input type="${formField.fieldType}"/><td>
			</#if>
			<#if formField.fieldType == 'password'>
				<td>${formField.fieldLabel}:</td><td><input type="${formField.fieldType}"/></td>
			</#if>
			<#if formField.fieldType == 'button'>
				<td></td><td><input type="${formField.fieldType}" value="${formField.fieldLabel}" id="loginButton"/></td>
			</#if>
		</tr>
		</#list>
	</table>
</body>
</html>

here is the screenshots of the database and the final output.
database

login_ui

Happy Coding (Dynamic UI) 🙂

Advertisements

James Gosling grades Oracle’s handling of Sun’s technology

Gosling says Oracle has done ‘surprisingly well’ with Java

With the four-year anniversary of Oracle’s Sun Microsystems acquisition looming, we reached out to Java founder James Gosling to rate how Oracle has done in shepherding Sun technology.
Gosling gives Oracle eyebrow-raising grades, lauding Oracle’s handling of Java,despite his past acrimony toward Oracle over Java, and giving Oracle a flat-out failing grade on what has become of Solaris OS.
Gosling was a longtime Sun technologist and, briefly, a CTO at Oracle right after Oracle bought Sun in January 2010. He is considered the father of Java, which was founded at Sun in 1995. Asked how different technologies have faired under Oracle’s stewardship, Gosling graded Oracle and offered his own perspectives:
sample

These days, Gosling is chief software architect at Liquid Robotics, which develops ocean-based robotics. After leaving Oracle in 2010, Gosling stopped presenting at the JavaOne technical conference, but he reappeared onstage at the event in October 2012.

Credits : directly taken from “www.infoworld.com”
Java is great…