Java简单用户管理系统

Dbutil.java

-----------------------------------------------------------------------------------

package com.ceshi.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 封装数据常用操作
 * @author Administrator
 *
 */
public class DbUtil {

 /**
  * 取得Connection
  * @return
  */
 public static Connection getConnection(){
  Connection conn = null;
  
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   String url = "jdbc:oracle:thin:@localhost:1521:orcl";
   String username = "drp1";
   String password = "drp1";
   conn = DriverManager.getConnection(url,username,password);
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return conn;
 }
 
 /**
  * 关闭conn
  * @param conn
  */
 public static void close(Connection conn){
  if(conn != null){
   try {
    conn.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * 关闭PreparedStatement
  * @param pstmt
  */
 public static void close(PreparedStatement pstmt){
  if(pstmt != null){
   try {
    pstmt.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * 关闭ResultSet
  * @param pstmt
  */
 public static void close(ResultSet rs ) {
  if (rs != null) {
   try {
    rs.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * 测试数据库是否连接成功
  * @param args
  */
 public static void main(String args[]){
  System.out.println("数据库连接成功!"+DbUtil.getConnection());
 }
}

-----------------------------------------------------------------------------------

 

PageModel.java

-----------------------------------------------------------------------------------

package com.ceshi.util;

import java.util.List;

/**
 * 封装分页信息
 * @author Administrator
 *
 */
public class PageModel {

 //结果集
 private List list;
 
 //查询记录数
 private int totalRecords;
 
 //每页多少条数据
 private int pageSize;
 
 //第几页
 private int pageNo;
 
 /**
  * 总页数
  * @return
  */
 public int getTotalPages() {
  return (totalRecords + pageSize - 1) / pageSize;
 }
 
 /**
  * 取得首页
  * @return
  */
 public int getTopPageNo() {
  return 1;
 }
 
 /**
  * 上一页
  * @return
  */
 public int getPreviousPageNo() {
  if (pageNo <= 1) {
   return 1;
  }
  return pageNo - 1;
 }
 
 /**
  * 下一页
  * @return
  */
 public int getNextPageNo() {
  if (pageNo >= getBottomPageNo()) {
   return getBottomPageNo();
  }
  return pageNo + 1; 
 }
 
 /**
  * 取得尾页
  * @return
  */
 public int getBottomPageNo() {
  return getTotalPages();
 }
 
 public List getList() {
  return list;
 }

 public void setList(List list) {
  this.list = list;
 }

 public int getTotalRecords() {
  return totalRecords;
 }

 public void setTotalRecords(int totalRecords) {
  this.totalRecords = totalRecords;
 }

 public int getPageSize() {
  return pageSize;
 }

 public void setPageSize(int pageSize) {
  this.pageSize = pageSize;
 }

 public int getPageNo() {
  return pageNo;
 }

 public void setPageNo(int pageNo) {
  this.pageNo = pageNo;
 }
}

-----------------------------------------------------------------------------------

UserManager.java

-----------------------------------------------------------------------------------

package com.ceshi.manager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ceshi.entity.User;
import com.ceshi.util.DbUtil;
import com.ceshi.util.PageModel;

/**
 * 采用单例管理用户
 * @author Administrator
 *
 */
public class UserManager {

 private static UserManager  instance = new UserManager();
 private UserManager(){}
 
 /**
  * 提供一个入口方法
  * @return
  */
 public static UserManager getInstance(){
  return instance;
 }
 
 /**
  * 添加用户的方法
  * @param user
  */
 public void addUser(User user){
  String sql = "insert into t_user (user_id, user_name, password, contact_tel, email, create_date) values (?,?,?,?,?,?)";
  Connection conn = null;
  PreparedStatement pstmt = null;
  
  try{
   
   conn = DbUtil.getConnection();
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, user.getUserId());
   pstmt.setString(2, user.getUserName());
   pstmt.setString(3, user.getPassword());
   pstmt.setString(4, user.getContactTel());
   pstmt.setString(5, user.getEmail());
   pstmt.setTimestamp(6, new Timestamp(new Date().getTime()));//能保存年月日 时分秒
   
   pstmt.executeQuery();
  } catch(SQLException e) {
   e.printStackTrace();
  }finally {
   DbUtil.close(pstmt);
   DbUtil.close(conn);
  }
 }
 
 /**
  * 修改用户
  * @param user
  */
 public void modifyUser(User user) {
  StringBuilder sbSql = new StringBuilder();
  sbSql.append("update t_user ")
  .append("set    user_name   = ?, ")
         .append("password    = ?, ")
         .append("contact_tel = ?, ")
         .append("email       = ? ")
  .append("where  user_id     = ? ");
  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DbUtil.getConnection();
   pstmt = conn.prepareStatement(sbSql.toString());
   pstmt.setString(1, user.getUserName());
   pstmt.setString(2, user.getPassword());
   pstmt.setString(3, user.getContactTel());
   pstmt.setString(4, user.getEmail());
   pstmt.setString(5, user.getUserId());
   pstmt.executeUpdate();
  }catch(SQLException e) {
   e.printStackTrace();
  }finally {
   DbUtil.close(pstmt);
   DbUtil.close(conn);
  }
 }
 
 /**
  * 根据用户代码删除
  * @param userId
  */
 public void delUser(String userId) {
  String sql = "delete from t_user where user_id=?";
  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DbUtil.getConnection();
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, userId);
   pstmt.executeUpdate();
  }catch(SQLException e) {
   e.printStackTrace();
  }finally {
   DbUtil.close(pstmt);
   DbUtil.close(conn);
  }
 }
 
 /**
  * 根据用户代码查询
  * @param userId
  * @return 如果存在返回User对象,否则返回null
  */
 public User findUserById(String userId) {
  String sql = "select user_id, user_name, password, contact_tel, email, create_date from t_user where user_id=?";
  Connection conn = null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  User user = null;
  try {
   conn = DbUtil.getConnection();
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, userId);
   rs = pstmt.executeQuery();
   if (rs.next()) {
    user = new User();
    user.setUserId(rs.getString("user_id"));
    user.setUserName(rs.getString("user_name"));
    user.setPassword(rs.getString("password"));
    user.setContactTel(rs.getString("contact_tel"));
    user.setEmail(rs.getString("email"));
    user.setCreateDate(rs.getTimestamp("create_date"));
   }
  }catch(SQLException e) {
   e.printStackTrace();
  }finally {
   DbUtil.close(rs);
   DbUtil.close(pstmt);
   DbUtil.close(conn);
  }
  return user;
 }
 
 /**
  * 分页查询
  * @param pageNo 第几页
  * @param pageSize 每页多少条数据
  * @return pageModel
  */
 public PageModel findUserList(int pageNo, int pageSize) {
  StringBuffer sbSql = new StringBuffer(); 
  sbSql.append("select user_id, user_name, password, contact_tel, email, create_date ")
   .append("from ")
   .append("( ")
   .append("select rownum rn, user_id, user_name, password, contact_tel, email, create_date ")
   .append("from ")
   .append("( ")
   .append("select user_id, user_name, password, contact_tel, email, create_date from t_user where user_id <> 'root' order by user_id ")
   .append(")  where rownum <= ? ")
   .append(")  where rn > ? ");
  Connection conn = null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  PageModel pageModel = null;
  try {
   conn = DbUtil.getConnection();
   pstmt = conn.prepareStatement(sbSql.toString());
   pstmt.setInt(1, pageNo * pageSize);
   pstmt.setInt(2, (pageNo - 1) * pageSize);
   rs = pstmt.executeQuery();
   List userList = new ArrayList();
   while (rs.next()) {
    User user = new User();
    user.setUserId(rs.getString("user_id"));
    user.setUserName(rs.getString("user_name"));
    user.setPassword(rs.getString("password"));
    user.setContactTel(rs.getString("contact_tel"));
    user.setEmail(rs.getString("email"));
    user.setCreateDate(rs.getTimestamp("create_date"));
    userList.add(user);
   }
   pageModel = new PageModel();
   pageModel.setList(userList);
   pageModel.setTotalRecords(getTotalRecords(conn));
   pageModel.setPageSize(pageSize);
   pageModel.setPageNo(pageNo);
  }catch(SQLException e) {
   e.printStackTrace();
  }finally {
   DbUtil.close(rs);
   DbUtil.close(pstmt);
   DbUtil.close(conn);
  }
  return pageModel;
 }
 
 /**
  * 取得总记录数
  * @param conn
  * @return
  */
 private int getTotalRecords(Connection conn)
 throws SQLException {
  String sql = "select count(*) from t_user where user_id <> 'root'";
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  int count = 0;
  try {
   pstmt = conn.prepareStatement(sql);
   rs = pstmt.executeQuery();
   rs.next();
   count = rs.getInt(1);
  }finally {
   DbUtil.close(rs);
   DbUtil.close(pstmt);
  }
  return count;
 }
}

 

-----------------------------------------------------------------------------------

User.java

-----------------------------------------------------------------------------------

package com.ceshi.entity;

import java.util.Date;

public class User {

 private String userId;   //用户ID
    private String userName;  //用户名称
    private String password;  //用户密码
 private String contactTel;  //用户电话
 private String email;   //电子邮件
 private Date createDate;  //创建日期

 public String getUserId() {
  return userId;
 }

 public void setUserId(String userId) {
  this.userId = userId;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getContactTel() {
  return contactTel == null ? "": contactTel;
 }

 public void setContactTel(String contactTel) {
  this.contactTel = contactTel;
 }

 public String getEmail() {
  return email == null ? "": email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public Date getCreateDate() {
  return createDate;
 }

 public void setCreateDate(Date createDate) {
  this.createDate = createDate;
 }
}

 

-----------------------------------------------------------------------------------

add_query.jsp

-----------------------------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%>
<%@ page import="java.util.*" %> 
<%@ page import="java.text.*" %> 
<%@ page import="com.ceshi.manager.*"%>
<%@ page import="com.ceshi.util.*"%>
<%@ page import="com.ceshi.entity.*"%>
<%
    request.setCharacterEncoding("GB18030");
    String command = request.getParameter("command");
 if ("del".equals(command)) {
  String[] userIds = request.getParameterValues("selectFlag");
  for (int i=0; i    UserManager.getInstance().delUser(userIds[i]);
  }
 }
 int pageNo = 1;
 int pageSize = 4; //每页设置的大小
 String pageNoString = request.getParameter("pageNo");
 if (pageNoString != null) {
  pageNo = Integer.parseInt(pageNoString);
 }
 PageModel pageModel = UserManager.getInstance().findUserList(pageNo, pageSize); 
%> 

 
  
  用户维护
  
 
 
 

  


  
用户维护界面


 
    
     
     
     
     
     
     
    
    <%
     List userList = pageModel.getList();
     for (Iterator iter=userList.iterator(); iter.hasNext();) {
      User user = iter.next();
     %>
    

     
     
     
     
     
     
    
    <%
     }
     %>
   

      
     

      用户代码
     

      用户名称
     

      联系电话
     

      email
     

      创建日期
     

              value="<%=user.getUserId() %>">
     

      <%=user.getUserId() %>
     

      <%=user.getUserName() %>
     

      <%=user.getContactTel()%>
     

      <%=user.getEmail() %>
     

      <%=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getCreateDate()) %>
     

        cellpadding="0" cellspacing="0" class="rd1">
    
     
     
    
   

      

       共 <%=pageModel.getTotalPages() %> 页    
       当前第<%=pageModel.getPageNo() %>
      

     

          

       
       
       
       
       
       
       
      

     

  

 

 

-----------------------------------------------------------------------------------

add_modify.jsp

-----------------------------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%>
<%@ page import="com.ceshi.entity.*" %>
<%@ page import="com.ceshi.manager.*" %>
<%
 request.setCharacterEncoding("GB18030");
 String command = request.getParameter("command");
 String userId = request.getParameter("userId");
 User user = UserManager.getInstance().findUserById(userId);
 if ("modify".equals(command)) {

  user.setUserId(request.getParameter("userId"));
  user.setUserName(request.getParameter("userName"));
  user.setPassword(request.getParameter("password"));
  user.setContactTel(request.getParameter("tel"));
  user.setEmail(request.getParameter("email"));
  
  UserManager.getInstance().modifyUser(user);
  out.println("修改用户成功!");
 }
%>



修改用户






修改用户



 
   
   
 
 
   
   
 
 
   
   
 
 
   
   
 
 
   
   
 
  
   
   
 
用户代码
       
  
用户名称
       
   
密码
       
   
联系电话
       
   
E-mail
        
   

        

   

        
        
   



 

-----------------------------------------------------------------------------------

add_add.jsp

-----------------------------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%>
<%@ page import="com.ceshi.entity.*" %>
<%@ page import="com.ceshi.manager.*" %>
<%
    request.setCharacterEncoding("GB18030");
 String command = request.getParameter("command");
 String userId = "";
 String userName = "";
 String contactTel = "";
 String email = "";
    if("add".equals(command)){//会很好的防止空指针异常
    if(UserManager.getInstance().findUserById(request.getParameter("userId")) == null)
    {
       User user = new User();
       user.setUserId(request.getParameter("userId"));
       user.setUserName(request.getParameter("userName"));
       user.setPassword(request.getParameter("password"));
       user.setContactTel(request.getParameter("tel"));
       user.setEmail(request.getParameter("email"));
      
       UserManager.getInstance().addUser(user);
       out.println("添加用户成功!");
       }else {
            userId = request.getParameter("userId");
   userName = request.getParameter("userName");
   contactTel = request.getParameter("contactTel");
   email = request.getParameter("email");
   out.println("用户代码已经存在,代码=【" + request.getParameter("userId") + "】");  
  }
    }
%>



添加用户






添加用户



 
   
   
 
 
   
   
 
 
   
   
 
 
   
   
 
 
   
   
 
  
   
   
 
用户代码
       
       
  
用户名称
       
   
密码
       
   
联系电话
       
   
E-mail
        
   

        

   

        
        
   



-----------------------------------------------------------------------------------

no fy

-----------------------------------------------------------------------------------

/**
  * 取得用户列表
  * @return
  */
 public List getUsers(){//如果不是static 我们取用户的时候可能要new 一个新的用户
  String sql = "select * from t_user";
  Connection conn = null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  User user = null;
  List users = new ArrayList();

  try {
   conn = DbUtil.getConnection();
   pstmt = conn.prepareStatement(sql);
   rs = pstmt.executeQuery();
   while (rs.next()) {
    user = new User();
    user.setId(rs.getString("id"));
    user.setName(rs.getString("name"));
    user.setPassword(rs.getString("password"));
    user.setTel(rs.getString("tel"));
    user.setEmail(rs.getString("email"));
    user.setCreateDate(rs.getTimestamp("create_date"));
    users.add(user);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   DbUtil.close(rs);
   DbUtil.close(pstmt);
   DbUtil.close(conn);
  }
  return users;
 }

 

-----------------------------------------------------------------------------------

<%
            List users = UserManager.getInstance().getUsers(); 
      for (int i = 0; i < users.size(); i++) {
      User user = users.get(i);
    %>
    
     
      
     
     
      <%=user.getName() %>
     
     
      <%=user.getPassword() %>
     
     
      <%=user.getTel()%>
     
     
      <%=user.getEmail() %>
     
     
      <%=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getCreateDate()) %>
     
    
    <%
     }
     %>
-----------------------------------------------------------------------------------

Junit.java

-----------------------------------------------------------------------------------

package com.ceshi.manager;

import java.util.List;
import java.util.Scanner;

import junit.framework.TestCase;

import com.ceshi.entity.User;

public class TestUserManager extends TestCase{
 
 //测试删除操作
 public void testDelUser(){
  Scanner str = new Scanner(System.in);
  System.out.print("请输入要删除的用户Id:");
  String userId = str.next();
  UserManager.getInstance().delUser(userId);
 }
 
 //测试查询操作
 public void testGetUsers(){
  List users = UserManager.getInstance().getUsers(); 
  for (int i = 0; i < users.size(); i++) {
  User user = users.get(i);
  System.out.print(user.getName());//获取名字
   }
    }
 
 //测试用户添加
 public void testAddUser(){
  User user = new User();
  Scanner str = new Scanner(System.in);
  System.out.print("请输入用户Id:");
  String id = str.next();
  System.out.print("请输入用户name:");
  String name = str.next();
  System.out.print("请输入用户password:");
  String password = str.next();
  System.out.print("请输入用户tel:");
  String tel = str.next();
  System.out.print("请输入用户email:");
  String email = str.next();
  user.setId(id);
  user.setName(name);
  user.setPassword(password);
  user.setTel(tel);
  user.setEmail(email);
  UserManager.getInstance().addUser(user);
 }
 
 //根据用户Id查询
 public void testFindUserById(){
  Scanner str = new Scanner(System.in);
  System.out.print("请输入用户Id:");
  String userId = str.next();
  UserManager.getInstance().findUserById(userId);
  User user = new User();
  System.out.print("用户的名字:"+user.getName());
 }
}

 

-----------------------------------------------------------------------------------

你可能感兴趣的:(软件工程)