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.