FreeMarker : Example


Freemarker is a simple templating engine that can generate text contents from any type of template. It is so simple that you can learn it in a single day and can use it in any project.
It helps you when you need to produce bulk text contents of the common format like newsletters, green mail, notifications etc.


package fm;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.sun.tools.javac.util.List;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FMTest2 {
    public static void main(String[] args) throws IOException, TemplateException {
        Configuration cfg = new Configuration();
        cfg.setDirectoryForTemplateLoading(
                new File("templates"));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        Template temp = cfg.getTemplate("FMTest2.ftl");
        Map root = new HashMap();
    
        Map order = new HashMap();
        order.put("topic""Purchage Order");
        
        ArrayList items=new ArrayList();
        items.add(new HashMap(){{put("cdrom","23000");put("mouse","2230");put("keybord","2230");}});
        items.add(new HashMap(){{put("cdrom","23000");put("mouse","225");put("keybord","530");}});
        items.add(new HashMap(){{put("cdrom","23000");put("mouse","7650");put("keybord","2230");}});
        order.put("items", items);
    
        root.put("order", order);
        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);
        out.flush();
        
    }
}

template file : templates/FMTest2.ftl

Computer Model ${order.topic}   
<#list order.items as i>
  ${i.cdrom}, ${i.mouse}, ${i.keybord}
</#list> 

Struts2 - Enabling Client Side validation

Struts2 provides the declarative option to define the validation rules for the data fields in form. You can use the default implementation of validation framework of the struts2 to validate various kind of data. When you use the validation feature of the struts2, it is done server side by default. But setting
a single attribute of the form tag, it can be applied at client side.

Struts2 validation process can work on server side as well as client side. When it works at server side, server return input form containing validation error along with  the text fields. when you use client side validation feature, the javascript will process the validate without sending the form data to server for validation.

it means data is validated before going to server. this javascript is generated by struts frame work into the rendered webpage having the form. this validation works when you set the validation attribute to true in the form tag. And you have the add the head tag of the struts taglib in head tag of the html page.


Here is the source code of the example that is using the struts validation on both sides.

login.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<s:head/>
</head>
<body>
<s:form action="myaction" method="post" validate="true">
  <s:textfield name="username" label="user-name"/>
  <s:textfield name="emailid" label="email-id"/>
  <s:submit value="submit"/>
</s:form>

</body>
</html>



Sucess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2><s:property value="username"/></h2>

</body>
</html>



MyAction.java

import com.opensymphony.xwork2.ActionSupport;
public class MyAction extends ActionSupport {
    
    private String username;
    private String  emailid;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getEmailid() {
        return emailid;
    }
    public void setEmailid(String emailid) {
        this.emailid = emailid;
    }
    
    public String execute()
    {
        
        return "sucess";
    }
}

MyAction-validation.xml


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC 
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>

   <field name="username">
        <field-validator type="requiredstring">
            
            <message>Name is required.</message>
        </field-validator>
    </field>
   <field name="emailid">
        <field-validator type="requiredstring">
            <message>email is required.</message>
        </field-validator>
        
        <field-validator type="email">
            <message> valid email is required.</message>
        </field-validator>

        <field-validator type="fieldexpression">
            <param name="expression">emailid.endsWith('@gmail.com')</param>
            <message>Use only gmail.</message>
        </field-validator>
    </field>
</validators>


struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUB
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <package name="default" namespace="/" extends="struts-default">
 <action name="myaction" class="MyAction">
 <result name="sucess">success.jsp</result>
 <result name="input">loginjsp.jsp</result>
 </action>

 </package>
</struts>

Download Source code

Struts2 - Writing custom validator

Sometimes it is needed that the existing validation rules those are implemented by struts framework do not satisfy project validation criteria. That you have to write your logic according to your requirements. Struts2 provides the facility to write your own validation class in which you can implement your own validation logic.

Step-1:
Write down a class that extends inbuilt validator support class. In this example I am extending the FieldValidatorSupport class that the validate() method that has to be overridden by your custom validator class. Here we can create the variable (i.e. property) e.g. domainName(or other) and its getter-setter in which the values will be passed from validation (xml) file as parameters.

Method validate() is overridden to implement your validation logic. This method takes the Object to be validated at run time that is passed by interceptor.

The method  getFieldValue() which is inherited from super class will help you to retrieve the actual value of the specified field name from the Object passed to validate method.

Now you can define you validation criteria and you can use addFieldError method to add the field error if your validation condition get failed.  If field error is added here, struts framework get intimation that the field validation has failed and shows its corresponding message is displayed on web page.


import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class MyValidator extends FieldValidatorSupport {
    private String domainName;

    public String getDomainName() {
        return domainName;
    }

    public void setDomainName(String domainName) {
        this.domainName = domainName;
    }
    public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        Object value = this.getFieldValue(fieldName, object);
        String s = (String) value;
        System.out.println("custom validator invoked for value : "+s);
        if (!s.endsWith(domainName)) {
            addFieldError(fieldName, object);
        }
    }
}

Step-2:
Create file validators.xml in class path where ActionSupport class is and add the following lines there.
<?xml version="1.0" encoding="UTF-8"?> 
 <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator Config 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
    <validator name="myvalidator" class="MyValidator" />
</validators>

Here myvalidator is the name of validator through which will be refered
MyValidator is the name of the class that is implementing the validation logic.


Step-3 :
Add the following lines of code to use the validator to validate the field .

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC 
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
    <field name="username">
        <field-validator type="requiredstring">
            <param name="trim">false</param>
            <message>Username is required.</message>
        </field-validator>
    </field>

    <field name="email">
        <field-validator type="email">
            <message>Email is invalid.</message>
        </field-validator>
        <field-validator type="requiredstring">
            <message>Email is required.</message>
        </field-validator>
        <field-validator type="myvalidator">
            <param name="domainName">gmail.com</param>
            <message>Email must ends with ${domainName}</message>
        </field-validator>
    </field>
</validators>


Here, you are using the validator myvalidator by referring it the type attribute of field-validator element.
Value of the param having the name domainName will be sent to the domainName property of the validator support class MyValidator.

Download Complete source code of this example.

Popular Posts