分享
 
 
 

简单的struts实例

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

终于把自己的这个测试做完了. 希望对想学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.....

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有