14 - Defining namespaces in Struts with example program

Introduction:

  • In all the examples we have seen till now, we have not declared or used any namespaces.
  • This chapter will explain you the concepts of namespaces such as: what is namespace? Why to use namespace? and how to use it in our web application?

What is a Namespace?

  • In general terms, Namespaces are sections of program where a programmer can declare and use a variable or a function n number of times in a given scope.
  • As we know the concepts of core java, or C or C++, we understand that we cannot have a variable or a function declaration twice in current scope.
  • For example,
In C or C++:

void main()
  {
    int number1 = 10;
    int number1 = 20;
   }
In Java:

public static void main(String args[])
   {
   double radius = 15.0;
   double radius = 25.0;
   }
// this is not possible in any programming language.
  • The basic use of namespace is to create sub sections in a program that can support multiple declarations of variables (or functions) which does not override the previously mentioned (or declared) variables value.
  • A namespace is normally tagged under a label name which is similar to an identifier and follows its rules. The general syntax of defining namespace is:

namespace name

            {    
                // body of namespace   }

  • For example:
In C, C++ or Java:
// now this is possible.

namespace first
{
    int  number1 = 10;
}
namespace second
{
    int  number1 = 20;
}
void main()
{
      cout << “Value of number is: ” << first :: number1;
      cout << “Value of number is: ” << second :: number1;
}

//Output:
Value of number is: 10
Value of number is: 20

Namespace in Struts 2:

  • In Struts 2 framework, the use of namespace is similar as in core languages.
  • But here, namespaces are used to handle more than one module simultaneously. Modules here refer to different actions, action classes and JSP’s.
  • The web applications we have developed till now were using same namespace, which is the default namespace. (If we do not specify namespace, it refers to the default namespace).

Where to specify namespaces in struts 2?

  • Namespaces are to be defined in the configuration files, because, on click of which submit button, which action is to be executed and which method of which class is to be called is completely specified in configuration files.
  • So the namespaces are to be declared in struts.xml configuration file.

How to specify namespaces?

  • In struts.xml, namespaces can be declared by using “namespace” attribute of package element.
<package name = “Name of Package” namespace = “Name of Namespace” extends = “Name of super packages”>
  <action>
    <!—Body of action element -->
  </action>
</package>
  • For example:
<package name = “default” namespace = “/” extends = “struts-default”>
</package>
<! —In the above example, the namespace “/” specifies the root namespace or the “default” namespace.
    If you are not specifying any namespace, then also by default it is assumed as “/” namespace. -->
<package name = “first” namespace = “first_namespace” extends = “struts-default”>
</package>
<!—In this example, the namespace “first_namespace” is created under 
   “first” package and actions in this package will refer to “first_namepace”. -->

What is the use namespaces? OR Where the namespaces are reflected during program execution?

  • Namespaces are reflected in the URL of form while execution of web application. The default name space will be reflected with “/” character in form URL.
  • The general syntax for namespace is:

        http:// hostname: port number / web application name / namespace name / action name

  • For default namespace the syntax is:

        http:// hostname: port number / web application name / action name

  • The main use of namespace is to separate the JSP pages for same actions. For example, if we have a “login” action, the login page (JSP page) will be same for all the users. But based on the credentials entered and authenticated, the page will get redirected to different users’ JSP’s. So, login page and action (in login form) for manager as well as employee is same, but, based on the authentication they will be redirected to different home pages.

Example Program for Namespaces in Struts2:

  • In this example, we are going to construct a very simple web application that demonstrates the use of namespaces. The program uses a simple submit button that has an action and its mapping in struts.xml file as described in syntax above.
  • Please refer to ______________________________ for instructions to create a struts2 web application.
  • Create a folder named “jsp” inside “web pages” directory. We will be placing all our JSP pages here.
  • Also create our first JSP page that will initiate the web application. Name is as “first.jsp”.
  • And for redirecting on button click we will create another JSP named as “next.jsp”. Remember that “next.jsp” will only be used for default namespace in our program.
  • Now for redirection of action to multiple JSP’s in multiple folders, let us create three folders inside web pages along with “jsp” folder. Let us name these folders as “c”, “cpp” and “java”.
  • Also, for action let us create package “action_class” in source package folder and place a java class “course.java” in action_class package.
    • Web Application 1
      • Web Pages
        • Meta – INF
          • Context.xml
        • Web – INF
          • Web.xml
        • jsp
          • first.jsp
          • next.jsp
        • student_c
          • course_c.jsp
        • student_cpp
          • course_cpp.jsp
        • student_java
          • course_java.jsp
      • Source Packages
        • Default package
        • action_class
          • course.java
      • Libraries
        • All struts libraries
      • Configuration Files
        • MANIFEST.MF
        • Context.xml
        • Web-fragment.xml
        • Web.xml
  • So the files will be as:


first.jsp

//first.jsp
<%-- 
    Document   : first
    Created on : Nov 21, 2014, 10:07:16 AM
    Author     : Admin
--%>
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<%@taglib prefix = "s" uri = "/struts-tags" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
        <title>JSP Page</title>
    </head>
    <body>        
        <s:form action = "click">
                    Click to here view courses details
            <s:submit value = "SUBMIT"/>
        </s:form>
   </body>
</html>

course_c.jsp

//course_c.jsp
<%--
    Document   : course_c
    Created on : Nov 21, 2014, 10:07:26 AM
    Author     : Admin
--%>
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Welcome to Course C</h1>
        <h3>
           Topics to cover are:
           <ul>
               <li> Introduction </li>
               <li> Variables </li>
               <li> Functions .. </li>              
           </ul>                
        </h3>
    </body>
</html>

course_cpp.jsp

//course_cpp.jsp
<%--
    Document   : course_cpp
    Created on : Nov 21, 2014, 10:07:43 AM
    Author     : Admin
--%>
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
        <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
      <h1>Welcome to Course C++</h1>
        <h3>
           Topics to cover are:
           <ul>
               <li> Introduction </li>
               <li> Classes </li>
               <li> Objects .. </li>               
           </ul>        
        </h3>
    </body>
</html>

course_java.jsp

//course_java.jsp
<%--
    Document   : course_java
    Created on : Nov 21, 2014, 10:07:56 AM
    Author     : Admin
--%>
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1> Welcome to Course Java </h1>
        <h3>
           Topics to cover are:
           <ul>
               <li> Introduction </li>
               <li> Inheritance </li>
               <li> Polymorphism .. </li>              
           </ul>        
        </h3>
    </body>
</html>

course.java

//course.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package action_class;
import com.opensymphony.xwork2.ActionSupport;
/**
 *
 * @author Admin
 */
public class course extends ActionSupport {
    public String exec()
    {
        return "success";
    }
}

struts.xml

// struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>  
   <!-- Configuration for the default package. -->
   <package name = "default" extends = "struts-default" namespace = "/">
        <action name = "click" class = "action_class.course" method = "exec">
            <result name = "success"> jsp/next.jsp </result>
        </action>    
    </package>  
    <package name = "student_c" extends = "struts-default" namespace = "/c">
        <action name = "click" class = "action_class.course" method = "exec">
            <result name = "success"> course_c.jsp </result>
        </action>
    </package>
    <package name = "student_cpp" extends = "struts-default" namespace = "/cpp">
        <action name = "click" class = "action_class.course" method = "exec">
            <result name = "success"> course_cpp.jsp </result>
        </action>
    </package>
     <package name = "student_java" extends = "struts-default" namespace = "/java">
        <action name = "click" class = "action_class.course" method = "exec">
            <result name = "success"> course_java.jsp </result>
        </action>
    </package>
</struts>

web.xml

//web.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app version = "3.1" xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.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>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file> jsp/first.jsp </welcome-file>
    </welcome-file-list>
</web-app>
  • The first run of the application displays following:

 

Figure: welcome page (first run) of application

  • On click of submit button, the first namespace that is called is the “default” namespace. That is, the following action code from struts.xml configuration file will be executed:
<package name = "default" extends = "struts-default" namespace = "/">
     <action name = "click" class = "action_class.course" method = "exec">
            <result name = "success"> jsp/next.jsp </result>
     </action>    
</package>
  • So the output will be:

Figure: Next.jsp on “click” action of application

  • In our application, we are dealing with the same action, which is “click” action. On the click of submit button the first preference of action is given to default namespace only. So the result is next.jsp (as per mentioned in struts.xml).
  • But now if user wants to skip to courses of C or Cpp or Java, he has to call the respective namespace, which is done by URL rewriting. Say for example, for courses of c, the URL should be like:

        localhost: 8084/namespace_try/c/click

<package name = "student_c" extends = "struts-default" namespace = "/c">
        <action name = "click" class = "action_class.course" method = "exec">
            <result name = "success"> course_c.jsp </result>
        </action>
</package>
  • So the output now will be:

 

Figure: c.jsp on “click” action (for namespace “/c”)

 

  • For viewing the courses of C++, user will have to change the namespace to cpp. So the URL will be,

      localhost: 8084/namespace_try/cpp/click

  • The action element to be executed is:
<package name = "student_cpp" extends = "struts-default" namespace = "/cpp">
    <action name = "click" class = "action_class.course" method = "exec">
       <result name = "success"> course_cpp.jsp </result>
    </action>
</package>
    • So the output will be:

     

    Figure: cpp.jsp on “click” action (for namespace “/cpp”)

    • For visiting the page of courses of Java, the URL should be re-written as:

          localhost: 8084/namespace_try/java/click

    • The action element to be executed is:
    <package name = "student_java" extends = "struts-default" namespace = "/java">
       <action name = "click" class = "action_class.course" method = "exec">
          <result name = "success"> course_java.jsp </result>
            </action>
    </package>

     

    Figure: java.jsp on “click” action (for namespace “/java”)

    Things to remember for using namespace in web application:

    • Create separate folders for each of the namespace you want. That is, we have to group similar kinds of JSP’s in a single folder and then give it a label. Say for example, for a banking application, we will group all the JSP’s responsible for transaction (withdraw and deposit) under a folder and use it as a namespace.
    • It is not necessary that the name of folder for JSP should be the name of value of namespace attribute of package element. For example, in our application, the name of folder of JSP is “student_c”, “student_cpp” and “student_java”. While the value of namespace attribute is “/c”, “/cpp” and “/java” respectively.
    • The value of namespace attribute always begins with “/”. Also, simple “/” denotes default namespace. Other namespaces can be given as “/” followed by the name of namespace.
    • The URL should be re-written by namespace name only and not by JSP folder name. For example, in our application, for Java courses the URL is rewritten as:

         localhost: 8084/namespace_try/java/click

    Figure : URL rewriting in namespace

    Like us on Facebook