CSDN博客

img ycl111

简单的struts实例

发表于2004/10/29 9:24:00  2014人阅读

终于把自己的这个测试做完了. 希望对想学struts的新手有所帮助.


(mystruts应用)目录结构
   mystruts
        |-WEB-INF
        |      |- lib
        |      |   |- struts.jar
        |      |- classes
        |      |      |- ConnectionPool
        |      |      |            |- getDbConnection.class
        |      |      |-mystruts
        |      |             |- user1Action.class
        |      |             |- userAction.class
        |      |             |- userActionForm.class
        |      |             |- userdao.class
        |      |-struts-bean.tld
        |      |-struts-config.xml
        |      |-struts-html.tld
        |      |-struts-logic.tld
        |      |-struts-template.tld
        |-adduser.jsp
        |-index.jsp
        |-viewuser.jsp

第一步: 开发环境配置

(如果你还没有相关软件. 请到http://www.apache.org 下载)

tomcat5.0 配置  (建立一个 mystruts 应用, 并拷贝相关文件)

请在你的tomcat安装目录中找到/conf/Catalina/localhost 子目录. 新建 mystruts.xml 文件
文件内容如下. 在这个文件中. 我们将配置一个联接池.请把相关的驱动.数据库用户,密码改成你自己的本机配置.
并把JDBC驱动拷贝一份到 Tomcat 5.0/common/lib 目录下. 请把 struts.jar /mystruts/WEB-INF/lib 目录下.

<Context path="/mystruts" docBase="D:/www/mystruts/mystruts/mystruts" debug="0" privileged="true">

  <Resource name="jdbc/TestDB"
               auth="Container"
               type="javax.sql.DataSource"/>

  <ResourceParams name="jdbc/TestDB">
    <parameter>
      <name>factory</name>
      <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>

    <parameter>
      <name>maxActive</name>
      <value>10</value>
    </parameter>

    <parameter>
      <name>maxIdle</name>
      <value>5</value>
    </parameter>

    <parameter>
      <name>maxWait</name>
      <value>10000</value>
    </parameter>

    <parameter>
     <name>username</name>
     <value>sa</value>
    </parameter>
    <parameter>
     <name>password</name>
     <value>test</value>
    </parameter>

    <parameter>
       <name>driverClassName</name>
       <value>net.sourceforge.jtds.jdbc.Driver</value>
    </parameter>

    <parameter>
      <name>url</name>
      <value>jdbc:jtds:sqlserver://192.168.10.223:1433/mystruts</value>
    </parameter>
  </ResourceParams>
</Context>

WEB-INF/web.xml  (加入struts标记库的支持)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-template.tld</taglib-location>
  </taglib>
</web-app>

第二步: 配置数据库

1.首先创建数据联接bean, 并打包到 ConnectionPool, 它将从我们配置的联接池中取得可用联接.

// Java Document
package ConnectionPool;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
import java.io.*;
import java.util.*;

public class getDbConnection {

 Connection conn;
 Statement stmt;
 ResultSet rs=null;

String foo = "Not Connected";
  int bar = -1;

  public getDbConnection() {
    try{
      Context ctx = new InitialContext();
      if(ctx == null )
          throw new Exception("Boom - No Context");

      DataSource ds =
            (DataSource)ctx.lookup(
               "java:comp/env/jdbc/TestDB");

      if (ds != null) {
        conn = ds.getConnection();

        }
      }
    catch(Exception e) {
      e.printStackTrace();
    }
 }

public Connection  getCon()
 {
   return  conn;
 }


public void d_close() throws SQLException
  {
    if (rs != null) {
      try { rs.close(); } catch (SQLException e) { ; }
      rs = null;
    }
    if (stmt != null) {
      try { stmt.close(); } catch (SQLException e) { ; }
      stmt = null;
    }
    if (conn != null) {
      try { conn.close(); } catch (SQLException e) { ; }
      conn = null;
    }

  }

protected void finalize() throws Throwable
  {
   try { d_close(); } catch (SQLException e) { ; }
  }

}

2.创建数据库. 

数据库名: mystruts

部门表: mydep

_______________________________________
dep_id           dep_name
_______________________________________
 1               dep1
 2               dep2
 3               dep3
 4               dep4
_______________________________________

用户表: myuser
______________________________________________
user_id     user_name    dep     tel
______________________________________________
 1          jack          1      0769-2454042
 2          max           2      0769-2454043
______________________________________________

(注: 以上字段为了测试方便. 全部使用字符型)


第三步:  创建ActionForm  (userActionForm.java)

 

package mystruts;  //请打包到mystruts下.

import org.apache.struts.action.*;
import javax.servlet.http.*;

public class userActionForm extends ActionForm {
  private String action="add";
  private String dep;
  private String tel;
  private String user_id;
  private String user_name;
  public String getAction() {
    return action;
  }
  public void setAction(String action) {
    this.action = action;
  }
  public String getDep() {
    return dep;
  }
  public void setDep(String dep) {
    this.dep = dep;
  }
  public String getTel() {
    return tel;
  }
  public void setTel(String tel) {
    this.tel = tel;
  }
  public String getUser_id() {
    return user_id;
  }
  public void setUser_id(String user_id) {
    this.user_id = user_id;
  }
  public String getUser_name() {
    return user_name;
  }
  public void setUser_name(String user_name) {
    this.user_name = user_name;
  }
  public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {

    return null;
  }
  public void reset(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
  }
}


第四步:建立数据库操作对象 (完成对表的增删修改与查询)

package mystruts;

import java.sql.*;
import ConnectionPool.*;
import java.util.*;

public class userdao {
  getDbConnection db=null;
  Connection con=null;

  public userdao() {
  }
  //-------------------------------------------------------------------
  public void userInsert(userActionForm uaf1)
  {
   db=new getDbConnection();
   con=db.getCon();
   userActionForm uaf=uaf1;
   PreparedStatement ps = null;
   String sql="insert into myuser (user_id,user_name,dep,tel) values(?,?,?,?)";
   try {

       ps = con.prepareStatement(sql);
       ps.setString(1,uaf.getUser_id());
       ps.setString(2,uaf.getUser_name());
       ps.setString(3,uaf.getDep());
       ps.setString(4,uaf.getTel());
       ps.executeUpdate();
        }
        catch (SQLException e)
        {
         System.out.println("sql error");
        }
       finally
       {
        try{
               con.close();
               db.d_close();
             }
        catch(Exception e) {}
        }
    }
   //---------------------------------------------
   public void userUpdate(userActionForm uaf1)
   {
   db=new getDbConnection();
   con=db.getCon();
   userActionForm uaf=uaf1;
   PreparedStatement ps = null;
   String sql="update myuser set user_name=?,dep=?,tel=? where user_id=?";
   try {

      ps = con.prepareStatement(sql);
      ps.setString(1,uaf.getUser_name());
      ps.setString(2,uaf.getDep());
      ps.setString(3,uaf.getTel());
      ps.setString(4,uaf.getUser_id());
      ps.executeUpdate();
       }
      catch (SQLException e)
      {
       System.out.println("sql error");
      }
     finally
      {
      try{
             con.close();
             db.d_close();
           }
      catch(Exception e) {}
      }
  }
 //---------------------------------------------
  public userActionForm getUser(String key)
  {
   db=new getDbConnection();
   con=db.getCon();
   ResultSet rs=null;
   userActionForm uaf=new userActionForm();
   PreparedStatement ps = null;
   String sql="select * from  myuser where user_id=?";
   try {
         ps = con.prepareStatement(sql);
         ps.setString(1,key.trim());
         rs=ps.executeQuery();
        if(rs.next())
           {
            uaf.setUser_id(rs.getString("user_id"));
            uaf.setUser_name(rs.getString("user_name"));
            uaf.setDep(rs.getString("dep"));
            uaf.setTel(rs.getString("tel"));
            uaf.setAction("edit");
           }
        }
        catch (SQLException e)
        {
         System.out.println("sql error");
        }
       finally
       {
        try{
               con.close();
               db.d_close();
             }
        catch(Exception e) {}
        }
      System.out.println("mod"+key);
     return uaf;
    }
  //----------------------------------------
  public void delUser(String key)
   {
   db=new getDbConnection();
   con=db.getCon();
   PreparedStatement ps = null;
   String sql="delete  from  myuser where user_id=?";
   try {
         ps = con.prepareStatement(sql);
         ps.setString(1,key.trim());
         ps.executeUpdate();
        }
        catch (SQLException e)
        {
         System.out.println("sql error");
        }
       finally
       {
        try{
               con.close();
               db.d_close();
             }
        catch(Exception e) {}
        }
      System.out.println("del"+key);
    }
   //----------------------------------
  public Collection getAlluser()
  {
   db=new getDbConnection();
   con=db.getCon();
   ResultSet rs=null;
   userActionForm uaf=new userActionForm();
   PreparedStatement ps = null;

   ArrayList rslist = new ArrayList();

   String sql="select * from myuser u,mydep d where u.dep=d.dep_id";
   try {
         ps = con.prepareStatement(sql);
         rs=ps.executeQuery();
        while(rs.next())
           {
            HashMap rscol = new HashMap();
            rscol.put("user_id",rs.getString("user_id"));
            rscol.put("user_name",rs.getString("user_name"));
            rscol.put("dep",rs.getString("dep"));
            rscol.put("dep_name",rs.getString("dep_name"));
            rscol.put("tel",rs.getString("tel"));
            rslist.add(rscol);
           }
        }
        catch (SQLException e)
        {
         System.out.println("sql error");
        }
       finally
       {
        try{
               con.close();
               db.d_close();
             }
        catch(Exception e) {}
        }
     return rslist;
    }
   //----------------------------------
}

第五步:建立Action  (userAction.java)

这里我们将建产两个Action .
 
userAction.java 将完成以下工作.
1.添加(前期数据准备. 主是提取部门资料.并传递给adduser.jsp)
2.修改(前期数据准备)
3.删除
4.查看所有用户资料.

user1Action.java 将完成以下工作
1.添加用户(对myuser表操作)
2.修改用户(对myuser表操作)

package mystruts;

import org.apache.struts.action.*;
import javax.servlet.http.*;
import mystruts.*;
import java.util.*;
import java.sql.*;
import ConnectionPool.*;

public class userAction extends Action {
  public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)  throws Exception
  {
   userdao dao=new userdao();
   HttpServletRequest request=httpServletRequest;
   String action;
   if(request.getParameter("action").equals("") || request.getParameter("action")==null)
   {
     action="add";
   }
   else
   {
     action=request.getParameter("action");
   }
  if(action.equals("add"))
  {
    request.setAttribute("dep",this.getDep());
    return (actionMapping.findForward("add"));
  }
  if(action.equals("edit"))
  {
   String key=request.getParameter("key");
   request.setAttribute("dep",this.getDep());
   request.setAttribute("userActionForm",dao.getUser(key));
   return (actionMapping.findForward("add"));
  }
  if(action.equals("del"))
    {
      String key=request.getParameter("key");
      dao.delUser(key);
     return (actionMapping.findForward("delview"));
    }
  if(action.equals("view"))
    {
     request.setAttribute("rs",dao.getAlluser());
     return (actionMapping.findForward("view"));
    }

   return null;
  }
  //---------------------------------------------
  public  Collection getDep()
  {
   getDbConnection db=new getDbConnection();
   Connection con=db.getCon();
   ResultSet rs=null;

   PreparedStatement ps = null;

   ArrayList rslist = new ArrayList();

   String sql="select * from mydep";
   try {
         ps = con.prepareStatement(sql);
         rs=ps.executeQuery();
        while(rs.next())
           {
            HashMap rscol = new HashMap();
            rscol.put("id",rs.getString("dep_id"));
            rscol.put("name1",rs.getString("dep_name"));
            rslist.add(rscol);
           }
        }
        catch (SQLException e)
        {
         System.out.println("sql error");
        }
       finally
       {
        try{
               con.close();
               db.d_close();
             }
        catch(Exception e) {}
        }
     return rslist;
   }
}

 

package mystruts;

import org.apache.struts.action.*;
import javax.servlet.http.*;

public class user1Action extends Action {
  public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception
  {
    userActionForm uaf = (userActionForm) actionForm;
    if(uaf.getAction().equals("add"))
    {
      new userdao().userInsert(uaf);
      return (actionMapping.findForward("view"));
    }
    if(uaf.getAction().equals("edit"))
    {
      new userdao().userUpdate(uaf);
      return (actionMapping.findForward("view"));
    }
  return null;
  }
}


第六步:建立JSP视图页面 (主要有两个jsp文件. 添加页面. adduser.jsp 查看页面 viewuser.jsp)

adduser.jsp

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-template.tld" prefix="template" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ page contentType="text/html; charset=gb2312" %>
<html:html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>
adduser
</title>
</head>
<body>
<h1>&nbsp;</h1>
<p>
<html:form action="/user1Action.do" method="POST">
<html:hidden property="action"/>
<br>
部门:
 <html:select property="dep">
     <html:options collection="dep" property="id" labelProperty="name1"/>
 </html:select>
<br>
ID:
<logic:equal name="userActionForm" property="action" scope="request" value="add">
<html:text property="user_id"/>
</logic:equal>
<logic:equal name="userActionForm" property="action" scope="request" value="edit">
<html:text property="user_id" readonly="true"/>
</logic:equal>
<br>
名字:<html:text property="user_name"/>
<br>
电话:<html:text property="tel"/>
<br>
<html:submit property="submit" value="Submit"/><br>
<html:reset value ="Reset"/>
</html:form>
</body>
</html:html>

viewuser.jsp

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-template.tld" prefix="template" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ page contentType="text/html; charset=GBK" %>
<html:html>
<head>
<title>
viewuser
</title>
</head>
<body>
<div align="center"><a href="userAction.do?action=add">add </a></div>
<table width="60%" border="1" align="center">
  <tr bgcolor="#CCCCCC">
    <td>ID</td>
    <td>user_name</td>
    <td>dep</td>
    <td>tel</td>
    <td>modify</td>
    <td>del</td>
  </tr>
  <logic:iterate name="rs" id="user" scope="request" type="java.util.HashMap">
  <tr>
    <td><bean:write name="user" property="user_id"/>&nbsp;</td>
    <td><bean:write name="user" property="user_name"/>&nbsp;</td>
    <td><bean:write name="user" property="dep_name"/>&nbsp;</td>
    <td><bean:write name="user" property="tel"/>&nbsp;</td>
    <td><a href="userAction.do?action=edit&key=<bean:write name="user" property="user_id"/>">modify</a></td>
    <td><a href="userAction.do?action=del&key=<bean:write name="user" property="user_id"/>">del</a></td>
  </tr>
  </logic:iterate>
</table>
</body>
</html:html>

建产一个转向页面 (index.jsp)
<%@ page contentType="text/html; charset=gb2312" %>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<% response.sendRedirect("userAction.do?action=view"); %>
</body>
</html>

递七步:建立struts配置文件 (WEB-INF/config-struts.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
  <form-beans>
    <form-bean name="userActionForm" type="mystruts.userActionForm" />
  </form-beans>
  <action-mappings>
    <action type="mystruts.userAction" scope="request" path="/userAction">
      <forward name="view" path="/viewuser.jsp" />
      <forward name="add" path="/adduser.jsp" />
      <forward name="delview" path="/userAction.do?action=view" />
    </action>
    <action name="userActionForm" type="mystruts.user1Action" scope="request" path="/user1Action">
      <forward name="view" path="/userAction.do?action=view" />
    </action>
  </action-mappings>
</struts-config>

运行程序:
启动tomcat
启动IE  在地址栏中输入:http://localhost:8080/mystruts

OK.....

阅读全文
0 0

相关文章推荐

img
取 消
img