| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1584 人关注过本帖
标题:求助
只看楼主 加入收藏
shacky886
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2008-3-6
收藏
 问题点数:0 回复次数:8 
求助
本人刚学JAVA不久,想请教一个问题,我做了一个JSP页面,页面上有表格,现在要实现某一功能,有一个增加一行和一个保存按钮,增加的时候能够生成一行和上面表格一样的一行表格,且可以保存,可以删除,但是呢,业务逻辑只能写在页面,不能写在后台,急求,谢谢了!!!!!
搜索更多相关主题的帖子: 学JAVA 
2008-03-06 14:19
marer
Rank: 2
等 级:新手上路
威 望:3
帖 子:928
专家分:0
注 册:2005-7-18
收藏
得分:0 
建议使用Ext Js,到网上看看吧,好在我今天没什么事,给你现写个例子吧:
1、index.jsp:
<%@ page language="java" contentType="text/html;charset=utf-8"%>
<html>
<head>
    <title>表格编辑示例</title>
    <link href="JS/resources/css/ext-all.css" rel="stylesheet" type="text/css">
    <link href="Css/myCss.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="JS/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="JS/ext-all.js"></script>
    <script type="text/javascript" src="JS/source/locale/ext-lang-zh_CN.js"></script>
    <script type="text/javascript" src="JS/editgrid.js"></script>
</head>
<body>
    <a href="#"></a>
    <select id="sex" style="display:none">
        <option value="0">男</option>
        <option value="1">女</option>
    </select>
    <div id="editgrid" style="padding:10px;margin:10px"></div>
</body>
</html>

2、editgrid.js:(注意:使用utf-8编码)
Ext.onReady(function(){
    Ext.QuickTips.init();
    function formatSex(value){
        return value==0?'男':'女';       //性别渲染方法
    }
    function formatDate(value){
        return value?value.dateFormat('Y年m月d日'):'';   //日期渲染方法
    }
    var sexdata=[[0,'男'],[1,'女']];   //性别集合(用于后面添加新用户)
    //创建列模型
    var column=new Ext.grid.ColumnModel([
        {
            id:'id',
            header:'用户编号',
            dataIndex:'userid',
            width:80
        },
        {
            id:'name',
            header:'用户姓名',
            dataIndex:'username',
            width:150,
            editor:new Ext.form.TextField({allowBlank:false,blankText:'用户姓名不能为空'})   //修改模式的文本框
        },
        {
            header:'性别',
            dataIndex:'sex',
            width:80,
            editor:new Ext.({triggerAction:'all',lazyRender:true,transform:'sex'})   //修改模式的下拉框
        },
        {
            header:'生日',
            dataIndex:'birth',
            width:100,
            editor:new Ext.form.DateField({format:'Y/m/d'})   //修改模式的日期框
        }
    ]);
    //创建记录模型
    var User=new Ext.data.Record.create([
        {name:'userid',type:'string'},
        {name:'username',type:'string'},
        {name:'sex',type:'int'},
        {name:'birth',type:'date',dateFormat:'Y/m/d'}
    ]);
    //创建记录集
    var store=new Ext.data.Store({url:'DemoData',reader:new Ext.data.JsonReader({root:'data'},User),sortInfo:{field:'userid',direction:'ASC'}});
    store.load();    //填充记录
    //创建等待读取数据时的等待框
    var mask=new Ext.LoadMask('editgrid',{msg:'数据读取中...',removeMask:true});
    mask.show();    //显示
    //创建可编辑的数据表格
    var grid=new Ext.grid.EditorGridPanel({
        store:store,
        cm:column,
        title:'用户管理',
        width:800,
        height:300,
        frame:true,
        autoExpandColumn:'name',
        loadMask:mask,
        clicksToEdit:1,
        renderTo:'editgrid',
        selModel:new Ext.grid.RowSelectionModel({singleSelect:true}),
        tbar:[
            {
                text:'添加用户',
                iconCls:'add',
                handler:function(){
                    var sexstore=new Ext.data.Store({proxy:new Ext.data.MemoryProxy(sexdata),reader:new Ext.data.ArrayReader({},['value','text'])});     //得到上面的性别集合中的数据
                    sexstore.load();
                    var userid=new Ext.form.TextField({id:'userid',allowBlank:false,blankText:'用户编号不能为空',width:150,fieldLabel:'用户编号'});
                    var username=new Ext.form.TextField({id:'username',allowBlank:false,blankText:'用户姓名不能为空',width:150,fieldLabel:'用户姓名'});
                    var sex=new Ext.({id:'sex',allowBlank:false,blankText:'用户性别不能为空',triggerAction:'all',editable:false,store:sexstore,displayField:'text',valueField:'value',fieldLabel:'用户性别'});
                    var birth=new Ext.form.DateField({id:'birth',allowBlank:false,blankText:'出生日期不能为空',format:'Y/m/d',fieldLabel:'出生日期'});
                    var form=new Ext.form.FormPanel({
                        id:'f1',
                        baseCls:'x-plain',
                        labelWidth:40,
                        items:[userid,username,sex,birth]
                    });
                    var win=new Ext.Window({
                        title:'添加新用户',
                        width:300,
                        height:200,
                        minWidth:300,
                        minHeight:200,
                        layout:'fit',
                        plain:true,
                        bodyStyle:'padding:5px',
                        buttonAlign:'center',
                        items:form,
                        buttons:[
                            {
                                text:'保存',
                                handler:function(){
                                    Ext.Ajax.request({
                                        url:'AddUser',
                                        params:{userid:userid.getValue(),username:username.getValue(),sex:sex.getValue(),birth:birth.getValue().dateFormat('Y/m/d')},
                                        success:function(response,options){
                                            var arrays=Ext.util.JSON.decode(response.responseText);
                                            if(arrays.info.indexOf('成功')!=-1)
                                            {
                                                win.close();
                                                store.load();
                                            }
                                            else
                                            {
                                                Ext.Msg.alert('提示',arrays.info);
                                            }
                                       }                             
                                    });
                                }
                            },
                            {
                                text:'取消',
                                handler:function(){
                                    win.close();
                                }
                            }
                        ]
                    });
                    win.show();   //显示窗体
                }
            },
            {
                text:'查看所选',
                iconCls:'details',
                handler:function(){
                    var sel=grid.getSelectionModel().getSelected();  //得到被选中的行
                    if(sel)
                    {
                        var sex=sel.get('sex');
                        sex=(sex==0)?'男':'女';
                        var dates=sel.get('birth');
                        dates=dates.dateFormat('Y年m月d日');
                        var win=new Ext.Window({
                            title:'详细信息',
                            layout:'fit',
                            width:300,
                            height:200,
                            closeAction:'close',
                            maximizable:false,
                            plain:true,
                            autoHeight:true,
                            html:'<p class="x-window-body">用户编号:'+sel.get('userid')+'<br><br>用户名称:'+sel.get('username')+'<br><br>用户性别:'+sex+'<br><br>出生日期:'+dates+'</p>',
                            buttons:[{text:'关闭',handler:function(){
                                    win.close();
                                }
                            }]
                        });
                        win.show(this);
                    }
                    else
                    {
                        Ext.Msg.alert('提示','请选择要查看的行');
                    }
                }
            },
            {
                text:'删除所选',
                iconCls:'deleteSel',
                handler:function(){
                    var sel=grid.getSelectionModel().getSelected();
                    if(!sel){
                        Ext.Msg.alert('提示','请选择要删除的行');
                        return;   
                    }
                    Ext.Message.confirm('提示','您真的要删除所选行吗?',function(btn){
                            if(btn=='yes'){
                                Ext.Ajax.request({
                                    url:'DelUser',
                                    params:{userid:sel.get('userid'),selects:'one'},
                                    success:function(response,options){
                                        var arrays=Ext.util.JSON.decode(response.responseText);
                                        if(arrays.info==true)
                                        {
                                            Ext.Msg.alert('提示','已成功删除用户');
                                            store.remove(sel);
                                        }
                                        else
                                        {
                                            Ext.Msg.alert('提示','未知原因,未能删除用户');
                                        }
                                    }
                                });
                            }
                        }
                }
            },
            {
                text:'删除所有',
                iconCls:'deleteAll',
                handler:function(){
                    var count=grid.getStore().getCount();
                    if(count<=0)
                    {
                        Ext.Msg.alert('提示','没有任何数据进行删除');
                        return;
                    }
                    Ext.Message.confirm('提示','确认要删除全部数据吗?',function(btn){
                        if(btn=='yes'){
                            Ext.Ajax.request({
                                url:'DelUser',
                                params:{userid:'',selects:'all'},
                                success:function(response,optins){
                                    var arrays=Ext.util.JSON.decode(response.responseText);
                                    if(arrays.info==true){
                                        Ext.Msg.alert('提示','已成功删除所有数据');
                                        store.removeAll();
                                    }
                                    else{
                                        Ext.Msg.alert('提示','未知原因,未能删除所有数据');
                                    }
                                }
                            });
                        }
                    }
                }
            },
            {
                text:'保存修改',
                iconCls:'save',
                handler:function(){
                  grid.stopEditing();    //停止编辑
                Ext.Msg.wait('保存数据','正在保存数据,请稍等...');
                var records=grid.getStore().getModifiedRecords();   //得到所有已修改的行
                var count=records.length;
                var paras="";
                if(count>0)
                {
                    for(var i=0;i<count;i++)
                    {
                    var dates=records[i].get('birth');
                        dates=dates.dateFormat('Y/m/d');
                    paras+=records[i].get('userid')+"@"+records[i].get('username')+"@"+records[i].get('sex')+"@"+dates+",";
                    }
                    paras=paras.substring(0,paras.length-1);
                    Ext.Ajax.request({
                    url:'SaveMotify',
                    params:{paras:paras},
                    success:function(response,options){
                        var arrays=Ext.util.JSON.decode(response.responseText);
                        if(arrays.info==true)
                        {
                            Ext.Msg.alert('提示','已成功保存修改,共修改了'+arrays.count+'条记录');
                            grid.getStore().commitChanges();
                        }
                        else
                        {
                            Ext.Msg.alert('提示','未成功保存全部修改,共修改了'+arrays.count+'条记录');
                        }
                            }
                    });
                    }
                    else{
                        Ext.Msg.alert('提示','没有任何需要更新的数据');
                    }
                }
            }
        ]
    });
});

3、CSS文件(myCss.css):里面只写了工具栏中五个按钮的图片路径
.add{background-image:url(../Images/add.gif)!important}
.detail{background-image:url(../Images/detail.gif)!important}
.deleteSel{background-image:url(../Images/deleteSel.gif)!important}
.deleteAll{background-image:url(../Images/deleteAll.gif)!important}
.save{background-image:url(../Images/save.gif)!important}

public class 人生历程 extends Thread{public void run(){while(true){努力,努力,再努力!!;Thread.sleep(0);}}}
2008-03-06 15:37
marer
Rank: 2
等 级:新手上路
威 望:3
帖 子:928
专家分:0
注 册:2005-7-18
收藏
得分:0 
4、后台读取数据Servlet(DemoData.java):
package com.liz;
import *;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoData extends HttpServlet
{
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    {
        response.setContentType("text/html;charset=utf-8");
        try
        {
        Connection con=ConToDb.getDemoCon();
        String info="{data:[";
        if(con!=null)
        {
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery("select * from Info");
        while(rs.next())
        {
                 info+="{userid:'"+rs.getString(1)+"'";
            info+=",username:'"+rs.getString(2)+"'";
            info+=",sex:"+rs.getInt(3);
            info+=",birth:'"+rs.getString(4)+"'}";
            info+=",";
        }
        rs.close();
        stmt.close();
        con.close();
        info=info.substring(0,info.length()-1);
        info+="]}";
        PrintWriter out=response.getWriter();
        out.print(info);
        }
        }
        catch(Exception er)
        {
            er.printStackTrace();
        }
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    {
        doGet(request,response);
    }
}

5、后台数据库连接类:
package com.liz;
import java.sql.*;
public class ConToDb
{
    public static Connection getDemoCon()
    {
        Connection con=null;
        try
        {
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            con=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:2206;user=sa;password=sa;databasename=DemoData");
            return con;
        }
        catch(Exception er)
        {
            er.printStackTrace();
            return null;
        }
    }
}

6、后台添加用户Servlet(AddUser.java):
package com.liz;
import *;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddUser extends HttpServlet
{
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String userid=request.getParameter("userid");
        String username=request.getParameter("username");
        String strsex=request.getParameter("sex");
        String birth=request.getParameter("birth");
        String result="";
        int sex=-1;
        try
        {
            sex=Integer.parseInt(strsex);
        }
        catch(Exception er)
        {
            result="{info:'您选择的用户性别不是有效的性别名称'}";
            PrintWriter out=response.getWriter();
            out.print(result);
            return;
        }
        if(birth.length()!=10)
        {
            result="{info:'您输入的出生日期不是有效的日期格式,正确的格式是:yyyy/mm/dd'}";
            PrintWriter out=response.getWriter();
            out.print(result);
            return;
        }
        if(birth.indexOf('/')==-1)
        {
            result="{info:'您输入的出生日期不是有效的日期格式,正确的格式是:yyyy/mm/dd'}";
            PrintWriter out=response.getWriter();
            out.print(result);
            return;
        }
        String tmpbirth=birth.substring(0,4);
        try
        {
            int bir=Integer.parseInt(tmpbirth);
            if(bir<1908 || bir>1990)
            {
                result="{info:'您输入的出生日期不能小于1908年或者大于1990年'}";
                PrintWriter out=response.getWriter();
                out.print(result);
                return;
            }
        }
        catch(Exception er)
        {
            result="{info:'您输入的出生日期不是有效的日期格式,正确的格式是:yyyy/mm/dd'}";
            PrintWriter out=response.getWriter();
            out.print(result);
            return;
        }
        Connection con=ConToDb.getDemoCon();
        boolean hasID=false;
        try
        {
            if(con!=null)
            {
                Statement stmt=con.createStatement();
                ResultSet rs=stmt.executeQuery("select userid from Info where userid='"+userid+"'");
                if(rs.next())
                {
                    hasID=true;
                }
                rs.close();
                if(hasID)
                {
                    result="{info:'您输入的用户编号已存在'}";
                }
                else
                {
                    stmt.execute("insert into Info values('"+userid+"','"+username+"',"+sex+",'"+birth+"')");
                    stmt.close();
                    con.close();
                    result="{info:'已成功添加新用户["+username+"]'}";
                }
            }
        }
        catch(Exception er)
        {
            result="{info:'"+er.getMessage()+"'}";
            er.printStackTrace();
        }   
        finally
        {
            try
            {
                if(!con.isClosed())
                    con.close();
            }
            catch(Exception er)
            {
                er.printStackTrace();
            }
        }
        PrintWriter out=response.getWriter();
        out.print(result);
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response)     throws ServletException,IOException
    {
        doGet(request,response);
    }
}

7、后台删除用户Servlet(DelUser.java):
package com.liz;
import *;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DelUser extends HttpServlet
{
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    {
        request.setCharacterEncoding("utf-8");
        String userid=request.getParameter("userid");
        String selects=request.getParameter("selects");
        String info="";
        if(selects.equals("one"))
        {
            try
            {
                Connection con=ConToDb.getDemoCon();
                if(con!=null)
                {
                    Statement stmt=con.createStatement();
                    stmt.execute("delete from Info where userid='"+userid+"'");
                }
                info="{info:true}";
            }
            catch(Exception er)
            {
                info="{info:false}";
                er.printStackTrace();
            }
        }
        else if(selects.equals("all"))
        {
            try
            {
                Connection con=ConToDb.getDemoCon();
                if(con!=null)
                {
                    Statement stmt=con.createStatement();
                    stmt.execute("delete from Info");
                }
                info="{info:true}";
            }
            catch(Exception er)
            {
                info="{info:false}";
                er.printStackTrace();
            }
        }
        PrintWriter out=response.getWriter();
        out.print(info);
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    {
        doGet(request,response);
    }
}

8、后台保存数据Servlet(SaveMotify.java):
package com.liz;
import *;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SaveMotify extends HttpServlet
{
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String paras=request.getParameter("paras");
        String info="";
        int finish=0;
        String[] oneParas=paras.split(",");
        int count=oneParas.length;
        for(int i=0;i<count;i++)
        {
            String[] field=oneParas[i].split("@");
            Connection con=ConToDb.getDemoCon();
            try
            {
                String id=field[0];
                String name=field[1];
                String sex=field[2];
                String birth=field[3];
                if(con!=null)
                {
                    Statement stmt=con.createStatement();
                    stmt.execute("update Info set username='"+name+"',sex="+sex+",birth='"+birth+"' where userid='"+id+"'");
                    stmt.close();
                    con.close();
                    finish++;
                }
            }
            catch(Exception er)
            {
                er.printStackTrace();
            }
            finally
            {
                try
                {
                    if(!con.isClosed())
                        con.close();
                }
                catch(Exception er)
                {
                    er.printStackTrace();
                }
            }
        }
        if(finish==count)
        {
            info="{info:true,count:"+finish+"}";
        }
        else
        {
            info="{info:false,count:"+finish+"}";
        }
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    {
        doGet(request,response);
    }

}

public class 人生历程 extends Thread{public void run(){while(true){努力,努力,再努力!!;Thread.sleep(0);}}}
2008-03-06 16:04
marer
Rank: 2
等 级:新手上路
威 望:3
帖 子:928
专家分:0
注 册:2005-7-18
收藏
得分:0 
以上代码为临时手输,如有拼写或括号错误,请谅解

public class 人生历程 extends Thread{public void run(){while(true){努力,努力,再努力!!;Thread.sleep(0);}}}
2008-03-06 16:05
shacky886
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2008-3-6
收藏
得分:0 
多谢
2008-03-06 23:30
带头大哥
Rank: 1
等 级:新手上路
帖 子:39
专家分:0
注 册:2008-3-2
收藏
得分:0 
2楼能把项目文件打个包发上来吗,直接能跑起来的,学习一下
2008-03-07 00:25
marer
Rank: 2
等 级:新手上路
威 望:3
帖 子:928
专家分:0
注 册:2005-7-18
收藏
得分:0 
不好意思,我不是不想分享,只是上面的代码真的是我在没事的时候纯手敲上去的,没有做工程项目,如果要做的话,我又要重写一次,工程量较大。如果想跑起来请到Ext JS的主站上下载相关包,然后在Eclipse中创建项目,把上面的代码贴进去就行了。实在不好意思!

public class 人生历程 extends Thread{public void run(){while(true){努力,努力,再努力!!;Thread.sleep(0);}}}
2008-03-07 09:39
marer
Rank: 2
等 级:新手上路
威 望:3
帖 子:928
专家分:0
注 册:2005-7-18
收藏
得分:0 
另外需要查询后台sqlserver数据库,新建一个库,名称为:DemoData,在库中建一个表:Info,表字段是:
userid    varchar    50    not null  主键
username  varchar    50    not null
sex       int        4     not null
birth     varchar    50     not null
注意:表中的数据格式:举例:001  abc  0  2008/08/05
一定注意日期字段的格式为YYYY/MM/DD,否则前台显示不出来

public class 人生历程 extends Thread{public void run(){while(true){努力,努力,再努力!!;Thread.sleep(0);}}}
2008-03-07 09:46
shacky886
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2008-3-6
收藏
得分:0 
哎!

可怜呀!所有的业务逻辑都要写在页面我恐怖呀!

该怎么弄呀,急死了!
2008-03-07 10:29
快速回复:求助
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.036423 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved