Serving Static content in Spring

To serve a static content in spring, spring’s mvc namespace provides <mvc:resources> element. All we must do is configure it in the Spring configuration.

All requests that go through DispatcherServlet must be handled in some way, commonly via controllers. Since requests for static content are also being handled by DispatcherServlet, we’re going to need some way to tell Dispatcher-Servlet how to serve those resources. But writing and maintaining a controller for that purpose seems too involved. Fortunately, the <mvc:resources> element is on the job.

Let’s see how we configure element in configuration file:

	<?xml version="1.0"encoding="UTF-8"?>
	<beans xmlns="http://www.springframework.org/schema/beans"
	       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		   xmlns:mvc="http://www.springframework.org/schema/mvc"
		   xsi:schemaLocation="http://www.springframework.org/schema/mvc
		   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		   http://www.springframework.org/schema/beans
	       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

		<mvc:resources mapping="/resources/**" location="/resources/"/>
	</beans>

In above configuration, we can see two attributes used for :

mapping : The mapping attribute is set to /resources/**, which includes an Ant-style wildcard to indicate that the path must begin with /resources, but may include any subpath after that.

location : The location attribute indicates the location of the files to be served. As configured here, any requests whose paths begin with /resources will be automatically served from the /resources folder at the root of the application.
Therefore, all of our images, stylesheets, JavaScript, and other static content needs to be kept in the application’s /resources folder.

Enjoy Spring 🙂

Thanks
Pranav Kumar
Associate Projects
Cognizant Technology Solutions

Autowiring in Spring

As we know in Spring you can wire beans with their dependencies by doing XML configuration. This XML configuration works well for small scale application but
for big application to write so much XML is a hectic task. Fortunately Spring provides a few tricks to cut down on the amount of the XML configuration required.
And One of the way is Autowiring that I am going to discuss in this article.

When it comes to automatically wiring beans with their dependencies, Spring has lots of tricks to work from. As a result, Spring provides four flavors of autowiring:

byName

This byName autowiring tries to match all properties of the autowired bean with beans that have the same name or ID as the properties.
And the properties for which there is no matching bean will remain unwired.

Lets understand this by an example. Suppose there is a bean class named ‘EmployeeBean’ having two properties ‘name’ and ‘company’.
Comapny is just one another bean that we are using as properties in EmploeeBean class.

	package com.mindfire.bean;
 
	public class EmployeeBean {
     
		String name;
     
		//Assume Company is an another bean contains company information
	    Company company; 
		
		//Getter and Setter methods for name and company field here
	}
 

The traditional XML configuration for above bean will be like this:

    <!-- Declaring a bean with id 'employeeBean' and class value here. -->
	<bean id="employeeBean" class="com.mindfire.bean.EmployeeBean">
		<property name = "name" value = "Pranav" />
		<property name = "company" ref = "company" />
	</bean>
 
	<!-- Bean declaration for Company Bean class . -->
	<bean id = "company" class = "com.mindfire.bean.Company" />
  

now lets see how we will configure the same Employee bean using autowiring byName.

    <!-- Declaring a bean with id 'employeeBean' and class value here. -->
	<bean id="employeeBean" class="com.mindfire.bean.EmployeeBean" autowire="byName">
		<property name = "name" value = "Pranav" />
	</bean>
 
	<!-- Bean declaration for Company Bean class . -->
	<bean id = "company" class = "com.mindfire.bean.Company" />
  

So we see the difference that by using byName autowiring we don’t need to write this:
Spring automatically wires the ‘company’ bean declared in XML with EmployeeBean’s ‘company’ property when it finds the name of the bean declared is same
as property name in EmployeeBean.

byType

Autowiring using byType works in a similar way to byName, except that instead of considering a property’s name , the property’s type is examined.

Lets consider the same example we saw above with autowiring byName. In this case Spring continer will search for a bean whose type is ‘Company’ in XML configuration
and will wire that bean into the ‘company’ property of EmployeeBean class.

But there is a limitation to autowiring by type. What happens if Spring finds more than one <bean> declared whose type is assignable to the autowired property ?
In such case, Spring is not going to decide which bean to autowired and will just throw an exception.

To overcome ambiguities with autoworing by type, Spring offers two way:
– Either identify a primary candidate for autowiring or
– Eliminate bean from autowire candidancy.

To identify a primary autowire candidate, we need to work with element’s primary attribute. If only one autowire candidate has primary attribute
set to true, then that bean will be choosen over others. But the weird thing is that all bean’s primary is setted true by default.
That means that all autowire candidates will be primary. So, to use primary, you will need to set it to false for all beans that are not the primary choice.

You can apply this on any bean like this:

	<bean id = "company" class = "com.mindfire.bean.Company" primary="false" />
   

The primary attribute is only used to choose preferred candidate over others.

If you want to remove some beans in participating autowiring process, you can set their autowire-candidate attribute to false like this:

	<bean id = "company" class = "com.mindfire.bean.Company" autowire-candidate="false" />
   

constructor

If you do autowire = “constructor” for any bean, Spring tries to match up a constructor of the autowired bean with beans whose type are assignable to
the constructor arguments.

When we use constructor injection in spring, we use <construct-arg> element to pass required parameters to constructors.
The same thing can be acheived using autowire = “constructor”. In this case Spring automatically choose constructor arguments from beans in the Spring container.

Autowiring by constructor has same limitations as byType. Spring won’t attempt to guess which bean to autowire when it finds multiple beans that matches a constructor
arguments.

autodetect

This is the best fit autowiring. When you can’t decide which autowiring you should use, you can set autowire=”autodetect” and let Spring make decisions for you.
For a bean configured with autowire = “autodetect”, Spring tries to autowire by constructor first. If a suitable constructor match can’t be found, then Spring
will attempt to autowire by type.

Default Autowiring
You can also set default-autowire attribute for <beans> element in Container. Once you set this default-autowire for <beans> element, it will be
applied to all beans declared in that XML configuration file. You can do this like below:

    <?xml version="1.0" encoding="UTF-8"?>
	<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
	   default-autowire="byType">
 
    ....
 
	</beans>
  

In above configuration, default-autowire is setted to byType.
Since you have setted default-autowire attribute for , it doesn’t mean you are stuck with it for all beans.
You can still override the default on bean-by-bean basis using their autowire attribute.

Summary
We saw all four types of Autowiring method in Spring and also discussed the pros and cons of each. All has same purpose to reduce the amount of XML configuration.
As per our need we can decide which autowire suits best to our situation. There are also one other way called ‘Annotation’ to autowire beans in Spring
that I will discuss in my next blog.

Enjoy Spring 🙂

Pranav Kumar
Java/J2EE Developer, Mindfire Solutions
http://www.mindfiresolutions.com
Mindfire Solutions

Wiring Collections in Spring configuration

To wire a simple property like ‘String name’, ‘int id’ etc… in Spring bean we use ‘value’ attribute and when we have to wire reference of other bean we use ‘ref’ attribute in configuration file. But all these are singular values. Now think about the collections like List,Set,Map etc…

How to wire plural values or Collections in Spring bean configuration ?

Spring offers a way to wire collections in Spring by providing four types of collection configuration elements and these are:

<list>    : Wires a List of values, allowing duplicates
<set>    : Wires a Set of values, no duplicates allowed
<map>   : Wires a collection of name-value pairs where name and value can be of any type
<props>: Wires a collection of name-value pairs where name and value are both Strings

<list> and <set> are used to configure properties that are either arrays or some implementation of java.util.Collection. Lets try to understand this by an example:

Suppose there is a Bean class named Library.java

	public class Library {

		private Collection<Book> books;

		//Getter/Setter methods here

	}

In above bean we have a property ‘books’ of type ‘java.util.Collection’. We also have one other bean Book.java:

	public class Book {

		private String name;
		private String publisher;

		//Getter/Setter methods here

	}

Now lets configure the Library bean in Spring XML configuration file:


	<bean id="library" class="com.mindfire.bean.Library">
		<property name="books">
				<list>
				<ref bean = "springBook" />
				<ref bean = "javaBook" />
				<ref bean = "mySqlBook" />
			</list>
		</property>
	</bean>

	<bean id="springBook" class="com.mindfire.bean.Book" />
	<bean id="javaBook" class="com.mindfire.bean.Book" />
	<bean id="mySqlBook" class="com.mindfire.bean.Book" />

In above configuration file, we are using <list> element to prepare a List and wiring that list to property ‘books’ of Library bean.
<ref> element is used to reference another bean and in this case that bean is ‘Book’.

As I told above <list> and <set> can be used for a property of any implementation of java.util.collection or an arrays. It means <list> element we just used in above configuration file would still work, even if the ‘books’ property were to be declared as

	java.util.List<Book> books;
 

or even if it were to be declared as

	Book[] books;
 

Likewise , you could also use <set> to wire a collection or array property like this:


	<bean id="library" class="com.mindfire.bean.Library">
		<property name="books">
			<set>
				<ref bean = "springBook" />
				<ref bean = "javaBook" />
				<ref bean = "mySqlBook" />
			</set>
		</property>
	</bean>

	<bean id="springBook" class="com.mindfire.bean.Book" />
	<bean id="javaBook" class="com.mindfire.bean.Book" />
	<bean id="mySqlBook" class="com.mindfire.bean.Book" />

So either <list> or <set> can be used to wire any implementation of java.util.Collection or an array. If a property is declared as java.util.Set, it doesn’t mean you must use <set> to do the wiring. Though it seems odd to configure java.util.List property using <set> but it works. In doing so, you will be guarenteed that all members of the List will be unique.

Wiring Maps

Now consider Library bean contains a property ‘books’ of type ‘java.util.Map’ like this:

	public class Library {

		//A Map having 'isbnNumber' (String) as key and Book as value
		private Map<isbnNumber,Book> books;

		//Getter/Setter methods here

	}

Now we have a property which contains key-value pair for ‘books’. Lets configure Library bean in spring configuration for ‘Map’:


	<bean id="library" class="com.mindfire.bean.Library">
		<property name="books">
			<map>
				<entry key = "1111" value-ref = "springBook" />
				<entry key = "2222" value-ref = "javaBook" />
				<entry key = "3333" value-ref = "mySqlBook" />
			</map>
		</property>
	</bean>

	<bean id="springBook" class="com.mindfire.bean.Book" />
	<bean id="javaBook" class="com.mindfire.bean.Book" />
	<bean id="mySqlBook" class="com.mindfire.bean.Book" />

The <map> element declares a value of type java.util.Map. Each <entry> element defines a member of the Map.
key attribute specifies the key of the entry whereas the value-ref attribute defines the value of the entry as a reference to another bean within the Spring Context.

<entry> element in <map> has four attribute:
1. key : Specifies the key of the map entry as String
2. key-ref : Specifies the key of the map entry as a reference to a bean in the Spring Context
3. value : Specifies the value of the map entry as a String
4. value-ref : Specified the value of the map entry as a reference to a bean in the Spring Context

Wiring Properties

If you need to implement a Map whose entries have both String keys and String values, you may want to consider using java.util.Properties instead of a Map. the Properties class serves the same purpose as Map, but limits the keys and values to Strings.

Suppose the property ‘books’ is declared like:

	public class Library {

		//A Properties having 'isbnNumber' (String) as key and Book Name (String) as value
		private Properties<isbnNumber,bookName> books;

		//Getter/Setter methods here

	}

Lets see how to configure a bean property ‘books’ of type ‘java.util.Properties’.


	<bean id="library" class="com.mindfire.bean.Library">
		<property name="books">
			<props>
				<prop key = "11111" > Spring </prop>
				<prop key = "2222" > Java </prop>
				<prop key = "3333" > MySql </prop>
			</props>
		</property>
	</bean>

The <props> element constructs a java.util.Properties value where each member is defined by a <prop> element.
Key : Defines the key of each Properties member.
Value is defined by contents of the <prop> element. In above example key is ISBN number of Book and values is Name of book.

Spring also provides an element <null> to set a property to null. You can use <null> like this:

	<bean id="library" class="com.mindfire.bean.Library">
		<property name="books">
			<null/>
		</property>
	</bean>

Summary:
We saw how to wire Collections in Spring configuration.

Pranav Kumar
Java/J2EE Developer, Mindfire Solutions
http://www.mindfiresolutions.com
Mindfire Solutions

Spring’s p namespace in XML configuration

In configuring bean’s in Spring, traditionally we use <property> element to set property for any bean. Instead of using <property> element to set each property in bean , Spring’s p namespace offers a way to wire bean properties that doesn’t require so many angle brackets (<>).

The p namespace has a schema URI of http://www.springframework.org/schema/p

Now lets see how to use Spring’s p namespace in Spring Configuration file:

To use it , simply add a declaration for it in the Spring XML configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	 xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans      	 	   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

.....

</beans>

See in above XML configuration, I’ve added declaration for Spring’s p namespace:

xmlns:p="http://www.springframework.org/schema/p"

With it declared , you can use now p:-prefixed attributes of the element to wire properties.

Example:
Suppose there is a bean class named EmployeeBean.java:

EmployeeBean.java

package com.mindfire.bean;

public class EmployeeBean {
	
	String name;
	
	//Assume Company is an another bean contains company information
	Company company; 
	
	//Getter and Setter methods for name and company field here
}

Company.java:

package com.mindfire.bean;

public class Company {

   //Some code goes here
   
}

We will first configure the above bean’s using <property> element and then using Spring’s p namespace and will finally see the difference.

The XML configuration for above beans using <property> element:

    <!-- Declaring a bean with id 'employeeBean' and class value here. -->
    <bean id="employeeBean" class="com.mindfire.bean.EmployeeBean">
		<property name = "name" value = "Pranav" />
		<property name = "company" ref = "companyBean" />
    </bean>
	
    <!-- Bean declaration for Company Bean class . -->
    <bean id = "companyBean" class = "com.mindfire.bean.Company" />

Now configure the same bean using Spring’s p namespace:

<bean id="employeeBean" class="com.mindfire.bean.EmployeeBean" p:name = "Pranav" p:company-ref = "companyBean">

    <!-- Bean declaration for Company Bean class . -->
    <bean id = "companyBean" class = "com.mindfire.bean.Company" />

The p:name attribute is set to “Pranav”, wiring the ‘name’ property of EmployeeBean with value “Pranav”.

The p:company-ref attribute is set to “companyBean“, effectively wiring the ‘company’ property of EmployeeBean with a reference to the bean whose ID is ‘companyBean‘.
The ‘-ref‘ suffix gives a clue to Spring that a reference should be wired instead of a literal value.

So now the question is whether we should use <property> element or Spring’s p namespace ?

Actually the choice between <property> and the p namespace is up to you. The benefit of Spring’s p namespace is just that it gives you a short way to do same thing that <property> element does. I personally love to use Spring’s p namespace. What about you ? 😉

Enjoy Spring 🙂

Pranav Kumar
Java/J2EE Developer, Mindfire Solutions
http://www.mindfiresolutions.com
Mindfire Solutions

Bean Scopes in Spring

In Spring, all beans are Singletons by default. It means every time you ask an instance of bean from container , it returns you same instance every time. But in real time there might be a situation where you need unique instance every time from container via getBean() method or wiring. So to achieve this basically we need to override the default singleton nature of bean in Spring.

When declaring a in spring container (Spring XML configuration file), we have the option for declaring a scope for that bean. To force Spring to produce a new bean instance each time, we should declare the bean’s scope attribute to be prototype.

For example:
Suppose there is a bean class ‘MovieTicket.java‘ declared in ‘com.mindfire.spring.bean‘ package. For Movie ticket bean instance, each movie ticket must be assigned to only one person i.e each ticket needs to be unique. Right ? So in this case we need unique instance of MovieTicket bean every time from container. For this, we need to set ‘scope’ attribute value to ‘prototype‘ like below:


   <bean id="movieTicketBean" class="com.mindfire.spring.bean.MovieTicket" scope="prototype">

In addition to prototype scope, Spring offers a handful of other scoping options.

1.) singleton: Always returns same instance per Spring container (Default)

2.) prototype: Always returns a new instance (once per use)

3.) request : Scopes a bean definition to an HTTP request. It is only valid when used with a web capable Spring context like Spring MVC.

4.) session : Scopes a bean definition to an HTTP Session. It is only valid when used with a web capable Spring context like Spring MVC.

5.) global-session : Scopes a bean definition to a global HTTP session. Only valid when used in a Portlet context.

Pranav Kumar
Java/J2EE Developer, Mindfire Solutions
http://www.mindfiresolutions.com
Mindfire Solutions

Configure Beans in Spring Container.

In Spring Framework, every java class we write is a POJO (Plain Old Java Object) or sometimes we also say it Bean Class. Since Spring is a Container-based framework, So if you don’t configure the Spring Container, then it’s an empty container and doesn’t serve anything. So basically we need to configure Spring to tell it what beans it should contain and how to wire those beans so that they can work together.

As of spring 3.0 , there are two ways to configure beans in the Spring container. Traditionally, Spring configuration is defined in one or more XML files. But Spring 3.0 also offers a annotation based configuration option. We will discuss traditional XML option here.

A typical Spring configuration XML looks like:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans      	 	   
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<!-- Bean definitions go here -->

</beans>


Within the element you can place all of your Spring configuration, including declaration.


Declaring a Simple Bean

Lets consider there is a class named “EmployeeBean.java”. We will configure this bean in Spring Container and then we will see how we can use this EmployeeBean instance in Spring.

EmployeeBean.java

package com.mindfire.bean;

public class EmployeeBean {

public void printHello() {
System.out.println("Hello Spring!");
}
}

Now lets configure this bean in Spring Configuration file and we give a name for configuration file – ‘spring-config.xml’

spring-config.xml:

spring-config.xml:
<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

   <!-- Declaring a bean with id 'employeeBean' and   	 	class="com.mindfire.bean.EmployeeBean" here. -->
 <bean id="employeeBean" class="com.mindfire.bean.EmployeeBean">

</bean></beans> 

As you can see there are two property used in tag :
id – Just a unique name for bean by which this bean will be identified.
class – For this property we set fully qualified class name of bean.

Now Lets’ see how we can use this bean in Spring. We need to create a class that will read the Spring configuration file first and will get the instance of “EmployeeBean” class.
When we will have instance of EmployeeBean class, we can easily call ‘printHello()’ method of EmployeeBean and can see our desired output “Hello Spring!”.

TestSpringContainer.java:

package com.mindfire.container;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpringContainer {

public static void main(String[] args) throws Exception {

// loads the spring-config xml file in context
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

/*
* Using the getBean() method of context class we are * getting instance of EmployeeBean class.
* The parameter 'employeeBean' in getBean() is the value of * id in that we set in spring-config.xml file
*/
EmployeeBean empBean =
(EmployeeBean) context.getBean("employeeBean");

//now calling printHello()
empBean.printHello();

}
}

Run the TestSpringContainer and you will see the output: Hello Spring!

So in the above example when Spring loads its beans, it will instantiate the bean using default constructor because there is no constrctor defined in EmployeeBean class.

In other way we can say the declaration in XML file:

<bean id="employeeBean" class="com.mindfire.bean.EmployeeBean">

is equivalent to Java code

employeeBean = new com.mindfire.bean.EmployeeBean();

Injecting values through constructors

To inject value in constructor of bean class from Spring configuration file we use

<constructor-arg>

element. We will explore this ‘constructor-arg’ element by an example now.

Now lets go ahead and add two field ‘String name’ and ‘Company company’ in EmployeeBean class.

EmployeeBean.java

package com.mindfire.bean;

public class EmployeeBean {

String name;

//Assume Company is an another bean contains //company information
String Company;

/*
* Constructor using 'name' and 'company' field
*/
public EmployeeBean(String name, Company company) {

this.name = name;
this.company = company;
}

public void printHello() {
System.out.println("Hello Spring!");
}

//Getter and Setter methods for name and company field here
}

Company.java:

package com.mindfire.bean;

public class Company {

//Some code goes here

}

Now lets configure the modified EmployeeBean and new Company bean class in our Spring Container.

spring-config.xml:


<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

  <!-- Declaring a bean with id 'employeeBean' and class value here. -->
    <bean id="employeeBean" class="com.mindfire.bean.EmployeeBean">
		<constructor-arg value="Pranav">
		<constructor-arg ref="companyBean">
	</constructor-arg></constructor-arg></bean>
	
	<!-- Bean declaration for Company Bean class . -->
	<bean id="companyBean" class="com.mindfire.bean.Company">

</bean></beans> 

Look carefully in above bean configuration, We have used two property of ‘constructor-arg’ element:
value – This property is used to pass value for simple type like String, int etc..
ref – This property is used to pass reference for other bean.

Since type of field ‘company’ is itself a different bean class named ‘Company’, so we also need to create a for ‘Company’ bean class and then we
use this as reference in constrctor of EmployeeBean class.

Injecting values through Setter methods

Sometimes you don’t have constructor but getter/setter methods for fields in bean class. In that case you can use default constructor and can set the value using Setters method defined in bean class.

So now we will see how to set values for fields using setter methods instead of constructors.
To set the field value of bean using setter methods we use

<property>

element of Spring.

Now lets configure the container to set field value via setter methods.

spring-config.xml:

<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

   <!-- Declaring a bean with id 'employeeBean' and class="com.mindfire.bean.EmployeeBean" here. -->
      <bean id="employeeBean" class="com.mindfire.bean.EmployeeBean">
		<property name="name" value="Pranav">
		<property name="company" ref="companyBean">
	</property></property></bean>
	
	<!-- Bean declaration for Company Bean class . -->
	<bean id="companyBean" class="com.mindfire.bean.Company">

</bean></beans> 

As you see in above configuration we are using two ‘property’ element. The first one passes the value as String and the second one pass the reference for Company bean class.
Summary
So we learned how to configure a bean in Spring container and how can we pass values via constrctor and setter methods of bean class.
Also we saw how we read the configuration file and create an instance of bean class in Spring.

Pranav Kumar
Java/J2EE Developer, Mindfire Solutions
http://www.mindfiresolutions.com
Mindfire Solutions

Add HTML code dynamically from Java code in Wicket.

How to add HTML code dynamically from Java file in Wicket.

Steps for adding html code dynamically from java file in wicket:-
1. First save the required html code as a string in some String variable.
2. Create a Label instance by passing the above String in the constructor of Label.
3. Make “EscapeModelStrings” false for the Label.
label.setEscapeModelStrings(false);
4. Add Label to Form or Panel or any Container in wicket.
5. Now go to the Html file where you want to add this dynamic html code and write the markup for this Label under <span> tag.

Code Example:- 
In this example we add a dynamic <div> tag in markup from our java file “AddHtmlPanel”. Here AddHtmlPanel extends Panel, so it also becomes a panel and we can add directly the Label here.

    AddHtmlPanel.java

    public class AddHtmlPanel extends Panel {
         
            /**
             * Constructor here
             */
            public AddHtmlPanel (String id) {
                super(id);
         
                //Saved the dynamic html code in a String Variable "dynamicHtml " here by calling the createDynamicHtml() method
                String dynamicHtml = createDynamicHtml("divIdName");
          
                /**
                 * created label here for adding dynamic html code as a string. Constructor of Label contains
                 * two parameters, first parameter is "wicket:id" by which label is identified in markup.
                 * Second parameter is the String variable "dynamicHtml " which contains our dynamic html code as a string.
                 */
                Label divLabel = new Label("divLabel",dynamicHtml );
         
                //Setted EscapeModelStrings False for the label
                divLabel.setEscapeModelStrings(false);
         
                //added label to panel here
                add(divLabel);    
              }
    
               /**
                 * method which returns <div> tag content as a string required to add in html file
                  */
               public String createDynamicHtml(String div_id) {
             
                //created a instance named "divSB " of StringBuilder here
                StringBuilder divSB = new StringBuilder(512);
             
                /**
                 *appended dynamic html code to divscriptSB instance of StringBuilder
                 */
                divSB.append("<div id=\"");
                divSB.append(div_id);
                divSB.append("\"></div>");
             
                //return StringBuilder instance as a String which contains our dynamic html code
                return divSB.toString(); 
            }
     }
    

      AddHtmlPanel.html

    <wicket:panel>
       <span wicket:id="divLabel"></span>
    </wicket:panel>
    

    Its very simple to add any markup code in your html file from your java file in wicket. This is very effective for many purpose. I used this technique at
    several places in my project . I found this flexibility of Wicket when I was looking for a way to implement the Google charts in Wicket. Using this technique I have implemented Google charts in wicket successfully in my project. By this technique you can also add any JavaScript code dynamically to html file from java file. Really very effective… 🙂

    Pranav Kumar
    Java/J2EE Developer, Mindfire Solutions
    http://www.mindfiresolutions.com
    Mindfire Solutions