Wednesday 22 April 2020

Themes Development in WebSphere Portal 8.5

Developing New Theme Skin modules in Websphere Portal 8.5

To develop new Themes/Skins in IBM Websphere Portal 8.5 you need the following.

1.      IBM WebSphere Portal 8.5
2.      IBM Rational Application Developer (RAD) 8 or above / IBM Rational Software Architect.
3.      WebDAV Client (not mandatory but good to have)

The steps mentioned below are required to be followed to develop a new Them in
IBM WebSphere Portal 8.5. 

Theme Resources

To set up the custom theme in an EAR file we need to retrieve the source from the shipped theme.
We need two kind of resources for this:
           
           1.   Dynamic resources               
            2.   Static resources

Dynamic Resources: Copy the following folders to your own folder

Location: /WebSphere/PortalServer/theme/wp.theme.themes/default85/installedApps/DefaultTheme85.ear/DefaultTheme85.war

Folders to copy
     ·         skins
     ·         themes
     ·         WEB-INF/decorations.xml
     ·         WEB-INF/tld/*

Static Resources: To retrieve the static resources we need to retrieve the content through the browser, using the following URLs:




Common Resources –

Unpack the ZIP files and save them to a temporary folder.
When common-resources are unzipped, the folder is named only “ibm”. Move the folder “ibm” into a newly created folder with the name “common-resources”.

Some sample screenshots are shown below: 








Saturday 2 April 2016

Developing a JSR 286 Portlet using Spring MVC

As step-by-step approach to develop a portlet using Spring MVC using RAD and deploy in WebSphere portal 8.5


Spring is a very popular framework and it provides lots of features and functionalities, organized in modular fashion. In addition to supporting conventional (servlet-based) Web development, Spring also supports JSR-286 Portlet development. The Portlet MVC framework is a mirror image of the Web MVC framework, and also uses the same underlying view abstractions and integration technology.

Just like any other MVC framework , Spring MVC consists of 3 things. 

1) M-model 
2) V-view 
3) C-Controller. 

Following is the core architecture of Spring (Web) MVC framework.




The Front Controller (Dispatcher Portlet) works as Controller. The front controller takes the incoming request and dispatches to the specific handler (Controller) which has been designed to cater that particular type of request.

The handler(Controller) processes the request and sends the response back to the front controlloer with the help of Model.

The front controller then determines the particular View withe the help of View Resolver and finally send the response back to the client.

 Now let's create a Spring MVC portlet for example. I will use using Rational Application Developer (RAD) for creating the portlet.

Step 1: Open your RAD or Eclipse and create a new portlet project



Step 2: Now modify the type of the portlet and make it a JSR 286 empty portlet




 This will  create the structure of the web project and it will look like this.




Step 3: Now add the spring library and other related jars in our project. Download the following spring  jars from here. Add the jars in the /WEB-INF/lib folder of the project.




Step 4: The next step will be adding the entry of View Renderer servlet in web deployment descriptor. This step is very important. Spring portlet is an extension of the Spring Web MVC and Spring provides support of all its functionalities in portlet context with the help of this renderer servlet. This vervlet works as a bridge between Spring Web MVC and Portlet MVC.

 <servlet>
<servlet-name>ViewRendererServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.ViewRendererServlet
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ViewRendererServlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>

Also, add the following entry of Context Loader Listener. This will tie the Application Context to the life cycle of Servlet Context and automate the creation of Application Context. 

 <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Step 5: Open the portlet deployment descriptor (portlet.xml) and give entry of the Dispatcher portlet. As described above, the Dispatcher Portlet will serve as the Front Controller and will be responsible to dispatch the request to the contoler specified to hadle that particular type of request.

<portlet >
   ... 
   <portlet-class> org.springframework.web.portlet.DispatcherPortlet</portlet-class>
   ...
</portlet>

There is another entry that you can provide here in portlet.xml is "contextConfigLocation" in case if you want to have a custom name or location of the application context file. If you do not provide any specific location Spring will look for the Application Context file inside "/WEB-INF" by default. 

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value><<location of you Application Context file>> </param-value>
</context-param>

 Step 6: Create a file called ApplicationContext inside "/WEB-INF" and add the entry of ViewResolver there. In Spring framework, DispatcherPortlet will take the help of ViewResolver to choose the view( JSP in our case).So we need to configure view (through View Resolver) in Spring application context file. Add following entry in context file
  
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="cache" value="false" />
<property name="viewClass"
value="org.springframework.web.servlet.view.InternalResourceView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

Step 7 : Now we will create another context file and place it inside WEB-INF folder. The naming convention of the context needs to be <<portletName>> - portlet.xml. S0, in our case it will be "MyFirstSpringMVCPortlet-portlet.xml". This is a context file we will maintain to place all portlet specific configuration parameters. 





Inside the config file register your controllers and DefaultAnnotationHandlerMapping. The DefaultAnnotationHandlerMapping maps request to class and/or methods that are annotated with @RequestMapping.

<bean id="viewController" class="com.springmvc.poc.portlet.controller.ViewController"></bean>
<bean id="editController" class="com.springmvc.poc.portlet.controller.EditController"></bean>
<bean id="helpController" class="com.springmvc.poc.portlet.controller.HelpController"></bean>


<bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>

You may find it confusing why we need to maintain 2 different config files (Application Context and MyFirstSpringMVCPortlet-portlet.xml). Actually this is not mandatory. I am just following a good practice by separating the application specific configuration with portlet specific configuration.

Step 8: Now we need to create the controller class in the same package as registered in the context file.

@Controller("viewController")
@RequestMapping(value = "VIEW")
public class ViewController {

@RequestMapping
protected ModelAndView handleRenderRequestInternal(RenderRequest request,
RenderResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView();

modelAndView.setViewName("view");

return modelAndView;
}

}

The @Controller is used to denote that this is our controller. Value will be same as class name. Second annotation is @RequestMapping(“VIEW”) which tell to DispatcherPortlet  that this controller will support VIEW mode. Similarly dirrerent controllers has to be added for other modes (EDIT, HELP etc,).

The @RenderMapping annotation denotes the default render method. It means whenever we place this portlet, it will render this method. To handle render request, actions request and event request, separate methods need to be added with annotation @RenderMapping(params = "view=<<view Name>>"), @ActionMapping(value = "<<value>>") and @EventMapping(value = "<<value>>") respectively.

In our example the method returns a ModeAndView onject. The ModelAndView object tries to resolve the view name (view.jsp) inthe pathe we have specified in the our view resolver enetry in the previous step. We have specified the prefix as "/WEB-INF/jsp/" and suffix as ".jsp". So, the DispatcherPortlet with the help of ViewResolver, will try to find "/WEB-INF/jsp/view.jsp" and will try to render it. 


Step 9: Finally, we need to create the jsp in the same location so that it can be rendered.


and will write a small text in the jsp to display after a successful rendering of the portlet.

<%@page session="false" contentType="text/html"
pageEncoding="ISO-8859-1"
import="java.util.*,javax.portlet.*,com.freedommortgage.portlet.loandetailsheaderportlet.controller.*,com.freedommortgage.portlet.loandetailsheaderportlet.model.*"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<fmt:setBundle
basename="com.freedommortgage.portlet.loandetailsheaderportlet.nl.FMC_LoanDetailsHeaderPortletResource" />
<portlet:defineObjects />

<h3>MyFirstSpringMVCPortlet rendered successfully<h3>

Step 10: Now we are all set to deploy and test our Spring MVC portlet. Once deployed and added to a portal page, it will render display the jsp.




Wednesday 2 December 2015

WCM Basics: Install and Configure a Web Content Viewer Portlet in a Portal Page

WCM Basics: Install and Configure a Web Content Viewer Portlet in a Portal Page

WCM is a very popular web content management tool. In a real life scenario,it is most commonly used along with WebSphere portal. There are several other ways to integrate WCM with Web Sphere portal but, today we are going to talk about the most common and simple way to achieve it, using a out-of-box content viewer portlet.

Web content viewer portlet comes along with portal installation. Based on the type of WCM server, remote/local, the corresponding package (war) needs to be installed and configured to display web content. Following are the steps

1. Install the content viewer portlet. The package is available in the following location in WPS 8.0

Local Rendering: 
\PortalServer\pzn.ext\portlet.localrendering\localrendering.war\installableApps

Remote Rendering:
\PortalServer\pzn.ext\portlet.remoterendering\remoterendering.war\installableApps

Note: Choose the correct package based on the architecture of your project

2. After the installation is done, the portlet is ready to be added to a portal page. The portlet can be found if searched by "Web Content Viewer (JSR 286)". Now create a new page and add the portlet.














3. The next step will be to create the web content to be displayed. For our example, we have used the sample content available in the following location in WCM.














4. Now the content is ready and portlet is added to the page. Go to the Manage Pages and click "Edit Page Layout". Now there are 2 options available to configure the portlet.





a). Select the "Configure" option to configure the web content. If this option is selected, then the changes will applicable for all instances of the portlet.

b). Select the "Edit Shared Settings" option. If this option is selected, the changes will effect only that particular instance of the portlet.















5. Select the options as shown in the below diagram





6. After all the steps done correctly, the portlet will display the web content.




  

Saturday 28 November 2015

Socialize your application with IBM Connections



The word "Social Networking" was buzzing around all over the place from the recent past and at present it has gained lot of momentum. It started with "Orkut" initially and over the time it has gained its popularity and with Facebook it has created a new dimension in the world of internet. It provides endless opportunities to connect with people, share thoughts, ask questions, answer to queries, create groups of people with similar interests etc. to e precise in a single word, to collaborate.

Seeing the popularity and the capability of social networking, research were started to bring  these features at the enterprise level. After initial level of research it was found that the attributes of social networking can be used at the enterprise level and it can open endless opportunities for the organizations to excel and prosper. The most common features of social networking like Community, Blog, Forum, Status Updates, File Sharing etc. could be very beneficial for an organization to implement so that the employees can collaborate among themselves.

Let's take an example, John is a marketing manager in a big organization. He is recently working for an assignment which needs some basic knowledge of search engine optimization. But, being a marketing person John is finding it difficult to cope up with the situation. He thought there could be several experts available in his own organization who can help him with some basic knowledge. But, while looking for a search engine specialist, John found it very difficult to reach out to the proper person. He does not have any clue whom to reach out to and where to start with.

Here comes the need of a enterprise social collaboration tool. John can easily login the platform and search for the search Engine optimization specialist. He can even go to the profile of the person and check the several assignments that he had worked on related to search engine optimization, he can check out the technical papers he might have published. Most importantly, John now can directly approach the person and take his help to get some basic knowledge required or his assignment.

This was just a small example. The possibilities are actually endless. To be more specific, the enterprise collaboration can open a new dimension to the organizations. These are all the reasons, enterprise level social collaboration has picked up super fast last few years and most of the organizations are now a days using it.

There are various enterprise collaborations  tools available. Among all these few are very popular. IBM Connections, Yammer and Jive are the most popular tools at present. Though Jive and Yammer are equally popular and efficient, I will talk about IBM Connections here.

IBM Connections initial version (v1.0) was launched on 29 June 2007. After launch, it was accepted by the industry very quickly and widely and that is the reason it has grown so fast and went though several stages of evolution and the v5.0 was launch last year (26 June, 2014). IBM Connections consists of the following applications: Activities, Blogs, Bookmarks, Communities, Files, Forums, Home page, Metrics, Profiles, and Wikis. Whether you want to share information, build a network of useful contacts, or follow people, there is an application for you.

IBM Connections can be used independently as well as can be integrated with existing portal to bring in social features. Following are the two ways to integrate IBM Connections with existing applications

1. Add Connections out-of-box portlets  in to your custom portal page:

IBM Connections provide out-of-box portlets, which are readily available in "Greenhouse Solutions Catalog", and  can be installed and configured easily. Once configured, the portlets can be added to a portal page and used. The portlets can be used to add social features like Blog, Wiki, Communities, Forum, File Sharing etc. to an existing Web Sphere portal application. The detailed steps to download, install and configure Connections portlets can be found in the Wiki below

http://www-10.lotus.com/ldd/lcwiki.nsf/xpDocViewer.xsp?lookupName=IBM+Portlets+for+Portal+8.5#action=openDocument&res_title=Installing_the_IBM_Connections_Portlets_for_WebSphere_Portal_ip85&content=pdcontent 

2. Integrate through IBM Connections API:

IBM Connections provides ATOM based API (Atom Syndication Format) to integrate with external applications. Any portal or non portal application can be integrated with connections using API very easily. The API details can be found in the Wiki below

http://www-10.lotus.com/ldd/lcwiki.nsf/xpDocViewer.xsp?lookupName=IBM+Connections+4.5+API+Documentation#action=openDocument&res_title=IBM_Connections_API_overview_ic45&content=pdcontent      

















Sunday 22 November 2015

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)
The following article describes a simple and step by step approach of customizing IBM Connections 3.0 using Web Application Integrator (WAI)

Introduction:

Web Application Integrator for IBM WebSphere Portal is a solution which allows external web applications to be integrated with WebSphere Portal. Examples of such external web applications include IBM web-based products like Lotus Connections, Lotus DWA, and Lotus Quickr, as well as other web applications within the enterprise. Following are the steps that need to be followed to integrate for IBM WebSphere Portal with IBM Connections.

Install the Install Web Application Integrator portlet: 

The installation kit can be downloaded from the following location.
https://greenhouse.lotus.com/plugins/plugincatalog.nsf/assetDetails.xsp?action=editDocument&documentId=31AC15EF8BF546DF85257700005C50BE

The installation kit installs the Web Application Integrator portlet and adds it to the "Manage Pages" page.

Create a standard Portal URL page:

1. Log into Portal using an ID with administrative access rights.
2. Go to the Manage Pages portlet, located on the "Manage Pages" page under Administration / Portal User Interface.
3. Click "New URL" button.

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)

























4. On the "New URL" page:

  • Add a title for page.
  • Click the "HTML" checkbox and enter the URL to the external web application.
  • Click the "OK" button.

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)




















Use the new Web Application Integration portlet to generate an HTML <script> tag :

1. Copy its unique name of the URL created in the previous step.
2. Open the Web App Integrator page and Paste it into the input field of the Web App        Integrator portlet.
3. Click the "Generate HTML <script> tag" button in the Web App Integrator portlet.       A text box will appear with a complete HTML <script> tag in it.
    Note: This tag only integrates the external web application for the URL page                 specified as input.

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)


















Add the <script> tag to the web application:

1. In the header component of the external web application, locate the code which generates the HTML <body> tag markup. 

2. Copy the entire content inside the <script> tag and paste it in a browser and save the generated markup as a jsp file. For example save it as “wai_activity.jsp”. As shown the figure below.

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)






















3. For example we are modifying the Activity feature of IBM Connections. Go to the IBM Connections installation directory and open the mainpage.jsp. It can be found in the following location

\installedApps\Activities.ear\oawebui.war\WEB-INF\jsps\webui\mainpage.jsp

4. Copy the “wai_activity.jsp” that we saved in the previous step and paste it in the same location where the “main .jsp” is present.

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)










5. Open the main.jsp and and include the  “wai_activity.jsp” immediately after the <body> tag.

<jsp:include page="wai_activity.jsp" />

6. Open the  “wai_activity.jsp” and verify the css, js and images file path. If the path is relative then prepend the proper host and port name. For example the jsp will have the path like 

<link type="text/css" rel="styleSheet" href="/MyThemeSkin/themes/html/MyTheme/css/stylescog.css" />
<link type="text/css" rel="styleSheet" href="/MyThemeSkin/themes/html/MyTheme/css/tabmenu.css" />
<link type="text/css" rel="styleSheet" href="/MyThemeSkin/themes/html/MyTheme/css/base.css" />


Prepend the proper host and port name to make it correct.

<link type="text/css" rel="styleSheet" href="http://pc161846.xyz.com:10039/MyThemeSkin/themes/html/MyTh eme/css/stylescog.css" />
<link type="text/css" rel="styleSheet" href="http://pc161846.xyz.com:10039/MyThemeSkin/themes/html/MyTh eme/css/tabmenu.css" />
<link type="text/css" rel="styleSheet" href="http://pc161846.xyz.com:10039/MyThemeSkin/themes/html/MyTh eme/css/base.css" />

This step will complete the process and now user can experience a seamless traverse from WebSphere portal and IBM Connections. Following figures show the navigation between portal and Connections. Following is the example  


1.Go to portal home page

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)


















2. User clicks the activities link from drop down.

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)


















3. This page shows the content from Connections Activities. All the Content is of Connections. This way user can traverse from portal to connection seamlessly.

Customizing IBM Connections 3.0 Using Web Application Integrator (WAI)



















If user wants to conditionally display Portal navigation when the user links to the web application through Portal, your code needs to do two things

1.  Append a parameter “fromPortal=true” to the application URL defined on the Portal URL page. For example:

https://pc182041.xyz.com:9444/activities/service/html/mainpage?fromPortal=true

2.  Now, in the web application’s header component where the Web App Integrator jsp is included, user can add code which checks for that URL parameter. If the URL parameter is present and set to true, the Portal navigation is displayed. Otherwise, the navigation is not displayed.  Following is the code snippet.

       <c: if test ="${param.fromPortal == 'true'}">
<jsp: include page = "wai_activity.jsp" />
</c: if>

References:

http://www-10.lotus.com/ldd/lqwiki.nsf/dx/using-the-web-application-integrator-for-ibm-websphere-portal

http://www.ibm.com/developerworks/websphere/library/techarticles/0901_debinder/0901_debinder.html

Friday 20 November 2015

Implementing AJAX in a JSR 286 portlet using Embedded Java Script (EJS)

Implementing AJAX in a JSR 286 portlet using Embedded Java Script (EJS)


The following article describes embedded java script toolkit in brief and provides a step by step approach to implement it using ajax in a custom JSR 286 portlet.


Introduction:

Embedded JavaScript (EJS) is a JavaScript template library, commonly used for building html strings from JSON data. EJS cleans the HTML out of JavaScript with client side templates.


Whenever AJAX is used in web development it is always a problem to deal with the response and generate markup based on the AJAX response. Normally to deal with the response the most general approach is to create dynamic HTML and generate the presentation layer. The following code snippet shows this approach
var html = "<h1>"+ajaxResponse.title+"</h1>"
html += "<ul>"
for(var i=0; i< ajaxResponse.data.length; i++) {
   html += "<li><a href='supplies/"+data.entry[i]+"'>"
   html += data.entry[i]+"</a></li>"
}
html += "</ul>"


But, the problem in this approach is, the structure of the HTML is lost in between the JavaScript logic. And in case of the big and complex markups, it is almost impossible to create and manage the JavaScript logic and markup HTML together. To handle this kind of scenario, EJS can be very useful. EJS separates presentation markup from JavaScript logic very well. EJS works like the following

Implementing AJAX ina JSR 286 portlet using Embedded Java Script (EJS)
               
Here,
HTML represents the markup part.
Data represents data in JSON format that is coming from AJAX response.
Template is something which EJS provides.


EJS separates the presentation markup into a separate file called template. Template is a file with a “.ejs” extension. For example:  “myPageData.ejs”. Following is the code snippet of a sample template.


Implementing AJAX ina JSR 286 portlet using Embedded Java Script (EJS)


Everything inside <% %> tag is executed and everything inside <%= %> tags inserts itself into the returned HTML string. A specific JavaScript syntax is needed for loading and rendering of the template. The following code snippet shows the syntax.


Implementing AJAX ina JSR 286 portlet using Embedded Java Script (EJS)
To get the templates working, the page needs to include EJS so your JavaScript can use it. The following code snippet shows the syntax.
Implementing AJAX ina JSR 286 portlet using Embedded Java Script (EJS)

Example :

Let’s take a real life example. In our example we have implemented EJS with DOJO in our Social collaboration Portlet (JSR 286) application. Following are the steps.


  1. Creates the DOJO XHR method (xhrGet(), xhrPost() or xhrPut()) to call your AJAX Servlet or Portlet. Following is the code snippet


function onAddButton(){
var xhrArgs = {
url: "<%=renderResponse.encodeURL(AddServerResourceURL.toString())%>",
form: dojo.byId("statusUpdateForm"), //ID of the HTML Form
handleAs: "text",
load: function(data) {
var jsonObj = eval('(' + data + ')'); //AJAX Response
var callback = new EJS({url : '<%=renderRequest.getContextPath()%>/_ProfileStatusUpdates_JSR286/templates/page.ejs'}).render(jsonObj); //Rendering of the EJS template
dojo.byId("theMenu").innerHTML = "";
dojo.byId("theMenu").innerHTML = callback;
},
error: function(error) {
alert(error);
}
}
//Call the asynchronous xhrPost
var deferred = dojo.xhrPost(xhrArgs);
 }


2. The AJAX url needs to be constructed to call the ServeResource() method of the portlet. Following is the syntax.


<portlet:resourceURL var="AddServerResourceURL" id="ADD"/>
<portlet:resourceURL var="DeleteServerResourceURL" id="DELETE"/>
<portlet:resourceURL var="AddCommentResourceURL" id="ADD_COMMENT"/>
<portlet:resourceURL var="DeleteCommentResourceURL" id="DELETE_COMMENT"/>


3.  The AJAX method will invoke the serveResource(ResourceRequest request, ResourceResponse response) of the portlet. Inside the method we will invoke the corresponding methods based on the resourceID (“ADD”, “DELETE”, “ADD_COMMENT” or “DELETE_COMMENT “). Following is the code snippet.


public void serveResource(ResourceRequest request, ResourceResponse response)throws PortletException, IOException {
String userId = request.getRemoteUser();
String jsonString = null;
String responseType  = null;
String resourceId = request.getResourceID();
try {
if(null != resourceId && resourceId.equals("ADD")){
String addCommentText = request.getParameter("addStatusTextArea");
responseType = MyStatusUpdatesHelper.addEntry(userId, addCommentText);
}else if(null != resourceId && resourceId.equals("DELETE")){
String deleteLink = request.getParameter("deleteUrl");
responseType = MyStatusUpdatesHelper.deleteEntry(userId,deleteLink);
}else if(null != resourceId && resourceId.equals("ADD_COMMENT")){
String entryId = request.getParameter("entryId");
String CommentText = request.getParameter("addCommentTextArea");
responseType = MyStatusUpdatesHelper.addComment(userId,entryId,CommentText);
}else if(null != resourceId && resourceId.equals("DELETE_COMMENT")){
String deleteCommentLink = request.getParameter("deleteCommentUrl");
System.out.println(deleteCommentLink);
responseType = MyStatusUpdatesHelper.deleteEntry(userId,deleteCommentLink);
}
if(responseType.equals("SUCCESS")){
List<ProfileUpdatesBean> statusUpdatesList = new ArrayList<ProfileUpdatesBean>();
try {


statusUpdatesList = MyStatusUpdatesHelper.getProfileStatusUpdates(userId);
jsonString = JsonHelper.getJson(statusUpdatesList, userId);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}else{
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
response.getWriter().write(jsonString);
}


4. As shown in the code above, After invoking the methods of the MyStatusUpdatesHelper class, we have checked the responseType. If it is “SUCCESS” then call the getJson() method of JsonHelper class. Pass the java object that was returned by the MyStatusUpdatesHelper class. This getJson() method will convert the java object into JSON object and return. Following is the code snippet.


public static String getJson(List<ProfileUpdatesBean> statusUpdatesList, String userId){
StatusUpdatesParentBean bean = new StatusUpdatesParentBean();
bean.setLoggedinUserId(userId);
bean.setProUpdateList(statusUpdatesList);
Gson gson = new Gson();
String Json = gson.toJson(bean);
return Json;
}

5. Once the JSON object is returned, we have sent that in respone using write() method of response.getWriter().
6. Once the response is back, we convert the JSON String to JSON object using the following syntax
var jsonObj = eval('(' + data + ')');


7. After that, just invoke the render() method  EJS on the template and pass the JSON object as parameter. The template is attached.

8. Finally, markup generated by the template, has to be inserted into the page markup using the following syntax.
dojo.byId("theMenu").innerHTML = "";
dojo.byId("theMenu").innerHTML = callback;
Here, “theMenu” is id od a HTML DIV element.


This way AJAX can be implemented with ease using EJS. EJS has the following advantages
  1. Building HTML strings with JavaScript:
As we discussed in this tutorial, the problem of HTML string concatenation in JavaScript is maintainability. When adding together HTML in JavaScript strings, it is difficult to see the big picture of what you’re creating - a representation of the layout for your page. Using templates makes layout easier because you can see the HTML and preserve line breaks and spacing.
  1. AJAX web development with web services:
EJS accepts JSON coming in asynchronously from a web service, passes this data into a template of your choosing, and inserts the resulting HTML into the page for you. Only the following  line of code is needed.
new EJS({url: 'comments.ejs'}).update('element_id', '/comments.json')
  1. Application skinning:
If user wants to give wer to customize their own look and feel, EJS provides the perfect mechanism. EJS templates execute in the browser only, so there is no security risk to your server. Allowing users to upload EJS templates and associated stylesheets is the easiest and fastest way to skin your site.


References :