Tuesday, July 19, 2011

Struts - Step3. Hello World - To start the application

Struts provides the option to configure values in properties file and use them in struts framework using the Message-resources element in struts-config.xml

Creating the Action Class

package org.mybusiness.strutstutorial.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class HelloWorldAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

        System.out.println("HelloWorld Action Invoked");
        return mapping.findForward("HelloWorld");
    }
}

Adding configurations to struts-config.xml

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

<!DOCTYPE struts-config PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
    "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>

    <!--
        Using Global Forwards to forward to the desired view for Home Page
    -->
    <global-forwards>
        <forward name="HelloWorld" path="/WEB-INF/jsp/HelloWorld.jsp" />
    </global-forwards>

    <!-- Contains the URL Mapping -->
    <action-mappings>
        <action path="/helloworld"
            type="org.mybusiness.strutstutorial.actions.HelloWorldAction" />
    </action-mappings>

    <message-resources parameter="application" />
</struts-config>

/WEB-INF/jsp/HelloWorld.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World</title>
</head>
<body bgcolor="#ffe">

<h2>Hello World. Welcome to my Struts based web application</h2>

</body>
</html>

With the above configurations deploy your web application or start the application using Eclipse WTP plugin and access the URL http://localhost:8080/StrutsTutorial/helloworld.do


No comments:

Post a Comment