Showing posts with label Struts2. Show all posts
Showing posts with label Struts2. Show all posts

Sunday, 31 October 2010

Ajax XML response and Struts2

Ajax and Struts2 are really cool! I really enjoy combining these two together in my web applications.
Few days ago I was working on some application, and needed to update some values in my JSP using Ajax. I decided to use XML as an Ajax response, parse it and do whatever I want with it...

In this post I will show you how to make Struts2 return XML as an Ajax response.

Here is an example of how you can do this:

public class CustomAction extends ActionSupport
{

public HttpServletResponse getResponse() 
{
        return ServletActionContext.getResponse();
}

@Override
    public String execute() throws Exception {
        PrintWriter printWriter = null;
        getResponse().setContentType("text / xml;charset = UTF-8");
        getResponse().setHeader("Cache - Control", "no - cache");
        
        StringBuffer sb = new StringBuffer("");
        // let's say you have A Movie object "movie" that needs to be represented as XML
try
        {
            printWriter = getResponse().getWriter();
            sb.append("" + movie.getDirector() + "");
            sb.append("" + movie.getLanguage() + "");
            sb.append("" + movie.getYear() + "");
            sb.append("");
            printWriter.print(sb.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
            throw e;
        }
        finally
        {
            printWriter.close();
            printWriter = null;
        }
        return NONE;
    }

} 

And that's it! Just create a PrintWriter, adjust some values in response and print your XML.

And now, in your JavaScript, you can parse this xml and do something with it:

directors=xmlhttp.responseXML.documentElement.getElementsByTagName("director");
        languages=xmlhttp.responseXML.documentElement.getElementsByTagName("language");
        years = xmlhttp.responseXML.documentElement.getElementsByTagName("year");
        director = directors[0].firstChild.nodeValue;
        language = languages[0].firstChild.nodeValue;
        year = years[0].firstChild.nodeValue;
document.getElementById('director').value=director;
document.getElementById('language').value=language;
document.getElementById('year').value=year;

That's it.
I hope I helped someone...

Wednesday, 7 October 2009

Struts2 config-browser plugin

Great thing that I recently discovered in struts2 is the ability of exploring the entire configuration that Struts2 uses to run your application by just including one .jar file - Struts2 config-browser plugin.jar

Using this plugin is quite easy…
All you need to do is to add  struts2-config-browser-plugin-2.x.x.jar to your project.
No other action is required!
Now, after you deploy your project, open config-browser by calling index.action inside config-browser namespace.

for example:

http://localhost:8084/MyApp/config-browser/index.action

After you run it, you’ll get a page containing entire configuration of you application.
You can click on any action you have mapped inside your struts.xml and see all the parameters set for it…







And not only actions!
You can explore the  struts constants too, for example…




and other things…

Try it! You could fine some interesting things, and it could actually help you when developing or maintaining application…

Thursday, 24 September 2009

Creating struts2 login page using Tomcat 6 and JNDI realm

Creating login module when using Struts2 and tomcat can be quite cool and interesting assignement, but can also be a quite annoying job if you are not familiar with all that you need to do…

When creating this module, there are several approaches. For example:

- Creating login module using container managed security
- Creating programmatic login module where you define a “database” of usernames, passwords, and roles. This way you define your login logic by yourself as well.
- Using some 3rd party library

This post describes how to configure Tomcat 6 to support container managed security, using JNDI realm.
I’ll use JNDI realm that enables application server to look for user’s information within Active Directory.

Realms are really cool!
They are, in fact, an instruction  for application server on where to look for user names, passwords and roles when a user that tries to login into your application needs to be authenticated or sometimes it’s a “database” of usernames, password and roles itself.
Great thing when using container managed security is that everything is already implemented, and all you have to do is to provide a realm and map several elements in web.xml, regarding  security.

Let’s start from the beginning.
At this moment, my web.xml file looks like this:


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>
            15
        </session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

And as for now, I put all my JSPs in the /jsp/ folder.
This is my application structure:

/ - root of  application
/jsp/  - contains JSPs
/css/main.css - contains CSS
/js/jsfile.js  - contains all of my java script code
/images/  - contains a lot of images

My task is to create a login system for this application, and to provide that only logged users , with roles “boss” or “manager” are allowed to se my JSP pages ( located in “/jsp/” folder )

To do that, the first thing we’ll do is to define (add ) roles in our web.xml.
This can be done in some other files as well, but I’ll do it here…
Note: These roles must be equal to those in active directory.

So, let’s add these two roles:

<security-role>
                <role-name>boss</role-name>
        </security-role>
        <security-role>
                <role-name>manager</role-name>
</security-role> 

Next thing we’ll do is to create a security constraint on accessing web pages:

<security-constraint>
                <web-resource-collection>
                        <web-resource-name>Protected area</web-resource-name>
                        <url-pattern>/*</url-pattern>                  
                </web-resource-collection>

                <auth-constraint>
                    <role-name>boss</role-name>
                    <role-name>manager</role-name>
                </auth-constraint>
</security-constraint>

This way, we deny acces to our resources to anyone except to those of  role “boss” or “manager”.

Next thing we need to do is to define the authentication method we will be using.
There are several authentication methods: BASIC, FORM-BASED , DIGEST , SECURE SOCKET LAYER ( SSL) and CLIENT CERTIFICATE AUTHENTICATION.

Which one to use  - depends on what exactly you need.

For us, the most  interesting method is FORM-BASED authentication.
With this method, you create your custom JSP login  form inside your application, with your own look and feel.
There are 3 very important  things to know when working with form-based authentication:

- input field containing user name must be named “j_username”
- input field containing password must be named “j_password”
- action for form containing these two inputs must be “j_security_check”


So, let’s create one!
Here is the example of such page,:

<html>
<head>
<title>Login Page for Examples</title>
<body bgcolor="white">
<form method="POST" action="j_security_check" >
  <table border="0" cellspacing="5">
    <tr>
      <th align="right">Username:</th>
      <td align="left"><input type="text" name="j_username"></td>
    </tr>
    <tr>
      <th align="right">Password:</th>
      <td align="left"><input type="password" name="j_password"></td>
    </tr>
    <tr>
      <td align="right"><input type="submit" value="Log in"></td>
      <td align="left"><input type="reset"></td>
    </tr>
  </table>
</form>
</body>
</html>

Let’s call it “login.jsp”, and place it in the root folder ( /login.jsp )

Now, let’s map it inside web.xml:

<login-config>
                <auth-method>FORM</auth-method>
                <form-login-config>
                        <form-login-page>/login.jsp</form-login-page>

                </form-login-config>
</login-config>

For now, this is good, but it’s not enough.
We also need to define a form-error-page inside a <form-login-config> tag…
Application server will open that page when user enters wrong user name or password.

Here is what I’m going to do:
I’ll define login.jsp page to be form-error-page too, but with result=false in URL.
This way we will know that we need to add some warning message to user that didn’t enter valid username and/or password.
Let’s edit that prevoius <login-config>:

<login-config>
                <auth-method>FORM</auth-method>
                <form-login-config>
                        <form-login-page>/login.jsp</form-login-page>
                        <form-error-page>/login.jsp?result=false</form-error-page>
                </form-login-config>
</login-config>

and let’s edit that login.jsp page, to show error messages when needed:

<html>
<head>
<title>Login Page for Examples</title>
<body bgcolor="white">
                     <%
                         String result = request.getParameter("result");
                         if(result == null)
                            result = "";
                         if (result.equalsIgnoreCase("false")) 
                         {
                    %>
                    <span style="color: red">
                    Wrong user name or password
                    <br>
                    </span>
                    <%       

                         }
                    %>
<form method="POST" action="j_security_check" >
  <table border="0" cellspacing="5">
    <tr>
      <th align="right">Username:</th>
      <td align="left"><input type="text" name="j_username"></td>
    </tr>
    <tr>
      <th align="right">Password:</th>
      <td align="left"><input type="password" name="j_password"></td>
    </tr>
    <tr>
      <td align="right"><input type="submit" value="Log in"></td>
      <td align="left"><input type="reset"></td>
    </tr>
  </table>
</form>
</body>
</html>

So…
We created login.jsp page, we mapped it in the web.xml  and earlier before we made an acces constraint to all of our folders so only logged users can access it.
But now question is: “what if our login page uses some image from /images/ folder in it, or some java script from within /js/ , or css from within /css/ as it  probably would?”

If we leave everything like this, your login form will not be able to read your css and images, and it will look very bad…

What we now need to do is to make some resource  public, so that our login.jsp page could use it…
To do so, we could make some existing folders public ( for example /css/ and /images/ ) ,  or we could copy particular resources ( some images and css that login.jsp needs ) to some new folder and make public only what has to be public ( what we copied ), nothing more…
We’ll do that…
Let’s call this folder “login_resources
Let’s place it in the root:

/login_resources/

Copy all the resources that you login.jsp uses to this folder.
We will now create one more security constraint that will allow everyone ( login.jsp ) to access it:

<security-constraint>
        <web-resource-collection>
        <web-resource-name>Unprotected area</web-resource-name>
        <url-pattern>/login_resources/*</url-pattern>
        </web-resource-collection>
 </security-constraint>

We intentionaly “forgot” to set <auth-constraint> inside <security-constraint> so that everyone could access this resource.

Now, our login form will be able to read all the resources it needs…

And, at the end, we need to add our JNDI  realm to our context.xml file
You could add this realm to some other files as well, but I like to add it to context.xml.

Here is one example of it:

<Realm 
 className="org.apache.catalina.realm.JNDIRealm"
 debug="99"
 connectionURL="ldap://localhost:389"
 userPattern="uid={0},ou=people,dc=mycompany,dc=com"
 roleBase="ou=groups,dc=mycompany,dc=com"
 roleName="cn"
 roleSearch="(uniqueMember={0})"
/>

Please, visit http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html for more information on creating  realms.
Place this realm inside <context>  </context> tag in context.xml file.

So, let’s sumarize:

Our web.xml now looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

     <session-config>
        <session-timeout>
            15
        </session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

<security-role>
                <role-name>boss</role-name>
        </security-role>
        <security-role>
                <role-name>manager</role-name>
</security-role> 

<security-constraint>
                <web-resource-collection>
                        <web-resource-name>Protected area</web-resource-name>
                        <url-pattern>/*</url-pattern>                  
                </web-resource-collection>

                <auth-constraint>
                    <role-name>boss</role-name>
                    <role-name>manager</role-name>
                </auth-constraint>
</security-constraint>

<security-constraint>
        <web-resource-collection>
        <web-resource-name>Unprotected area</web-resource-name>
        <url-pattern>/login_resources/*</url-pattern>
        </web-resource-collection>
 </security-constraint>

<login-config>
                <auth-method>FORM</auth-method>
                <form-login-config>
                        <form-login-page>/login.jsp</form-login-page>
                        <form-error-page>/login.jsp?result=false</form-error-page>
                </form-login-config>
</login-config>


Once the user logs in, application server will create a session for him.
You can access it’s user name with

ServletActionContext.getRequest().getUserPrincipal().getName();

or check if he has a sufficient role with

ServletActionContext.getRequest().isUserInRole(“some_role”);


And if you would like to logout, you can use

getRequest().getSession().invalidate();





That’s it for now…
I hope I helped someone and saved him some time...

Tuesday, 22 September 2009

Using simple theme and custom CSS in Struts2

Simple theme in Struts2 is great when you want to use your own CSS , and control everything by yourself when it comes to GUI.
Probably many of you (us :-) ) tried using Struts2 with your own CSS without setting default theme to SIMPLE and came up with bunch of unfamiliar tags , like

<table class="wwFormTable">

In your HTML…

Well , if you want to use your own CSS and get your application to look like you wanted to, you need to either create your own new theme ( harder ), or just use Simple theme and use your own CSS ( easier ).

In order to switch to simple theme, just copy/paste this line to your struts.properties file:

struts.ui.theme=simple


Visit
http://devtalks.blogspot.com/2009/07/create-struts2-project-in-netbeans.html
if you are using NetBeans , or

http://devtalks.blogspot.com/2009/07/eclipse-galileo-and-struts2.html
if you are using eclipse

on how to create Struts2 project , and struts.properties file

And that’s it! This way your pages will not contain those annoying
<table class="wwFormTable"> tags…


ISSUES

One thing I noticed when using simple theme is that struts tag <s:fielderror> doesn’t seems to “work” as it should…
You cannot just say, for example,

<s:fielderror />
<s:textfield name=”firstName” />

and expect from struts2 to show errors if your validator doesn’t succeed in validating filed “firstName” .
As a matter of fact, struts2 will indeed dispatch to your INPUT result, but it will not show any errors!
Fortunately , There is a solution to this problem: just use

<s:fielderror> <s:param>filed_name</s:param> </s:fielderror>
instead of
<s:fielderror />

in your .jsp pages and your validation will again act as it should…


ALTERING FieldErrors , ActionMessages and ActionErrors

Speaking of fielderrors, I often see people asking how to change the way Struts is showing field errors action messages and action errors…

You do this by extending the theme you are using. When using simple theme, all you need to do is:

- Create subfolders “template” and “simple” inside folder “classes”



- Find actionerror.ftl , actionmessage.ftl and fielerror.ftl ( or just those which you would like to extend ) in struts2-core-2.x.x.jar , inside “template.simple” package. You can find this .JAR inside your “libraries” folder.




- Copy these files to your new template -> simple folder created in earlier step.



If you open one of these files, you’ll see how these messages are generated.
You can change all that just by editing that file.

Lets say you don’t want your application to show fielderrors as <ul> <li> </li> <ul> elements.
You just need to open the fielderror.ftl and change the part that does this:

So, instead of having

like it is in original file, we can just remove <ul> <li> </li> <ul> elements, and change it with, for example, simple <span> </span> element. That will do the trick. ;-)



Or let’s, for example,change the way your Action message is shown in an application.
Let’s say we need a green box with all the action messages shown in it…
Something like this:


To do this, you could just open the actionmessage.ftl file, and change the original

<#if (actionMessages?? && actionMessages?size > 0)>
<ul<#rt/>
<#if parameters.cssClass??>
class="${parameters.cssClass?html}"<#rt/>
<#else>
class="actionMessage"<#rt/>
</#if>
<#if parameters.cssStyle??>
style="${parameters.cssStyle?html}"<#rt/>
</#if>
>
<#list actionMessages as message>
<li><span>${message!}</span></li>
</#list>
</ul>
</#if>


with something like this:


<#if (actionMessages?? && actionMessages?size > 0)>
<div class="mymessage"><br><span<#rt/>
<#if parameters.cssClass??>
class="${parameters.cssClass?html}"<#rt/>
<#else>
class="actionMessage"<#rt/>
</#if>
<#if parameters.cssStyle??>
style="${parameters.cssStyle?html}"<#rt/>
</#if>
>
<#list actionMessages as message>
<span>- ${message!}</span>
</#list>
</span><br><br></div>
</#if>

And for now on, every Action message in your application will look like a green box containing messages.

Here is the css I used:

div.mymessage
{
right: 0;
bottom: 0;
left: 0;
width:300px;
margin: auto;
color: #33CC33;
border-color:#009900;
border-style:solid ;
border-width:1px;
border-collapse: collapse;
font-weight: bold;
text-align: center;
background-color:#DDFFDD;
}


This is just a simple example what you can do with extending a theme...


Wednesday, 29 July 2009

Eclipse Galileo and Struts2

I was quite surprised with how many people came to my blog and read my earlier post on how to create a blank Struts2 project and start using this framework in NetBeans 6.5

With a release of new Eclipse, I thought it would be interesting to do the same thing, but now in this IDE.
As you probably already know, Eclipse is one of the famous and certainly one of the best Java IDEs.
Well, about a month ago people from Eclipse foundation released a 3.5 version of Eclipse, called Galileo.

I develop almost all my project using NetBeans, and have never done any Struts2 programming using Eclipse.
That is why I decided to write a post on how to create a Struts2 example in new Eclipse release: Galileo. That's quite fun because that way I (we) get to learn on how to use Struts2 in Eclipse, and get to see Galileo in action a little bit closer…

Note: In this post, I’ll use much of the text , entire source code and application logic from my previous post and concetrate only on the differences between these two IDEs.


So, let’s get started:

First of all we need Eclipse Galileo. Go to the http://www.eclipse.org/downloads/ and download Eclipse IDE for Java EE Developers.

Next thing we need is Struts2 itself. Go to http://struts.apache.org/2.x/index.html and download the latest version of Struts2.
I downloaded struts-2.1.6-all.zip
You won't be needing all the libraries in it. Just 6 of them. Because of this, you can download essential dependencies only.

When you download one of these archives, extract it to some location, for example: c:\Struts2

It is now time to start a new project. Start Eclipse Galileo.


Click file --> new --> Dynamic web project



Let’s call this project GalileoStruts2Example
I’ll use Tomcat 6 . You can use some other server that you have available , it is completely up to you.






Click Finish.

Your project tree will look like this:







Now, in order to use Struts2 libraries, let's add those essential dependencies to project:

Right-click on the project --> properties --> Java Build Path , select Libraries tab and click on the “Add External JARs” button.

Go to folder where you extracted Struts2 libraries and select ( add to project ) following files:

- struts2-core-2.1.6.jar
- freemarker-2.3.13.jar
- ognl-2.6.11.jar
- commons-fileupload-1.2.1.jar
- commons-logging-1.0.4.jar
- xwork-2.1.2.jar


Most of the tutorials on the web are written for older version of struts2, at the time when commons-fileupload-1.2.1.jar was not mandatory, so even when following all the steps in tutorial , you just couldn't get your project to work ( with newer version of Struts2 ) !

Now, your project will look like this:



Now, copy these six JARs into the “lib” folder located in the root of WEB-INF folder.






These files will be uploaded to App Server , and a deployed application will use it.
We could put this files into main lib folder of application server, but it is most probably better this way...

We need to create one more folder in the root of the WEB-INF , and name it "classes".
This is where you will create struts.xml, and if needed - a struts.properties file.

I'll put all my JSP's into new folder, "jsp" , which I will create in the root of "WebContent" folder.

All Java code that we write, we will place into some package in the "Java Resources: src" folder.
I'll create one now, called "struts2Example" and a "Hello" Class in it.
If you use validaton, put all Validation XMLs inside class's package too...






This is how, at minimum, your Struts2 project structure should look like.


I'll create one small Struts2 application now. Nothing complicated.
User will enter his name, and press "submit" and other page will open , saying Hello to this user.

So, let's first create a Java class extending ActionSupport class , named Hello, inside Struts2Example package.
Let's make it to look something like this:

package struts2Example;
import com.opensymphony.xwork2.ActionSupport;


public class Hello extends ActionSupport
{
private String name, message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return "Hello " + getName();
}
public void setMessage(String message) {
this.message = message;
}
}

We now need two JSPs, for example "nameinput.jsp" and a "response.jsp"
Each JSP needs to contain this line, in order to use struts2 custom tags in it:

<%@ taglib prefix="s" uri="/struts-tags" %>

nameinput.jsp:


response.jsp:



Let's create an XML validation file for Hello class, and make a name property mandatory.

Hello-validation.xml:

<!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="name">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Please enter name</message>
</field-validator>
</field>
</validators>


Let’s see how our project tree looks at this stage:



There's only 2 things left for us to do:

Edit struts.xml, and web.xml:

struts.xml must be located in “classes” folder located in the root of WEB-INF folder:






This is where place a file struts.properties if we need to use it, as well…

web.xml:






And if we press “Run” button, and choose a server on which it is supposed to run




we’ll get something looking like this:




But don't worry. Everything is OK, we just didin't handle default page...
If we append entername.action on the URL , our new application will open:


If we do not enter name and press “submit”:



but if we do enter name and press “Submit”:



So, I hope I helped you to understand how to create an empty struts2 project in Eclipse Galileo.

At the end, our project looked like this:





A small conclusion of mine: great thing about Eclipse is that you can do just about everything with it , with just a little few extra settings and installations...
Unfortunately, for me - many things and options remained a little bit more complicated and unintuitive regarding to some other IDEs. That is such a shame!
Nevertheless , for me , Eclipse continues to be one of the best choices!.

Enjoy Struts2 and Galileo!


Thursday, 9 July 2009

How to create Struts2 project in NetBeans

If you decide to start learning and using struts2, probably one of the first things you think about is which IDE to use, and what you need in order to create and run a Struts2 project...

If you search the web , you'll find many tutorials on how to create a struts2 project, and start developing.
This is what I did when I was starting, and soon find out that nothing I found on the web worked for me in proper manner...

So, I decided to create a small tutorial on how to create an empty struts2 project , in order to help others, and save their time.
Not to teach you Struts2, but to help you create a working Struts2 project!

Ok, I will use NetBeans 6.5, and a Tomcat 6 that comes with it...

First of all, go to http://struts.apache.org/2.x/index.html and download the latest version of Struts2.
I downloaded struts-2.1.6-all.zip
You won't be needing all the libraries in it. Just 6 of them. Because of this, you can download essential dependencies only.

When you download one of these files, extract it to some location, for example: c:\Struts2
It is now time to start a new project. Start NetBeans.

Click File -> New project -> Java web -> Web application



Let's name our project "Struts2Example". Click "next".
Choose which server you wish to use ( I selected Tomcat 6 ), set JavaEE to version 5, and leave ContextPath to be /Struts2Example

You can click "finish" now.
If you click "next" DO NOT, I repeat DO NOT choose available ( older version ) of struts under "frameworks".

Your project tree will look this:




Now, in order to use Struts2 libraries, let's add those essential dependencies to project:

Right click on "Libraries" folder and then click "Add JAR/folder". A dialog will open.
Go to folder where you extracted Struts2 libraries and select ( add to project ) following files:

- struts2-core-2.1.6.jar
- freemarker-2.3.13.jar
- ognl-2.6.11.jar
- commons-fileupload-1.2.1.jar
- commons-logging-1.0.4.jar
- xwork-2.1.2.jar


Most of the tutorials on the web are written for older version of struts2, at the time when commons-fileupload-1.2.1.jar was not mandatory, so even when following all the steps in tutorial , you just couldn't get your project to work ( with newer version of Struts2 ) !

Now, your project will loke like this:



Now, in the root of WEB-INF folder create a new folder , and name it "lib".
Copy these six JARs into this new folder.




These files will be uploaded to App Server , and a deployed application will use it.
We could put this files into main lib folder of application server, but it is most probably better this way...

We need to create one more folder in the root of the WEB-INF , and name it "classes".
This is where you will create struts.xml, and if needed - a struts.properties file.




I'll put all my JSP's into new folder, "jsp" , which I will create in the root of "Web Pages" folder.

All Java code that we write, we will place into some package in the "Source Packages" folder.
I'll create one now, called "Struts2Example" and a "Hello" Class in it.
If you use validaton, put all Validation XMLs inside class's package too...




This is how, at minimum, your Struts2 project structure should look like.


I'll create one small Struts2 application now. Nothing complicated.
User will enter his name, and press "submit" and other page will open , saying Hello to this user.

So, let's first create a Java class extending ActionSupport class , named hello, inside Struts2Example package.
Let's make it to look something like this:

package Struts2Example;

import com.opensymphony.xwork2.ActionSupport;

/**
*
* @author Darko
*/
public class Hello extends ActionSupport
{
private String name, message;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getMessage() {
return "Hello " + getName();
}

public void setMessage(String message) {
this.message = message;
}

}

We now need two JSPs, for example "nameinput.jsp" and a "response.jsp"
Each JSP needs to contain this line, in order to use struts2 custom tags in it:

<%@ taglib prefix="s" uri="/struts-tags" %>

nameinput.jsp:



response.jsp:



Let's create an XML validation file for Hello class, and make a name property mandatory.
Hello-validation.xml:

<!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="name">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Please enter name</message>
</field-validator>
</field>
</validators>

There's only 2 things left for us to do:

Edit struts.xml, and web.xml:


struts.xml:


web.xml:


and if you deploy this project to server, and open
http://localhost:8084/Struts2Example/entername.action , you'll get something like this:



If we do not enter name:



and if we do:



So, I hope I helped you to understand how to create an empty struts2 project in NetBeans.
At the end, our project looked like this:





There's more to it. For example, if you wish to override some theme's behaviour ( for example "simple" ) you create folders
template/theme_name ( for example template/simple ) and it you copy all the original files from this theme ( from struts2-core-X.X.X.jar ) and edit them in this folder...



But, some other time about that and some other usefull things...

Enjoy Struts2!

Wednesday, 17 June 2009

Struts 2 Design and Programming: A Tutorial ( Book recommendation )

There's one more book that I would like to recommend to you.
It is called, well I assume you've already guessed, Struts 2 Design and Programming: A Tutorial.



If you'd like to learn Struts2 framework, then I think this is a good place for you to start!

It is written for beginners who'd like to learn Struts2, but pros could also use it to refresh their memory on how some things could and should be done.

What thrilled me most when reading this book was the fact it was written exactly as I would like it to be...

Everything is explained very well, and there are a lot of useful examples...


You'll learn about MVC design pattern, struts2 tags, interceptors, input validations , type conversions, ajax in struts2 , tiles ,  some Tomcat settings, DAO design patterns and alot more...

I really enjoyed reading it.