作业: 联系人管理

1.index.jsp联系人页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="com.hanqi.dao.*" %>
    <%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>联系人</title>

<script src="js/jquery-2.1.4.min.js"></script>


<%
contactsDal md = new contactsDal();


ArrayList<contacts> al = md.getList(0);
%>
<script>
function check()
{
    var name = document.getElementById("name");
    
    if(name.value == null || name.value.trim().length ==0)
        {
        alert("姓名不能为空")
        return false;
        }    

        var el = /\d{11}/;
        
        var tel = document.getElementById("tel");

        if(tel.value != null && tel.value.trim().length == 0 && !el.test(tel.value))
            {
            alert("手机号码必须是11位数,电话为区号+号码11位数.");
            return false;
            }
            
    return true;
}

function confirmDelete()
{
    return(confirm("确认要删除该记录么?"));

}
</script>


</head>
<body>

<table border=1>
<tr>
<td></td>
<td>姓名</td>
<td>电话</td>
<td>分组</td>
</tr>


<% 
if(al != null)
{
    for(contacts c : al)
    {
    %>
    <tr>
    <td><a href='Update.jsp?id=<%=c.getId() %>'>编辑</a> <a onclick="return confirmDelete()" href='DeleteContacts?id=<%=c.getId()%>'>删除</a></td>
    <td><%=c.getName()%></td>
    <td><%=c.getTel() %></td>
    <td>
             <%
             int gid = c.getGroupid(); 
             //实例化数据操作类
             groupDal gd1 = new groupDal();
             
             group g1 = gd1.getGroup(gid);

             out.print(g1.getName());

             %>
             </td>
    </tr>
<% 

}
}
%>


</table>

<input id="qwe" type="button" value="添加新号码" onclick="$('#zxc,#qwe').toggle(500);" />

<form id="zxc" style="display:none" method='POST' action='InsertContacts' onsubmit="return check()">
姓名:<input id='name' name='name' type="text" width=30/><br>
电话:<input id='tel' name='tel' type="text" width=30  maxlength=11/><br>
分组:
<select id='groupid' name='groupid'>
<%
groupDal gd = new groupDal();


ArrayList<group> al2 = gd.getGrouplist(0);
if(al2 != null)
{
    for(group g : al2)
    {
%>
<option value=<%=g.getId() %>><%=g.getName() %></option>
<%
}
}

%>

</select>
<br>
<input type="submit" value="添加" />
</form>

</body>
</html>
index.jsp

2.Update.jsp编辑页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="com.hanqi.dao.*" %>
    <%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改联系人</title>

<script src="js/jquery-2.1.4.min.js"></script>

<script>
function check()
{
    var name = document.getElementById("name");
    
    if(name.value == null || name.value.trim().length ==0)
        {
        alert("姓名不能为空")
        return false;
        }    

        var el = /\d{11}/;
        
        var tel = document.getElementById("tel");

        if(tel.value != null && tel.value.trim().length == 0 && !el.test(tel.value))
            {
            alert("手机号码必须是11位数,电话为区号+号码11位数.");
            return false;
            }
            
    return true;
}
</script>



</head>
<body>
<%

//接收参数id
     String id = request.getParameter("id");
 
     if(id == null || id.trim().length() == 0)
     {
         out.print("id为空");
         response.setHeader("refresh","5;url=index.jsp");
     }
     else{
     //查询联系人信息
     //实例化Contacts
     contacts c = new contacts();
     //实例化数据库操作类
     contactsDal cd = new contactsDal();
     
     c = cd.getContacts(Integer.parseInt(id));
     try{
%>

<form action="EditContacts?id=<%=c.getId() %>" method='POST' onsubmit='return check()'>
姓名:<input id='name' name='name' type="text" width=30 value='<%=c.getName() %>' /><br>
电话:<input id='tel' name='tel' type="text" width=30 maxlength=11 value='<%=c.getTel() %>' /><br>
分组:
<select id='groupid' name='groupid'>
<%}catch(Exception e)
     {
    response.getWriter().append(e.getMessage());
     }
groupDal gd = new groupDal();


ArrayList<group> al2 = gd.getGrouplist(0);
if(al2 != null)
{
    for(group g : al2)
    {
%>
<option value=<%=g.getId() %> <%= ((c.getGroupid()==g.getId())? "selected" : "" ) %>><%=g.getName() %></option>
<%
}
}
     }
%>
</select>
<br>
<input type='submit' value='修改'/>
</form>


</body>
</html>
Update.jsp

3.DBHelper.java数据库连接工具类

package com.hanqi.dao;

import java.sql.*;


public class DBHelper {
    
    public static Connection getConnection() throws Exception
    {
        //加载驱动
        Class.forName("oracle.jdbc.driver.OracleDriver");
        
        //创建URL
        String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
        
        //驱动管理
        Connection conn = DriverManager.getConnection(url,"test1","test1");
        
        return conn;
    }


}
DBHelper.java

4.contacts.java封装联系人信息的实体类

package com.hanqi.dao;

public class contacts {

    //id
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    //name
    private String name;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //tel
    private String tel;    
    
    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    //groupid
    private int groupid;
    
    public int getGroupid() {
        return groupid;
    }

    public void setGroupid(int groupid) {
        this.groupid = groupid;
    }


}
contacts.java

5.group.java封装分组信息的实体类

package com.hanqi.dao;

public class group {

    //id
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


    //name
    private String name;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
group.java

6.contactsDal.java联系人的数据库操作类

package com.hanqi.dao;

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


public class contactsDal {

    //
        public int insert(contacts c) throws Exception
        {
            int rtn = -1;
            
            Connection conn = DBHelper.getConnection();
            
            PreparedStatement pst = null;
            
            if(conn != null)
            {
                try
                {
                String sql = "insert into contacts (id,name,tel,groupid) values (sq_members_id.nextval,?,?,?)";
                
                pst = conn.prepareStatement(sql);
                
                pst.setString(1, c.getName());
                pst.setString(2, c.getTel());
                pst.setInt(3, c.getGroupid());
                
                rtn = pst.executeUpdate();
                }
                catch(Exception ex)
                {
                    throw ex;
                }
                finally{
                    try{
                
                pst.close();}
                catch(Exception ex){}
                conn.close();
                }
            }
            
            return rtn;
        }
        
        //
            public ArrayList<contacts> getList(int id) throws Exception
            {
                ArrayList<contacts> rtn = new ArrayList<contacts>();
                    
                Connection conn = DBHelper.getConnection();
                    
                PreparedStatement pst = null;
                    
                ResultSet rs = null;
                    
                if(conn != null)
                {
                    try
                    {
                    String sql = "select * from contacts";
                        
                    pst = conn.prepareStatement(sql);

                    rs = pst.executeQuery();
                    if(rs != null)
                    {
                        //遍历
                        while(rs.next())
                        {
                            //实例化实体类
                            contacts m = new contacts();
                                
                            m.setId(rs.getInt("ID"));//取值
                            m.setName(rs.getString("name"));//取值
                            m.setTel(rs.getString("tel"));
                            m.setGroupid(rs.getInt("groupid"));
                                
                            rtn.add(m);

                        }
                    }
                    }
                    catch(Exception ex)
                    {
                        throw ex;
                    }
                    finally{
                        try{
                        
                    pst.close();}
                    catch(Exception ex){}
                    conn.close();
                    }
                }
                    
                
                return rtn;
            }

            //
            public int delete(contacts c) throws Exception
            {
                int rtn = -1;
                
                Connection conn = DBHelper.getConnection();
                
                PreparedStatement pst = null;
                
                if(conn != null)
                {
                    try{
                    String sql = "delete from contacts where id = ?";
                    
                    pst = conn.prepareStatement(sql);
                    
                    pst.setInt(1,c.getId());
                    
                    rtn = pst.executeUpdate();
                    }
                    catch(Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        try{
                    pst.close();}
                        catch(Exception ex){}
                    conn.close();
                        }
                    
                }
                return rtn;
            }
            
            //
            public int update(contacts c) throws Exception
            {
                int rtn = -1;
                
                Connection conn = DBHelper.getConnection();
                
                PreparedStatement pst = null;
                
                if(conn != null)
                {
                    try
                    {
                    String sql = "update contacts set name = ?, tel = ? ,groupid = ? where id = ?";
                    
                    pst = conn.prepareStatement(sql);
                    
                    pst.setString(1, c.getName());
                    pst.setString(2, c.getTel());
                    pst.setInt(3, c.getGroupid());
                    pst.setInt(4,c.getId());
                
                    rtn = pst.executeUpdate();
                    }
                    catch(Exception ex)
                    {
                        throw ex;
                    }
                    finally{
                        try{
                    
                    pst.close();}
                    catch(Exception ex){}
                    conn.close();
                    }
                }
                
            
                return rtn;
            }
            
            //单条查询
            public contacts getContacts(int id) throws Exception
            {
                contacts rtn = null;
                
                //获取
                
                Connection conn = DBHelper.getConnection();
                
                PreparedStatement pst = null;
                
                ResultSet rs = null;
                
                if(conn != null)
                {
                    try
                    {
                    String sql = "select * from contacts where id=?";
                    
                    pst = conn.prepareStatement(sql);

                    pst.setInt(1,id);
                    
                    rs = pst.executeQuery();
                    if(rs != null && rs.next())
                    {

                            //初始化
                            rtn = new contacts();
                            //实例化实体类
                            rtn.setId(rs.getInt("ID"));//取值
                            rtn.setName(rs.getString("name"));//取值
                            rtn.setTel(rs.getString("tel"));
                            rtn.setGroupid(rs.getInt("groupid"));

                    }
                    }
                    catch(Exception ex)
                    {
                        throw ex;
                    }
                    finally{
                        try{
                    
                    pst.close();}
                    catch(Exception ex){}
                    conn.close();
                    }
                }
                
                return rtn;
            }
        
}
contactsDal

7.groupDal.java分组信息的数据库操作类

package com.hanqi.dao;

import java.sql.*;

import java.util.*;

public class groupDal {
    //
    public ArrayList<group> getGrouplist(int id) throws Exception
    {
        ArrayList<group> rtn = new ArrayList<group>();
            
        Connection conn = DBHelper.getConnection();
            
        PreparedStatement pst = null;
            
        ResultSet rs = null;
            
        if(conn != null)
        {
            try
            {
            String sql = "select * from groups";
                
            pst = conn.prepareStatement(sql);

            rs = pst.executeQuery();
            if(rs != null)
            {
                //遍历
                while(rs.next())
                {
                    //实例化实体类
                    group g = new group();
                        
                    g.setId(rs.getInt("ID"));//取值
                    g.setName(rs.getString("name"));//取值

                        
                    rtn.add(g);

                }
            }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally{
                try{
                
            pst.close();}
            catch(Exception ex){}
            conn.close();
            }
        }
            
        
        return rtn;
    }
    
    //单条查询
    public group getGroup(int id) throws Exception
    {
        group rtn = null;
        
        //获取
        
        Connection conn = DBHelper.getConnection();
        
        PreparedStatement pst = null;
        
        ResultSet rs = null;
        
        if(conn != null)
        {
            try
            {
            String sql = "select * from groups where id=?";
            
            pst = conn.prepareStatement(sql);

            pst.setInt(1,id);
            
            rs = pst.executeQuery();
            if(rs != null && rs.next())
            {

                    //初始化
                    rtn = new group();
                    //实例化实体类
                    rtn.setId(rs.getInt("ID"));//取值
                    rtn.setName(rs.getString("name"));//取值


            }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally{
                try{
            
            pst.close();}
            catch(Exception ex){}
            conn.close();
            }
        }
        
        return rtn;
    }


}
groupDal.java

8.InsertContacts.java添加联系人

package com.hanqi;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hanqi.dao.*;
/**
 * Servlet implementation class InsertContacts
 */
@WebServlet("/InsertContacts")
public class InsertContacts extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InsertContacts() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        //转换中文字符防止出现乱码
                request.setCharacterEncoding("UTF-8");
                        
                response.setContentType("text/html;charset=UTF-8");
                        
                response.setCharacterEncoding("UTF-8");
                
                String name = request.getParameter("name");        
                String tel = request.getParameter("tel");
                String gi = request.getParameter("groupid");
                
                if(name == null || name.trim().length() == 0)
                {
                    response.getWriter().append("姓名不能为空");
                }
                else
                {
                    //get方式
                    //name = new String(name.getBytes("ISO-8859-1"),"UTF-8");
                    
                    if(tel != null && tel.trim().length() > 0)
                    {
                        if(gi != null && gi.trim().length() > 0)
                        {
                        contacts c = new contacts();
                        
                        c.setGroupid(Integer.parseInt(gi));
                        c.setName(name);
                        c.setTel(tel);
                        //调用模型层
                        
                        contactsDal cd = new contactsDal();
                        
                        try{

                                cd.insert(c);

                            }catch(Exception e){
                                response.getWriter().append("保存数据失败");
                                e.printStackTrace();
                            }
                        
                        
                    }
                    }

                    else
                    {
                        response.getWriter().append("电话号码不能为空");
                    }
                    
                    }
                response.sendRedirect("index.jsp");
    }
                

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
InsertContacts.java

9.DeleteContacts.java删除联系人

package com.hanqi;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import com.hanqi.dao.*;


/**
 * Servlet implementation class DeleteContacts
 */
@WebServlet("/DeleteContacts")
public class DeleteContacts extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteContacts() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        
        response.setContentType("text/html;charset=UTF-8");
        
        response.setCharacterEncoding("UTF-8");
        
        String id = request.getParameter("id");
        
        if(id != null && id.trim().length() > 0)
        {
        contacts c = new contacts();

        contactsDal cd = new contactsDal();
        
        c.setId(Integer.parseInt(id));
        
        try{
            cd.delete(c);
            response.sendRedirect("index.jsp");
        }catch(Exception e){
            response.getWriter().append("删除数据失败");
            e.printStackTrace();
        }
        }
        else
        {
            response.getWriter().append("ID不能为空");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
DeleteContacts.java

10.EditContacts.java编辑联系人

package com.hanqi;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hanqi.dao.*;
import java.sql.*;


/**
 * Servlet implementation class EditContacts
 */
@WebServlet("/EditContacts")
public class EditContacts extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditContacts() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        
        response.setContentType("text/html;charset=UTF-8");
        
        response.setCharacterEncoding("UTF-8");
        
        String name = request.getParameter("name");
        String tel = request.getParameter("tel");
        String gi = request.getParameter("groupid");
        String id = request.getParameter("id");
        
        if(name == null || name.trim().length() == 0)
        {
            response.getWriter().append("姓名不能为空");
        }
        else if(tel == null || tel.trim().length() == 0)
        {
            response.getWriter().append("电话号码不能为空");
        }
        else
        {
            contacts c = new contacts();
            
            c.setName(name);
            c.setTel(tel);
            c.setGroupid(Integer.parseInt(gi));
            c.setId(Integer.parseInt(id));
            //调用模型层
            
            contactsDal cd = new contactsDal();
            
            try{

                cd.update(c);
                
            }catch(Exception e){
                response.getWriter().append("更新数据失败");
                e.printStackTrace();
            }
        }
        response.sendRedirect("index.jsp");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
EditContacts.java

 

posted on 2015-12-25 09:30  锿咚公爵  阅读(266)  评论(0编辑  收藏  举报