Search This Blog

Tuesday, December 14, 2010

Struts 2 example

Lets create a simple struts application that would involve a controller , a model and a view. The following structure exists for my project : I have downloaded the struts library and placed the jar files in lib. My codes are under src. The struts only configuration file lies in the src directory. My views are under web. To get started we need to route our incoming requests to our struts dispatcher, we do it in our web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
           version="2.5">

    <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>
</web-app>
Once this is done, we can define our controller that will handle our requests. In my case i have named it MyController and contains :

import com.opensymphony.xwork2.ActionSupport;
public class MyController extends ActionSupport {
        private User user;
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
    public String execute() throws Exception {
        this.user = new User();
        user.setId(1);
        user.setUsername("user1");
        user.setPassword("password");
        return SUCCESS;
    }
}

The above controller uses User model that i have defined in User.java :

public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

execute() is the method called when request comes to the controller. In MyController we initialize the User object and set its properties. We can also access this user object from jsp rendered by this controller, we'll c that later. Remember Object getters and setters are necessary for this to work. Controller can return different results, based on which it renders different views. For example if success is returned, required view can be rendered else if error is returned error page can be shown. We define all this in struts.xml that lies in my classspath :

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


<struts>
        <package name="test" namespace="/" extends="struts-default">
            <action name="showuser" class="MyController" >
                <result name="success">index.jsp</result>
                <result name="error">error.jsp</result>
            </action>
        </package>
</struts>
In my case i have defined only one action showuser, which will route this request to MyController which will then return a result. In case of success index.jsp will be rendered, error.jsp otherwise. Now lets show the user details which were initialized in MyController in our index.jsp :

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head><title>Simple jsp page</title></head>
  <body>
    <s:property value="user.id" />
    <s:property value="user.username" />
    <s:property value="user.password" />
  </body>
</html>
This will print the user id, username, password on the screen when we try to access http://localhost/showuser There is one more interesting thing to see over here, the auto wiring feature of struts. If we define Objects in the controller with its getter and setter and then pass the object as parameter in the url its value is automatically assigned to the object. For example if we add a String variable "message" in MyController and define setter and getter over it, we can use the url http://localhost/showuser?message=HelloWorld it will be printed on the page.

public class MyController extends ActionSupport {
        private User user;
        private String message;

    public String getMessage() {
        return message;
    }

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

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head><title>Simple jsp page</title></head>
  <body>
    <s:property value="message" />
  </body>
</html>

No comments:

Post a Comment