struts2: how to display more than one textfield in one row

November 13th, 2010

Struts2 comes with three themes: xhtml, simple and css_xhtml. The beginner usually starts using xhmtl theme which is very straightforward. The main disadvantages of xhtml theme is that default functionality puts one textfield in a row.

I was looking for a way to display two textfields in a row. I did the following attempts:
1.I used a simple theme and standard html tags (table, tr, td). The simple theme does not have several features comparing to xhtml (tooltip, validation, required…)

2.I developed a new theme qxhtml according to vitarara tutorial. The biggest disadvantages was designing a form. I missed a standard html functionality how to span table cells, align error messages etc. I had many problems because I was an absolute beginner and I did not know how to modify freemarker ftl templates.

3.I developed my custom extend_simple theme. I copied a simple theme and I did some modifications (support for validation according to annaskawinska.blogspot)

I was very frustrated about my experience with struts2 and I wanted to get advice from others. I posted a question at design-form-real-life-application. And I get the answer from Anbarasu Aladiyan. Thank you Anbarasu, If I would know for your answer I would use my spare time usefully than googling around and be frustrated…

Anbarasu Aladiyan has suggested: IMHO css_xhtml is the much flexible theme to use.

I have also read two books about struts: Struts 2 in Action and Struts 2 Design and Programming but I did not find any detail information about css_xhtml theme. The content at cssxhtml-theme is a little bit misleading about the feature “Standard two-column CSS-based layout”. I mistakenly thought that css_xhtml is almost the same as xhtml.

OK, I decide to test css_xhmtl.

I did two tests. Both tests try to display three textfields each on the separate row. In the fourth row there should be three textfields on the same row.
——————————–
textfield1
textfield2
textfield3
textfield4 textfield5 textfield6

Test1 uses a css_xhtml theme

<s:form action=javanusAction\" theme=\"css_xhtml\">
<s:textfield label="a1" labelposition="left"/>
<s:textfield label="a2" labelposition="left"/>
<s:textfield label="a3" labelposition="left"/>
<table>
<tr>
<td><s:textfield label="a4" labelposition="left"/></td>
<td><s:textfield label="a5" labelposition="left"/></td>
<td><s:textfield label="a6" labelposition="left"/></td>
</tr>
</table>
</s:form>

We can see that also css_xhmtl has the same standard two-columns layout as xhmtl. The important difference is using html tags(table, tr, td). css_xhtml theme takes html tags into account.

Test2 uses a xhtml theme. The code is the same as in test1, the only difference is used theme xhtml.

<s:form action=javanusAction\" theme=\"xhtml\">
<s:textfield label="a1" labelposition="left"/>
<s:textfield label="a2" labelposition="left"/>
<s:textfield label="a3" labelposition="left"/>
<table>
<tr>
<td><s:textfield label="a4" labelposition="left"/></td>
<td><s:textfield label="a5" labelposition="left"/></td>
<td><s:textfield label="a6" labelposition="left"/></td>
</tr>
</table>
</s:form>

Test2 display 6 textfields in a 6 rows.

I would like to thank to Anbarasu Aladiyan ones more and I hope that my post will help future struts2 developers.

Use i18 with struts2 and tiles

October 6th, 2010

I am developing a multilanguage application and I am using Apache Tiles to organize the page design. Today I will explain you how to modify the page title using Apache Tiles according to selected language.

I have prepare a set of tiles.xml configuration files (tiles.xml, tiles_de.xml, tiles_sl.xml and tiles_en.xml) to support internationalization (i18n), Unfortunatelly the application always choose an english locale regardless of using request_locale=sl.

SOLUTION:
1.User select language in a header.jsp. Below is a code snippet.
<!–select language–>
<s:url action=”setLanguage_sl” id=”slUrl”>
<s:param name=”request_locale”>sl</s:param>
</s:url>
<s:url action=”setLanguage_en” id=”enUrl”>
<s:param name=”request_locale”>en</s:param>
</s:url>
<s:url action=”setLanguage_de” id=”deUrl”>
<s:param name=”request_locale”>de</s:param>
</s:url>

2.Class languageMain is invoked in struts.xml
<action name=”setLanguage_*” class=”language.Main” method=”{1}”>
<result name=”success” type=”redirectAction”>example_list</result>
</action>

3.org.apache.tiles.LOCALE must be set to selected locale
public class Main extends ActionSupport implements SessionAware {
private Map session;

public String en() {
//english
Locale locale = new Locale("en", "EN");
session.put("org.apache.tiles.LOCALE", locale);

return execute();
}

public String de() {
//deutch
Locale locale = new Locale("de", "DE");
session.put("org.apache.tiles.LOCALE", locale);

return execute();
}

public String sl() {
//slovenian
Locale locale = new Locale("sl", "SL");
session.put("org.apache.tiles.LOCALE", locale);

return execute();
}

@Override
public String execute() {

return SUCCESS;
}

public Map getSession() {
return session;
}

public void setSession(Map session) {
this.session = session;
}
}

how to use jQuery grid with struts2 and returns to the selected page after refreshing a page

October 2nd, 2010

I am using jQuery grid with a struts2 to display the data in the table. My dataset has one thousand of rows so I decided to use a pagination. I put 20 rows per one page and there are 50 pages to display all 1000 records. I select page number 3 for example and the records from number 41 to number 60 are presented. Unfortunatelly the page 1 is displayed when the user refresh the page in the browser (records from number 1 to 20 are displayed instead records from number 41 to 60).

Today blog is about remaining the selected page in the jquery grid table after the page is being refreshed.

I face the same problem when the user edit the data. User selects row number 50 in the page 3 and the detail row data is displayed in another form. Page number 1 is displayed instead page number 3 when the record is saved to the database and the user is redirected back to the list page.

SOLUTION:
I decided to store the selected page number into the session.
1.I initialize the attribute tablePageSelection to 1 after the user successfully login to the application.
session.setAttribute(“tablePageSelection”, 1);

2.Selected page is set in the jsp. This is the most important part. “Page” attribute is used to define the selected page.

<sjg:grid
id="customerstable"
.......
page="%{#session.tablePageSelection}"
.......

3.The selected page is stored in a JsonTableAction. JsonTableAction is responsible to retrieve the data in the table. The setPage method is invoked each time the user moves to another page in the grid. I store the selected page in the session variable.
public void setPage(Integer page)
{
((SessionMap) session).put(“tablePageSelection”, page);
this.page = page;
}

how to use jQuery grid with struts2

September 18th, 2010

struts2-jQuery-grid is an absolutely fantastic plugin for a struts2 framework. I have used a displayTag until I discovered the jQuery. I warmly suggest you to invest some time to learn it. Your application will be much more professional after using jQuery grid.

I found a basic information about jQueryGrid here. I have downloaded the example source here and I created a new project with Netbeans and I tested a jQuery grid. It worked fine but the example also includes a hibernate plugin. Hibernate is used with a pagination functionallity. Each page fetch additional records so I also included struts2-fullhibernatecore-plugin-2.2.1-GA.jar to my project.

I have spent a lot of time to solve the following errors:
1.No Hibernate Validator class found (neither 3.x nor 4.x)
Include Hibernate-Validator.jar to your project. You can read more about that at here.

2.I did not know how to use struts-jquery-grid-tags and i18n. I have got an answer at JavaRanch.
Johannes Geppert gave me a tip:
you can use ognl like in other struts2 tags.
title=”%{getText(‘i18n.description.key’)}”

3.It took me sometime to understand how to include hibernate plugin struts2-fullhibernatecore-plugin-2.2.1-GA and json into apllication. Here are some basic steps:
a.)STRUTS.XML
a.1.)
Add hibenate-default and json-default to a package declaration in a struts.xml

a.2.)

Add an interceptor defaultStackHibernate to an action class used to prepare data for a jQuery grid

<action name=”jsontable” >
<interceptor-ref name=”defaultStackHibernate”></interceptor-ref>
<result name=”success” type=”json”>/WEB-INF/pages/tilespages/requests.jsp</result>
</action>

b.)Class json.JsonTableAction
b.1.)
JsonTableAction is used to return data which should be rendered in the jQuery grid inside a jsp page.
b.2.)
Class must have two annonations: @ParentPackage links the class with the package in a struts.xml and @Result annonates the return type as a json type.

@ParentPackage(value = "my-default")
@Result(type = "json")
public class JsonTableAction extends ActionSupport {

b.3.)
Method execute is also decorated with annonations. @Action value /jsontable is linked with an action in struts.xml.

@Actions( {
@Action(value = "/jsontable", results = {
@Result(name = "success", type = "json")
})
})
public String execute()

b.4.)
Method getGridModelJavanus is linked with a jsp page. gridModel must be populated in execute method.
I am using gridModel = RequestDao.findByCriteria(criteria, from, rows) to populate the model inside the execute method.


public List getGridModelJavanus()
{
return gridModel;
}

…..jsp

gridModel=”gridModelJavanus”
….

c.)JSP page
<!--j Q U E R Y   G R I D -->
<s:url id="remoteurl" action="jsontable" />
<sjg:grid
id="requesttable"
caption="Requests"
dataType="json"
href="%{remoteurl}"
pager="true"
navigator="true"
navigatorAddOptions="{height:280,reloadAfterSubmit:true}"
navigatorEditOptions="{height:280,reloadAfterSubmit:false}"
navigatorEdit="true"
navigatorView="true"
navigatorDelete="true"
navigatorDeleteOptions="{height:280,reloadAfterSubmit:true}"
gridModel="gridModelJavanus"
rowList="10,15,20,50"
rowNum="15"
editurl="%{editurl}"
editinline="false"
multiselect="true"
viewrecords="true">
<!--columns-->
<sjg:gridColumn
name="id"
index="id"
title="ID"
width="70"
sortable="true"
editable="true"
edittype="text"
/>

</sjg:grid>

4. I have two classes: Request and Project. Class Request has a @ManyToOne relation with a Project. Project has a @OneToMany relation with a Request. I solved the error below when I removed @OneToMany relation from the Project class.
SEVERE: Servlet.service() for servlet default threw exception
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2882)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:572)
at java.lang.StringBuilder.append(StringBuilder.java:203)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:518)
at org.apache.struts2.json.JSONWriter.string(JSONWriter.java:500)
at org.apache.struts2.json.JSONWriter.date(JSONWriter.java:401)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:156)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:130)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:336)
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:235)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:164)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:130)
at org.apache.struts2.json.JSONWriter.array(JSONWriter.java:425)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:154)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:130)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:336)
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:235)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:164)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:130)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:336)
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:235)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:164)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:130)
at org.apache.struts2.json.JSONWriter.array(JSONWriter.java:425)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:154)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:130)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:336)
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:235)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:164)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:130)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:336)

The challenges I faced programming with struts2

September 5th, 2010

I am programming with struts2 for two months. I have developed a simple application to gather user requests. I found a lot of simple example with google but I have not found any good example for a more complex application.

I will put in this post all the encountered problems. I plan to write more in detail about each issue in a separete posts. This post will be updated regularly. I will be very glad to get an answer for unsolved problems.

I have divided different features/probles into three categories: solved, NOT SOLVED and not started yet. Category “not stared yet” is used to describe the features I am planning to develop.

  • how to display a login form when the user is not logged yet – solved
  • how to use i18n with struts2 – solved
  • how to redirect to the same page after changing locale – NOT SOLVED
  • how to set a default language – solved
  • how to use a simple theme and error text – solved
  • how to put more than one field in a row within s:form – solved
  • how to use tiles – solved
  • how to use datepicker and date validation for not default date format – solved
  • how to use displaytag with i18n – solved
  • how to use form validation – solved
  • how to upload a file – not started yet
  • how to upload multiple files – not stared yet
  • how to connect struts2 application with a jasper report – not started yet
  • how to log out – solved
  • how to use jQuery grid with struts2 – solved
  • how to use jQuery grid with struts2 and returns to the selected page after refreshing a page – solved

using datetimepicker with struts2 and theme qxhtml

August 20th, 2010

It is very simple to create a form using struts2. Default theme is xhtml which supports errorfields and tooltips. I think the main disadvantage is that each textfield is placed in a separate row by default.

Label1: TextField1
Label2: TextField2

I would like to have many columns in one row.

Label1: TextField1 Label2: TextField2

I tried to use simple theme at the beginning but I found out that tooltips are not supported with a simple theme. I found the solution at http://www.vitarara.org/cms/struts_2_cookbook/creating_a_theme. It is a great page but the page is a little bit outdated,

I am using struts2 2.0.11. I copied qxhtml theme from sample application on vitavara page into my project. I succeed to put many columns in one row but there was a problem with datetimepicker. I found out that I have to modified the file datepicker.ftl to make things working. There is a change in a second row. It looks like in the old struts2 version there was a /simple/datepicker.ftl instead of /simple/datetimepicker.ftl.

<#include “/${parameters.templateDir}/${parameters.theme}/controlheader.ftl” />
<#include “/${parameters.templateDir}/simple/datetimepicker.ftl” />
<#include “/${parameters.templateDir}/qxhtml/controlfooter.ftl” />

You can use labelcolspan and inputcolspan to control the size of particular object. Example: the number of columns in a separate row is 8 columns. If we would like to put only one textfield in this row and if the label should take 1/4 then we would put 2 (2/8=1/4) for labelcolspan and 6 (6/8=3/4) for inputcolspan. Please check the code below.
IMPORTANT: Do not forget to use template=”datepicker” inside s:datetimepicker tag.

<s:datetimepicker template=”datepicker” label=”MyDate” theme=”qxhtml”>
<s:param name=”labelcolspan” value=”%{3}”/>
<s:param name=”inputcolspan” value=”%{4}”/>
</s:datetimepicker>

how to limit the text length in a TextBox using JavaFX

July 20th, 2010

I did not find any good example how to limit the text length in the TextBox control so I did it myself. Please feel free to use it.
/**
* @author www.javanus.com/AssistWeb
*/

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextBox;

Stage {
   title: "Application title"

   scene: Scene {
      width: 250
      height: 80
      content: [

         TextBox {
            override function replaceSelection(repl)
            {
            //limit text length to 5 charactes
            if (rawText.length() < 5) {
               super.replaceSelection(repl);
            }
         }
      }
    ]
   }
}

Summary row in jTable (Swing/Java)

August 31st, 2009

Summary row is used to present a total sum at the bottom of the jTable.

I have developed a grid component consists from the following components: JPanel is a basic container, jScrollPaneBasic is used to display horizontal scrollbar to handle a summary table and a data table. A data table (zebraJTable1) has another scrollPabe called jScrollPaneTabel used to display vertical scrollbar.

Picture below presents the summary row from the application.

Do not hesitate to run a demo at http://www.javanus.com/AssistWeb. Here are the steps needed to display summary rows in the application:

Manual: 
1.start the demo  
2.login as a GUEST username, password is empty 
3.select Invoices in the menu and after that select the menu item Review of cash accounts (Invoices->Review of cash accounts) 
4.click Search button to display data

PivotTable in java (Swing)

June 21st, 2009

I was looking for a PivotTable in java(swing) for a long time. I found out three different libraries for PivotTables. Lets check out each one:

1.JIDE – http://www.jidesoft.com/products/pivot.htm

JIDE software looks amazing but it is not an open source project. At the moment I am strictly “opensource” oriented so the JIDE is not the right choice. I would be very glad if they will decided to opensource their libraries. The screenshots looks great.

2.JMAGALLANES – http://sourceforge.net/projects/jmagallanes

It is an opensource project but the project is not active at the moment. The last update is from 2006. I have written an email to the authors and I have got a reply. They have told me they are planning the next release in a few months.

3.OPENSWING – http://oswing.sourceforge.net/

It is an opensource project. The project is active. I have downloaded the opensource library and the pivotTable worked fine. After a while I found a bug (http://sourceforge.net/forum/forum.php?thread_id=3296825&forum_id=572329) but Mcarniel did his job fast and well. The bug was corrected in the next week.

Below is a picture from my application which presents the use of pivotTable.

The above screen shot is from the hotel reservation software. You are free to launch a demo from http://www.javanus.com/AssistWeb/. Below are the steps used to test a PivotTable:

1.Select “Reports->Reservations” in the menu

2.Select “Search” button

Serialization, Timezones and Java Dates

June 6th, 2009

Timezone has not been kept while transfering over http.

The data are stored in the tableModel on the client side. TableModel is serialized and sent over the http to the server. The servlet on the server deserializes the data into the tableModel. TableModel is stored into the database.

My client is located in the central Europe and the server is located in the USA. The client time was Jun 06 00:00:00 CEST 2009. The data was transferred over the http and the same date on the server was Jun 05 17:00:00 CDT 2009.

Solution:

I set GMT timezone on both sides.

TimeZone tz = TimeZone.getDefault();
tz.setDefault(TimeZone.getTimeZone(“GMT”));

The client and the server date time are the same after setting default timezone: Jun 06 00:00:00 GMT 2009.

 Do not hesistate to check out a hotel reservation software using the described technology.