Logic Empty Tag ()

empty tag – If the requested variable is either null or an empty string then we use this tag to evaluate the contents contained in the nested body parts of this tag.


Tag evaluation of the nested body content occurs only if the specified value is either absent (i.e. null), an empty string (i.e. a java.lang.String with a length of zero), or an empty java.util.Collection or java.util.Map (tested by the isEmpty() method on the respective interface).


Attributes of Empty Tag

















Attribute Name Description
name

This attribute specifies a  JSP bean variable which is required to make comparison. 

property

The variable contains the property of the bean which is required to make comparison and is specified by the name attribute. 

scope

This specifies the bean scope within which  the bean is searched  by the name property, or “any scope” if not specified.


Logic notEmpty Tag (<logic:notEmpty>…</logic:notEmpty>) 


notEmptyIf the requested variable is neither null nor an empty string then we use this tag to evaluate the contents contained in the nested body parts of this tag.


Tag evaluation of the nested body content occurs only if the specified value is available (i.e.not null) and is not an empty string (i.e. a java.lang.String with a length of zero).

Attributes of notEmpty Tag

















Attribute Name Description
name

This attribute specifies a  JSP bean variable which is required to make comparison.  

property

The variable contains the property of the bean which is required to make comparison and is specified by the name attribute. 

scope

This specifies the bean scope within which  the bean is searched  by the name property, or “any scope” if not specified.


 


Example Illustrating the use of the Empty<logic:empty> and the notEmpty <logic:notEmpty> logic tags.


Here you will learn to use the Struts  Logic tags. We will cover an example that will show  a comparison between  the two logic tags (ie..<logic:empty> and the <logic:notEmpty>).


Example code


Creating an Action  Class


Develop a simple action class EmptyAction.java.











package roseindia.net;

import java.io.*;
import java.util.*;

/**

* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email [email protected]

**/
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.*;

public class EmptyAction extends Action 
{
  public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {

      

        return mapping.findForward(“success”);
    }
}


Creating Form Bean


Our form bean class contains only one property text. Here is the code of FormBean (EmptyForm.java)











package roseindia.net;

import org.apache.struts.action.*;

/**

* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email [email protected]

**/

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

public class EmptyForm extends ActionForm 
{
    
    private String text = “”;
       
  public String getText() 
    {
        return text;
    }
    
    public void setText(String text
    {
    this.text=text;
  }
   
    
  
    
}


Defining form Bean in struts-config.xml file


Add the following entry in the struts-config.xml file for defining the form bean






<form-bean name=”EmptyForm” type=”roseindia.net.EmptyForm”/>

 Developing the Action Mapping in the struts-config.xml

Here, Action mapping helps to select the method from the Action class for specific requests.






<action path=”/EmptyAction”
type=”roseindia.net.EmptyAction”
name=”EmptyForm”
scope=”request”
input=”/pages/input.jsp”>
<forward name=”success” path=”/pages/output.jsp”/>
</action>

Developing the input.jsp page






<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>

<html:html>
<head>
<title>Using &lt;logic&gt; Tags</title>
</head>

<body>
<h1>Using &lt;logic&gt; Tags</h1>

<html:form action=”/EmptyAction” method =”post”>

<h2>Enter your name:</h2>
<html:text property=”text”/>

<br>
<br>

<html:submit value=”Submit”/>


<html:cancel/>
</html:form>
</body>
</html:html>


Developing the output.jsp page






<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>

<HTML>
<HEAD>
<TITLE>Here’s Your Data…</TITLE>
</HEAD>

<BODY>
<H3>Here’s Your Data…</H3>

<h4>The text field text:</h4>

<bean:write name=”EmptyForm” property=”text”/>

<logic:notEmpty name=”EmptyForm” property=”text” scope=”request”>
<h4>Using the tag &lt;logic:notEmpty &gt; </h4> 
Results:not Empty
</logic:notEmpty>


<logic:empty name=”EmptyForm” property=”text” scope=”request”>
<h4>Using the tag&lt;logic:empty &gt;</h4> 
Results: Empty
</logic:empty>


</BODY>
</HTML>

Add the following line in the index.jsp to call the form.


<li>
<html:link page=”/pages/input.jsp”>Struts File Upload</html:link>
<br>
Example demonstrates  how EmptyAction Class works.
</li>


Building and Testing the Example 


To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the input.jsp page. Your browser displays the following  page.


Writing nothing to the out.jsp page displays the working of  the  Empty Logic tag <logic:empty > 







 Writing nothing displays the following out.jsp page







Now  write any data to the input.jsp to see the working of  the notEmpty logic tag <logic:notEmpty >







The <logic:notEmpty > evaluated here displays the output.jsp as







Struts Logic Tags: An Introduction

Struts logic tags are conditional tags that replaces scriptlets in the jsp files.


This tag library contains tags that do the following things :
    conditional generation of the output text,
    generate iterations to output the text,
    application flow management,
    matching strings and substrings…


Logic tags available in the Struts Framework


























































Tag Name Description
empty  If the requested variable is either null or an empty string then the nested body content of this tag is evaluated
equal  If the requested variable is equal to the specified value then the nested body content of this tag is evaluated
forward  It forwards the control to the page specified by the specified ActionForward entry.
greaterEqual If the value of the requested variable is greater than or equal to the specified value then the nested body content of this tag is evaluated
greaterThan  If the value of the requested variable is greater than the specified value then the nested body content of this tag is evaluated
iterate  It repeats the nested body content of this tag over a specified collection.
lessEqual  If the value of the requested variable is less than or equal to the specified value then the nested body content of this tag is evaluated
lessThan If the value of the requested variable is less than the specified value then the nested body content of this tag is evaluated
match Evaluates the nested body content of this tag if the specified value is an appropriate substring of the requested variable.
messagesNotPresent If the specified message is not present in the request then it generates the nested body content of this tag .
messagesPresent If the specified message is present in this request then it generates the nested body content of this tag .
notEmpty If the requested variable is neither null nor an empty string nor an empty java.util.Collection (tested by the isEmpty() method on the java.util.Collection interface) then the nested body content of this tag is evaluated
notEqual If the requested variable is not equal to the specified value then the nested body content of this tag is evaluated
notMatch If the specified value is not an appropriate substring of the requested variable then the nested body content of this tag is evaluated 
notPresent If the specified value is not present in the request then it generates the nested body content of this tag .
present If the specified value is present in the request then it generates the nested body content of this tag 
redirect It renders an HTTP Redirect request.

Struts logic tags uses equal, greaterEqual, greaterThan, lessEqual, lessThan, notEqual tags to compare the values. There are rules that must be  followed :



  • Initially the specified variable needed to be compared is examined (whether it can be converted to a double or to a long). Then a  numeric (either floating point or integer) type comparison is done. If numeric conversion fails than a String comparison is performed.
  • The variable to be compared is retrieved from the request attribute(s)  that may be a cookie, header, name, parameter or property available to the specified tag. This variable is then converted to the appropriate type needed for the comparison..
  • If the variable or property to be compared returns null, it is converted into a zero-length string before the comparison occurs.
  • If the comparison logic returns a true value then only the specific comparison is performed and subsequently the nested body content is evaluated .

Struts logic tags  can also do the substring matching using the tags (match, notMatch). There are rules that must be  followed :



  • The variable to be compared is retrieved from the request attribute(s)  that may be a cookie, header, name, parameter or property available on this tag. Then this variable is converted to a String, if necessary.
  • If the retrieval of the variable fails or it contains a null value then a request time exception is thrown.  
  • The existence of the variable as a substring is examined at the position specified by the location attribute Location can be specified at the beginning (if location is set to start), at the end (if location is set to end), or anywhere (if location is not specified).

A JspException is thrown at runtime if any tag is utilized incorrectly or any invalid combination of tag attributes are used. To process the actual exception that caused the problem,  a request attribute under key org.apache.struts.action.EXCEPTION  is passed to the error page.


In the subsequent section we will show you the examples of these tags.


Struts Logic Tags

Struts Logic Tags examples.



  1. Introduction to Struts Logic Tags
    Struts logic tags are conditional tags that replaces scriptlets in the jsp files.
     

  2. Logic Empty and notEmpty Tags
    Tag evaluation of the nested body content occurs only if the specified value is either absent (i.e. null), an empty string (i.e. a java.lang.String with a length of zero)
      

  3. Logic Equal and notEqual Tags
    if the requested variable is equal to the specified value then this tag is used to evaluate the contents contained in the nested body parts of this tag
      

  4. Logic greaterEqual and greaterThan Tags
    This tag compares the variable against the specified constant value. If the variable is greater than or equal to the specified value then the nested body contents of this tag is evaluated
      

  5. Logic lessEqual and lessThan Tags
    This tag compares the variable against the specified constant value. If the variable is less than or equal to the specified value then the nested body contents of this tag is evaluated
      

  6. Logic match and notMatch Tags
    This tag matches the variable specified as a String against the specified constant value. If the value is a substring  then the nested body content of this tag is evaluated.
      

  7. Logic present and notPresent Tags
    This tag checks the current request and depending on which attribute is specified, it evaluates the nested body content of this tag only if the specified value is present.


Struts nested tag Example

The tag library 忛ested?is included in Struts 1.1. In this tutorial we are going to explain what are the features of nested tag library and how you can use it. We can manage nested beans easily with the help of struts nested tag library. 


Nested tags are used in the nested context. The Nested tags and its supporting classes extends the base struts tags and making them possible to relate to each other in the nested fashion. In case of Nested tags the original logic of the tags does not change and all the references to beans and bean properties is managed in the nested context.


As far as bean is concerned, one is associated with another internally and access to all the beans are  through the current one. The beans that refers to another is the parent and the second related to the first one is its child. Here both ‘parent’ and ‘child’ denotes a hierarchical structure of beans. 
    
For example, Take an object which represents a Author. Each author  related to many book  .If this case was translated to bean objects, 
the author object would have a reference to the book objects he wrote, and each bunch object would hold a reference to
the chapters in the books.

The author object is the parent to the books object, and the books object is a child of the author object. The books object
is parent to its child chapters objects, and the child chapters objects children of the books object. The author is higher in
the hierarchy than the books, and the chapters lower in the hierarchy to the books.



Herbert Schildt
   
Teach Yourself C++
    Java: The Complete Reference, J2SE
    Struts: the complete reference
O’Reilly
   
.NET & XML
    ADO.NET in a Nutshell
    ADO: ActiveX Data Objects

Create a new struts 1.1 project to to understand nested tags.


Object Class Books
Create a class Books with properties id and name in the package roseindia.web.common.
Add a getter and setter method for each property.
Also add  a constructor that initialize the properties.

Books.java






package roseindia.web.common;
public class Books {

private int id;
private String name;

//constructors
public Books(){}

public Books(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


Object Class Authors
Create a second java class Authors in the same package roseindia.web.common.
Add two properties, id of type int and name of type String and one property books of type Collection, which holds a list of books.
Add a getter and setter method for each property.
Also add  a constructor that initialize the properties.

Authors.java






package roseindia.web.common;
import java.util.*;
public class Authors {
	private int id;
private String name;
	//books collection
private Collection books;
	//constructors
public Authors() {}
public Authors(int id, String name, Collection books){
this.id = id;
this.name = name;
this.books = books;
}
	public Collection getBooks() {
return books;
}
public void setBooks(Collection books) {
this.books = books;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


Action form class AuthorsBooksForm
Create a java class AuthorsBooksForm in the package roseindia.web.struts.form, which extends the class ActionForm of struts.
Add a property authors of type Authors .
Add a getter and setter method for the property authors .

Implement the reset() method of the ActionForm class. 

AuthorsBooksForm.java






package roseindia.web.struts.form;
import java.util.*;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import roseindia.web.common.Authors;
import roseindia.web.common.Books;
public class AuthorsBooksForm extends ActionForm {
	Authors authors;

public void setAuthors(Authors authors) {
this.authors = authors;
}
	public Authors getAuthors() {
return authors;
}
	public void reset(ActionMapping mapping,HttpServletRequest request) {
		//initial a dummy collection of books
Collection books = new ArrayList();
		books.add(new Books(1, “Teach Yourself C++”));
books.add(new Books(2, “Java: The Complete Reference, J2SE”));
books.add(new Books(3, “Struts: The Complete Reference”));

//initial a dummy authors
authors = new Authors(1, “Herbert Schildt”, books);

}
}


Action class AuthorsBooksAction 

Create a java class AuthorsBooksAction in the package roseindia.web.struts.action, which extends the class Action of struts.
Return the forward example.

AuthorsBooksAction.java






package roseindia.web.struts.action;
import roseindia.web.struts.form.AuthorsBooksForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
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 AuthorsBooksAction extends Action {

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
AuthorsBooksForm booksForm = (AuthorsBooksForm) form;
		return mapping.findForward(“books”);
}
}


The JSP file


Create a new JSP file authorsbooks.jsp.
Add the reference to the tag library nested at the top of the file.


authorsbooks.jsp






<%@ page language=”java”%>
<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>
<%@ taglib uri=”/tags/struts-nested” prefix=”nested”%>
<html>
<head>
<title>Struts nested tag Example</title>
</head>
<body>
<h1>Struts nested tag Example</h1>
	  <b>Author and his books:</b>
<html:form action=”/example” method=”post”>
			<nested:nest property=”authors”>
				<b><nested:write property=”name”/> </b>
<nested:iterate property=”books”>
					<ul><li><nested:write property=”name”/></li></ul>
</nested:iterate>
</nested:nest>

		</html:form>
</body>
</html>


Configure the struts-config.xml


Open the struts-config.xml and add the form bean and action mapping.


struts-config.xml






 <form-beans>
<form-bean name=”AuthorsBooksForm”
type=”roseindia.web.struts.form.AuthorsBooksForm” />
</form-beans>
<action-mappings>
<action
path=”/example”
type=”roseindia.web.struts.action.AuthorsBooksAction”
input=”/pages/user/authorsbooks.jsp”
name=”AuthorsBooksForm”
scope=”request”
validate=”false”>
<forward name=”example” path=”/pages/user/authorsbooks.jsp” />
</action>
</action-mappings>



Output:
To view the output run the authorsbooks.jsp from the browser.

Developing Struts PlugIn


This article shows you how to develop custom Struts PlugIn and incorporate in your Struts Web Applications. After completing this tutorial you will be able to create your own custom PlugIn for your web application. Struts PlugIn allows the programmer to enhance their web applications. There are many PlugIns available for struts e.g. Struts Tiles PlugIn, Struts Hibernate PlugIn, Struts Spring PlugIn etc. Beside these available PlugIn you can create your own PlugIn.


Understanding PlugIn


Struts PlugIns are configured using the <plug-in> element within the Struts configuration file. This element has only one valid attribute, ‘className’, which is the fully qualified name of the Java class which implements the org.apache.struts.action.PlugIn interface.


For PlugIns that require configuration themselves, the nested <set-property> element is available.


The plug-in tag in the struts-config.xml file is used to declare the PlugIn to be loaded at the time of server start-up. Following example shows how to declare the Tiles PlugIn:


<plug-in className=”org.apache.struts.tiles.TilesPlugin”>
    <set-property
        property=”definitions-config”
           value=”/WEB-INF/tiles-defs.xml”/>
</plug-in>


The above declaration instructs the struts to load and initialize the Tiles plugin for your application on startup. 


 


 


Writing Struts PlugIn Java Code


In this example we write HelloWorld Struts PlugIn example that will give you idea about creating, configuring and checking Struts PlugIn. Our HelloWorld Stuts PlugIn contains a method called Say Hello, which simply returns HelloWorld message.


Here is code of HelloWorld Struts Plugin: 






package roseindia.net.plugin;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.struts.action.PlugIn;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ModuleConfig;

/**
@author Deepak Kumar
* @Web http://www.roseindia.net
* @Email [email protected]
*/


public class HelloWorldStrutsPlugin implements PlugIn {


    public static final String PLUGIN_NAME_KEY 
            = HelloWorldStrutsPlugin.class.getName();

   public void destroy() {
      System.out.println(“Destroying Hello World PlugIn”);
   }

   public void init(ActionServlet servlet, ModuleConfig config
throws ServletException {
      System.out.println(“Initializing Hello World PlugIn”);
   ServletContext context = null;
   context = servlet.getServletContext();
   HelloWorldStrutsPlugin objPlugin = new HelloWorldStrutsPlugin();
   context.setAttribute(PLUGIN_NAME_KEY, objPlugin);

   }

  public String sayHello(){
    System.out.println(“Hello Plugin”);
    return “Hello Plugin”;
  }
  
}


Configuring PlugIn


To configure the plugin add the following line your struts-config.xml file.


<plug-in className=”roseindia.net.plugin.HelloWorldStrutsPlugin”>
</plug-in>


Calling PlugIn From JSP Page


Here is the code for calling our PlugIn from jsp page.






<%@page contentType=”text/html” import=”java.util.*,roseindia.net.plugin.*” %>
<%

ServletContext servletContext = this.getServletContext();


HelloWorldStrutsPlugin plugin= (HelloWorldStrutsPlugin) servletContext.getAttribute
(HelloWorldStrutsPlugin.PLUGIN_NAME_KEY);

String strMessage = plugin.sayHello();


%>

Message From Plugin: <%=strMessage%>


Building and Testing


Use ant tool to build the application and then deploy on the server. Enter the url http://localhost:8080/strutstutorial/pages/plugin.jsp in your browser. It display “Hello Plugin” message. Your server console also should display “Hello Plugin” message.


In this section we learnt how to develop simple struts plugin, configure, deploy and test.

STRUTS INTERNATIONALIZATION

In this tutorial we shall see how to implement Internationalization (abbreviated as I18N) in Struts.

The Multinational Corporations have their branches in various parts of the world. so, they must provide products and services to their clients and customers in their traditional way. The customers will expect the product to work in their native languages especially the date, time, currency etc.,. So, the we should not make any assumptions about their clients region or language. If such assumptions become invalid, we have to re-engineer the applications.

Internationalization or I18N is the process of designing the software to support multiple languages and regions, so that we don’t need to re-engineer the applications every language or country needs to be supported.

Struts provides various locale sensitive JSP tags which can be used to make the applications simpler. With this short introduction we shall see how to implement i18n in a Simple JSP file of Struts.

g:\>md localedemo
g:\>cd localedemo
g:\localedemo>edit localedemo.jsp

// g:\localedemo\localedemo.jsp

<%@ page language=”java” %>

<%@ taglib uri=”/WEB-INF/struts-html.tld” prefix=”html” %>
<%@ taglib uri=”/WEB-INF/struts-bean.tld” prefix=”bean” %>
<%@ taglib uri=”/WEB-INF/struts-logic.tld” prefix=”logic” %>

<html:html locale=”true”>
<body bgcolor=pink>

<bean:message key=”index.info” />

</body>
</html:html>
————————————–



Next copy struts-blank.war to f:\tomcat41\webapps and start the tomcat with JAVA_HOME as jdk1.4. A folder named struts-blank will be created. Rename the folder as localedemo. Copy the above JSP file to f:\tomcat41\webapps\localedemo.

Now we have to edit the property files for various locales. The struts framework(struts1.1) provides a property file named application.properties. It is present in the folder f:\tomcat41\webapps\localedemo\web-inf\classes\resources. We have to add our own property file in this folder only. Our property file much be named along with the language code

For example the language code of
     1. German – de
     2. Spanish – es
     3. English – en
     4. Korean – ko
     5. French – fr
     6. Italy – it

So, when we write i18n message in German language it must be placed in property file named application_de.properties and all the properties files must be present in the resources folder only. Also when we write the property file of a particular language it need not be of the same language. For example we can create application_de.properties and write the message in french or english. In fact, the message does not depend on any language. It is a simple key value pair. The message we give for the key is just substituted. The property file to locate the value of key depends on the language settings of the browser. For this example, we will write four properties file as follows.

f:\tomcat41\webapps\localedemo\web-inf\classes\resources\ application_de.properties

index.info=GERMANY
———————————————————
f:\tomcat41\webapps\localedemo\web-inf\classes\resources\ application_es.properties

index.info=SPAIN
———————————————————–
f:\tomcat41\webapps\localedemo\web-inf\classes\resources\ application_en.properties

index.info=ENGLISH
———————————————————–
f:\tomcat41\webapps\localedemo\web-inf\classes\resources\ application_fr.properties

index.info=FRANCE
————————————————————
Also append this text in the application.properties file
    index.info=STRUTS TUTORIAL.

Now we have to add entry in the
struts-config.xml file for all the properties files. The entry and its corresponding portion is shown below.

<!– Message Resources Definitions –>

        <message-resources parameter=”resources.application_fr“/>
        <message-resources parameter=”resources.application_es“/>
        <message-resources parameter=”resources.application_en“/>
        <message-resources parameter=”resources.application_de“/>
        <message-resources parameter=”resources.application“/>

Now restart the Tomcat server. Open the Internet Explorer and type the URL as http://localhost:8080/localedemo/localedemo.jsp. We will get the message ‘ENGLAND’. This is because our default browser language is ‘United States English’.

Now we have to change the language settings of the browser to change the locale. For that, Open a new Internet Explorer, goto ‘Tools’ menu and select the ‘Internet Options’. In the ‘Internet Option’ dialog box, select ‘General’ tab and click the ‘Languages…’ button. We will get ‘Language Preference’ dialog box. There click ‘Add…’ button and add the languages. For this example add English, Spanish, German and French. Here we have languages specific to particular region. For example we have, French Belgium, French Canada, French France etc., we can select any one of these in all cases. Next select ‘German’ and by using the ‘Move up’ button, place it on the top. Now type the URL as http://localhost:8080/localedemo/localedemo.jsp. We will get the message ‘GERMAN’ Similarly place ‘Spanish’ and ‘French’ at the top, we will get the message ‘SPAIN’ and ‘FRANCE’ respectively.
—————————————————————————

Configuring Struts DataSource Manager on Tomcat 5

This tutorial shows you how you can configure Struts DataSource Manager on the Tomcat 5.5.9 server. We will use struts 1.2.7 in this tutorial. In this tutorial we will configure Struts DataSource Manager to use MySQL Database and use the connection provided by Struts DataSource in action class.


Downloading and Installing Tomcat 5.5.9
Download jakarta-tomcat-5.5.9 from http://jakarta.apache.org/tomcat/. Install it on your machine. Run and test the pages that comes with the tomcat.


Download Struts
Download Struts struts-1.2.7 from http://struts.apache.org/download.cgi and unzip it to your favorite directory. Go to the struts-1.2.7\webapps directory and then unzip struts-blank.war file. We will use this file to write our tutorial.


Download MySQL JDBC Driver
Download mysql-connector-java-3.0.16-ga-bin.jar from here mysql-connector-java-3.0.16-ga-bin.jar or you can download and use the latest version of mysql jdbc driver. Copy the JDBC driver file (mysql-connector-java-3.0.16-ga-bin.jar or latest version) to the jakarta-tomcat-5.5.9\common\lib directory of your tomcat installation. This will add the MySQL JDBC driver to the tomcat server.


Creating MySQL Database
In this tutorial I am using MySQL server installed on my local machine. You can download and install MySQL on your local machine and use for this tutorial. If you already have MySQL server then you can use the existing MySQL server.


Create database “strutsdatabase” on the MySQL server and then run the following query to create test table.






CREATE TABLE `test` (
`username` varchar(20) NOT NULL default ”
) TYPE=MyISAM;

/*Data for the table `test` */

insert into `test` values (‘rajesh’),(‘George’),(‘Vikas’),(‘Prakash’),(‘Mahesh’);


Above query creates test table and then populates the table with data.


Configuring Struts Application
Now create a directory “strutsdatabase” in the jakarta-tomcat-5.5.9\webapps\ directory and copy the content of struts-blank application (unzipped above) in the strutsdatabase directory.


Now start the tomcat and try to access the strutsdatabase application by typing the url http://localhost:8080/strutsdatabase in browser. Your browser should display the welcome page. After testing shutdown the tomcat server.


Configuring Struts DataSource Manager
The Struts DataSource manager makes it easy for your Action class get the database connection. To configure the Stuts DataSource Manager we will uncomment the <data-sources> entry in the struts-config.xml.


Uncomment and then <data-sources> entry in the struts-config.xml and then change the line


org.apache.commons.dbcp.BasicDataSource” to “org.apache.tomcat.dbcp.dbcp.BasicDataSource“. In tomcat 5.5.9 dbcp classes are packaged in naming-factory-dbcp.jar archieve, so we are using “org.apache.tomcat.dbcp.dbcp.BasicDataSource” instead of “org.apache.commons.dbcp.BasicDataSource”. After this change the database dirver, database url and passwor in the <data-sources> tag.


You <data-source> element should look like:






<data-sources>
<data-source type=”org.apache.tomcat.dbcp.dbcp.BasicDataSource“>
<set-property
property=”driverClassName”
value=”com.mysql.jdbc.Driver” />
<set-property
property=”url”
value=”jdbc:mysql://localhost:3306/strutsdatabase?autoReconnect=true” />
<set-property
property=”username”
value=”root” />
<set-property
property=”password”
value=”” />
<set-property
property=”maxActive”
value=”10″ />
<set-property
property=”maxWait”
value=”5000″ />
<set-property
property=”defaultAutoCommit”
value=”false” />
<set-property
property=”defaultReadOnly”
value=”false” />
<set-property
property=”validationQuery”
value=”SELECT COUNT(*) FROM test” />
</data-source>
</data-sources>

Create action Class to Test the DataSource
Now we will write the code of Action class for getting the connection form DataSource:





package test;

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;

import java.sql.*;

public class TestDataSource extends Action
{
  public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse responsethrows Exception{

       javax.sql.DataSource dataSource;
       java.sql.Connection myConnection=null;
       try {
        dataSource = getDataSource(request);
        myConnection = dataSource.getConnection();
        Statement stmt=myConnection.createStatement();
        ResultSet rst=stmt.executeQuery(“select username from test”);
        System.out.println(“******************************************”);
        System.out.println(“********Out Put from TestDataSource ******”);
        while(rst.next()){
        System.out.println(“User Name is: ” + rst.getString(“username”));
        }
        System.out.println(“******************************************”);
        rst.close();
        stmt.close();
        // do what you wish with myConnection
       catch (SQLException sqle) {
        getServlet().log(“Connection.process”, sqle);
       finally {
        //enclose this in a finally block to make
        //sure the connection is closed
        try {
           myConnection.close();
        catch (SQLException e) {
           getServlet().log(“Connection.close”, e);
        }
         }


      return mapping.findForward(“success”);
  }

Following code is used to get the data source and then connection from Struts DataSource:


dataSource = getDataSource(request);
myConnection = dataSource.getConnection();


Save this file(TestDataSource.java)  into jakarta-tomcat-5.5.9\webapps\strutsdatabase\WEB-INF\src\java\test directory. Add the servlet API into class path. Then open dos prompt and navigate to jakarta-tomcat-5.5.9\webapps\strutsdatabase\WEB-INF\src\ directory and issue run ant. This will compile the action class (TestDataSource.java) and copy it to the classes directory of the webapplication.


Creating Action Mapping struts-config.xml
Now add the following action mapping into the struts-config.xml:






<action
      path=”/DataSource”
      type=”test.TestDataSource”>
      <forward name=”success” path=”/success.jsp”/>
</action>

Running and testing
Start tomcat and browse the url http://localhost:8080/strutsdatabase/DataSource.do. Your browser should show the following output.



Now check tomcat console, it should display records fetched from database.


You can download my struts-config.xml from here.


Note: The DataSource manager is being retained in Struts 1.x for backward compatibility but may not be retained in Struts 2.x or later.

STRUTS ACTION – AGGREGATING ACTIONS IN STRUTS

If you are a Struts developer then you might have experienced the pain of writing huge number of Action classes for your project. The latest version of struts provides classes using which you can aggregate a related set of actions into a single unified action. In this article we will see how to achieve this. Struts provides four important classes for this purpose. These classes are called as Dispatchers. The important Dispatchers that struts provides includes : DispatchAction, ActionDispatcher , LookupDispatchAction and MappingDispatchAction.

All these classes can be found in the package org.apache.struts.actions. Let us look in to each of these in detail. Our examples use the simple CRUD actions.

DispatchAction: In this type of aggregation, the action class must extend DispatchAction class as shown.

public final class CRUDDispatchAction extends DispatchAction {

public ActionForward create(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
return (mapping.findForward(“success”));
}
… 


and the action mapping will be as 

<action path=”/crudDispatchAction” type=”com.companyname.projname.CRUDDispatchAction” name=”formName” scope=”request” input=” homeDef” parameter=”methodToCall”>
<forward name=”success” path=”targetDefName”/>
</action>


in your jsp you can call this action as 

<html:link action=”crudDispatchAction?methodToCall=create”>Create</html:link>
… 


Observe that the above class extends DispatchAction and so you cannot use this method if your class already extends your (some) super class (eg., the class where the session is validated/invalidated). Here the user has to send a query string variable (methodToCall) to set the action name to call.

ActionDispatcher: This flavor of aggregation is same as DispatchAction except that we need not extend ActionDispatcher, so we can use this method even if our class extends a super class. The following code snippet shows this scenario.


public final class CRUDActionDispatcher extends Action {

protected ActionDispatcher dispatcher = new ActionDispatcher(this, ActionDispatcher.DEFAULT_FLAVOR);

public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
return dispatcher.execute(mapping, form, request, response);
}
The DEFAULT_FLAVOR field suggests that the default parameter is “method” if none is specified as parameter in struts-config.xml (eg,. methodToCall).
ActionDispatcher flavor also needs methodToCall parameter to be set (using hidden variable or a query string) as in case of DispatchAction.

LookupDispatchAction: This type of aggregation is useful in situations where in you have multiple submit buttons in a single form. The class must extend LookupDispatchAction. However, the great thing about this type is that its java script free. That means, you need not set any hidden variables or pass query string however, you must use submit buttons as shown.

<html:submit property=”submit”><bean:message key=”button.create”/></html: submit >
<html:submit property=”submit”><bean:message key=”button.read”/></html: submit >
… 
The example Action class will be as follows 

public class CRUDLookUpDispatchAction extends LookupDispatchAction {
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put(“button.create”, “create”);
?nbsp;
return map;
}
public ActionForward create(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
return (mapping.findForward(“success”));
}
Observe the getKeyMethodMap() method. The submit button names are specified in a Map and their keys comes from MessageResources file. Struts picks up the name from this file and redirects it to the value specified in the Map. The calling code in jsp however has multiple submit buttons only differing in their names.

MappingDispatchAction: This aggregation extends MappingDispatchAction class. This is the most useful type among the four types available. But as seen in other cases, you can use this type only when your action does not extend any other action. The good thing about this type is that the action mappings can differ and so need not be the same as in all other cases. To illustrate this consider the below mappings.

<action path=”/createMappingAction” type=”com.bodhtree.CRUDMappingDispatchAction” scope=”request” input=”homeDef” parameter=”create”>
<forward name=”success” path=”targetDef”/>
</action>
<action path=”/readMappingAction” type=”com.bodhtree.CRUDMappingDispatchAction” name=” formName” scope=”request” input=”homeDef” parameter=” read”>
<forward name=”success” path=”targetDef”/>
</action> 


Notice that in the first action mapping, there is no form bean while in the second the bean name is specified. This means that the user has the flexibility to change the mapping according to his needs and hence not been contained to use a constant mapping for all the CRUD actions. Note that in all the other types of aggregations, we must use the same mapping for all the CRUD actions.

Conclusion: Each of these types has their own pros and cons. DispatchAction is the default type which uses java script and we must extend DispatchAction to use it, ActionDispatcher is same as DispathAction except that we do not extend any action , LookupDispatchAction gives the flexibility to use multiple submit buttons while MappingDispatchAction allows us to change the action mappings according to our need. So each one of these has a particular usage and which one to use depends on the user requirement.

NOD32最新升級ID nod32升级服务器 nod32下载 nod32破解版 nod32注册码


2007年9月6號

 

UserName: AV-6476241
Password: n1d7xtk7ko

UserName: AV-6488086
Password: it9gqnd33a

UserName: AV-6471366
Password: 3gufs98wcq

UserName: AV-6258073
Password: y17dhcb1f4

UserName: AV-6454441
Password: 2mo24goes2

UserName: AV-6360500
Password: 73ec6ds05r

UserName: AV-6069610
Password: p96wc7bfbh

UserName: AV-6516992
Password: ise0qj9a8y

How to fix “java.lang.OutOfMemoryError: unable to create new native thread”


I recently came across this exception on a couple of java systems that use many threads  java.lang.OutOfMemoryError: unable to create new native thread. The strange thing was that the JVM had been assigned a lot of memory (1.5GB) and that it had at least half the memory available. Michele found this article that points out that the more memory you give to the JVM the more likely you are to get java.lang.OutOfMemoryError: unable to create new native thread exceptions when you have many threads.


Which makes perfect sense when you think about it. Each 32 bit process on Windows has 2GB “available” memory as 2GB is reserved to Windows. In my case the JVM grabbed 1.5 GB leaving 500MB. Part of the 500MB was used to map system dlls etc in memory so less than 400 MB was left. Now to the crucial point: When you create a thread in java it creates a Thread object in the JVM memory but it also creates a operating system thread. The operating system creates the thread with a thread stack in the 400MB that is left, not in the 1.5 GB allocated in the JVM. Java 1.4 uses a default stack size of 256kb but Java 1.5 uses a 1MB stack per thread. So, in the 400MB left to process I could only generate ~400 threads. Absurd but true: to create more threads you have to reduce the memory allocated to the JVM. Another option is to host the JVM in your own process using JNI.


This formula gives a decent estimate for the number of threads you can create: 
(MaxProcessMemory – JVMMemory – ReservedOsMemory) / (ThreadStackSize) = Number of threads


For Java 1.5 I get the following results assuming that the OS reserves about 120MB:
1.5GB allocated to JVM: (2GB-1.5Gb-120MB)/(1MB) = ~380 threads
1.0GB allocated to JVM: (2GB-1.0Gb-120MB)/(1MB) = ~880 threads


Java 1.4 uses 256kb for the thread stack which lets you create a lot more threads:
1.5GB allocated to JVM: ~1520 threads
1.0GB allocated to JVM: ~3520 threads


I have not tried the 3GB switch but it should in theory let you create more threads.