zoukankan      html  css  js  c++  java
  • 使用jsp+servlet+mysql用户管理系统之用户注册-----------使用简单三层结构分析页面显示层(view),业务逻辑层(service),数据持久层(dao)

    View层:jsp+servlet:

    jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!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>
    <style type="text/css">
    span {
    color: red;
    }
    </style>
    <script type="text/javascript" src="js/userCheck.js"></script>
    </head>
    <body>
    <!-- jsp中有九大内置对象,铜鼓pageContext对象可以获取其他内置对象 -->
    <form action="${pageContext.request.contextPath }/regist?type=reg" method="post">
    <table align="center">
    <tr>
    <td>用户名:</td>
    <td><input id="uname" type="text" name="uname" /> <span
    id="spname">${message }</span></td><!-- 此处message对应注册的servlet中的 信息请求赋值-->
    </tr>
    <tr>
    <td>密码:</td>
    <td><input id="upwd" type="password" name="upassword" /> <span
    id="sppwd"></span></td>
    </tr>

    <tr>
    <td>姓名:</td>
    <td><input id="urealname" type="text" name="urealname" /> <span
    id="sprealname"></span></td>
    </tr>
    <tr>
    <td>年龄:</td>
    <td><input id="uage" type="text" name="uage" /> <span
    id="spage"></span></td>
    </tr>
    <tr>
    <td>性别:</td>
    <td>男<input type="radio" name="usex" value="1" />女<input
    type="radio" name="usex" value="0" checked="checked" /></td>
    </tr>
    <tr>
    <td><input type="submit" value="提交数据"
    onclick="return checkControl();" /></td>
    <td><input type="reset" /></td>
    </tr>
    </table>
    </form>
    </body>
    </html>

    servlet:

    /**
    *
    */
    package com.qingmang.servlet;

    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.qingmang.domain.User;
    import com.qingmang.exception.UserExistException;
    import com.qingmang.service.UserService;

    /**
    * @author administrator
    * 用户添加和注册servlet
    *
    */
    @SuppressWarnings("serial")
    public class RegistServlet extends HttpServlet {

    private UserService service = new UserService();

    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    res.setContentType("text/html;charset=UTF-8");

    String type = req.getParameter("type");
    String uname = req.getParameter("uname");
    String upwd = req.getParameter("upassword");
    String realName = req.getParameter("urealname");
    String age = req.getParameter("uage");
    String sex = req.getParameter("usex");

    // 将信息封装进User
    User user = new User();
    user.setUname(uname);
    user.setUpassword(upwd);
    user.setUrealname(realName);
    user.setUage(Integer.parseInt(age));
    user.setUsex(Integer.parseInt(sex));

    try {
    // 将user信息存入数据库,并判断是否存入成功,只要返回不报错就成功
    boolean boo = service.add(user);
    if (boo) {
    if ("reg".equals(type)) {
    // 注册成功,跳转到登录页面
    res.sendRedirect(req.getContextPath() + "/login.jsp");
    } else {
    // 为了跳到用户列表页面时显示数据,应该跳到用户查询servlet中执行查询方法
    res.sendRedirect(req.getContextPath() + "/user");
    }

    }
    } catch (UserExistException e) {
    // 跳转回注册页面
    req.setAttribute("message", e.getMessage());// 在request对象中加入名为message的属性并附值为e.getMessage())

    } catch (Exception e) {
    // 跳转到错误页面

    }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

    doGet(req, res);
    }

    }

    service业务逻辑层:

    service:

    实现类:

    public interface IUserService {

    public boolean add(User user);
    public User getByName(String name);
    public boolean existName(String name);
    public User existUser(String name, String pwd);
    public List<User> getAll();
    public List<User> getByKey(String key);
    public boolean delete(String uid) throws Exception;
    public User findUserById(int id);
    public boolean updateUser(User user);
    }

    service类

    /**
    *
    */
    package com.qingmang.service;

    import java.util.List;
    import com.qingmang.dao.UserDao;
    import com.qingmang.domain.User;
    import com.qingmang.exception.UserExistException;
    import com.qingmang.service.IService.IUserService;

    /**
    * @author administrator
    *
    */
    public class UserService implements IUserService{

    // 声明并初始化UserDao
    UserDao dao = new UserDao();

    /*
    * (non-Javadoc)
    *
    * @see
    * com.qingmang.service.inter.IUserService#add(com.qingmang.domain.User)
    */
    public boolean add(User user) {

    if (existName(user.getUname()))
    throw new UserExistException("该用户已经存在!");

    return dao.add(user);
    }

    /*
    * (non-Javadoc)
    *
    * @see com.qingmang.service.inter.IUserService#getByName(java.lang.String)
    */
    public User getByName(String name) {
    return dao.getByName(name);
    }

    /*
    * (non-Javadoc) 判断用户名是否已经存在
    *
    * @see com.qingmang.service.inter.IUserService#existName(java.lang.String)
    */
    public boolean existName(String name) {
    boolean flag = false;
    User user = getByName(name);
    if (user != null)
    flag = true;

    return flag;
    }

    /*
    * (non-Javadoc) 判断用户名密码是否正确
    *
    * @see com.qingmang.service.inter.IUserService#existUser(java.lang.String,
    * java.lang.String)
    */
    public User existUser(String name, String pwd) {

    User user = getByName(name);
    if (user != null && user.getUpassword().equals(pwd)) {
    return user;
    }

    return null;
    }

    /*
    * (non-Javadoc)
    *
    * @see com.qingmang.service.inter.IUserService#getAll()
    */
    public List<User> getAll() {
    return dao.getAll();
    }

    /*
    * (non-Javadoc)
    *
    * @see com.qingmang.service.inter.IUserService#getByKey(java.lang.String)
    */
    public List<User> getByKey(String key) {
    return dao.getByKey(key);
    }

    public boolean delete(String uid) throws Exception {
    return dao.delete(uid);
    }

    public User findUserById(int id) {
    return dao.findUserById(id);

    }

    public boolean updateUser(User user) {

    return dao.updateUser(user);

    }

    }

    实现的Runtime异常类

    /**
    *
    */
    package com.qingmang.exception;

    /**
    * @author administrator
    *
    */
    @SuppressWarnings("serial")
    public class UserExistException extends RuntimeException{

    /**
    *
    */
    public UserExistException() {
    super();
    // TODO Auto-generated constructor stub
    }

    /**
    * @param message
    * @param cause
    */
    public UserExistException(String message, Throwable cause) {
    super(message, cause);
    // TODO Auto-generated constructor stub
    }

    /**
    * @param message
    */
    public UserExistException(String message) {
    super(message);
    // TODO Auto-generated constructor stub
    }

    /**
    * @param cause
    */
    public UserExistException(Throwable cause) {
    super(cause);
    // TODO Auto-generated constructor stub
    }


    }

    实体类:

    /**
    *
    */
    package com.qingmang.domain;

    import java.util.Date;

    /**
    * @author administrator
    *
    */
    public class User {

    private int uid;
    private String uname;
    private String upassword;
    private String urealname;
    private int uage;
    private int usex;
    /**
    *
    */
    public User() {
    super();
    // TODO Auto-generated constructor stub
    }
    /**
    * @param uid
    * @param uname
    * @param upassword
    * @param urealname
    * @param uage
    * @param usex
    */
    public User(int uid, String uname, String upassword, String urealname,
    int uage, int usex) {
    super();
    this.uid = uid;
    this.uname = uname;
    this.upassword = upassword;
    this.urealname = urealname;
    this.uage = uage;
    this.usex = usex;
    }
    /**
    * @return the uid
    */
    public int getUid() {
    return uid;
    }
    /**
    * @param uid the uid to set
    */
    public void setUid(int uid) {
    this.uid = uid;
    }
    /**
    * @return the uname
    */
    public String getUname() {
    return uname;
    }
    /**
    * @param uname the uname to set
    */
    public void setUname(String uname) {
    this.uname = uname;
    }
    /**
    * @return the upassword
    */
    public String getUpassword() {
    return upassword;
    }
    /**
    * @param upassword the upassword to set
    */
    public void setUpassword(String upassword) {
    this.upassword = upassword;
    }
    /**
    * @return the urealname
    */
    public String getUrealname() {
    return urealname;
    }
    /**
    * @param urealname the urealname to set
    */
    public void setUrealname(String urealname) {
    this.urealname = urealname;
    }
    /**
    * @return the uage
    */
    public int getUage() {
    return uage;
    }
    /**
    * @param uage the uage to set
    */
    public void setUage(int uage) {
    this.uage = uage;
    }
    /**
    * @return the usex
    */
    public int getUsex() {
    return usex;
    }
    /**
    * @param usex the usex to set
    */
    public void setUsex(int usex) {
    this.usex = usex;
    }



    }

    数据持久层:dao 层

    /**
    *
    */
    package com.qingmang.dao;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;

    import com.qingmang.domain.User;
    import com.qingmang.utils.JdbcUtil;

    /**
    * @author administrator
    *
    */
    public class UserDao {

    private Connection conn = null;// 初始化Connection连接对象,用于与数据库建立连接
    private PreparedStatement pstmt = null;// 初始化向数据库发送预编译sql的PrepareSatement对象
    private Statement stmt = null;// 初始化用于向数据库发送SQL的Statement对象
    private ResultSet rs = null; // 初始化结果集对象

    /*
    * PreperedStatement可以避免SQL注入的问题。
    * Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement
    * 可对SQL进行预编译,从而提高数据库的执行效率。
    * 并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。
    * 简单记:使用?传值的时候要使用预编译PreperedStatement对象
    */

    /*
    * (non-Javadoc) 用户添加方法
    *
    * @see com.qingmang.dao.inter.IUserDao#add(com.qingmang.domain.User)
    */
    public boolean add(User user) {
    boolean flag = false;// 初始化布尔类型对象值

    try {

    conn = JdbcUtil.getConnection();// 连接数据库
    String sql = "INSERT INTO users " + "(uname,upassword,"
    + "urealname,uage,usex) " + "VALUES (?,?,?,?,?)";// 在数据库执行的sql语句
    pstmt = conn.prepareStatement(sql);// 预编译sql语句;作用:将会大大降低运行时间,提高代码的可读性和可维护性
    // 为sql语句中的?设置参数,第一个位置的?占位符为1;第2个?位置的占位符为2,其后为参数
    pstmt.setString(1, user.getUname());
    pstmt.setString(2, user.getUpassword());
    pstmt.setString(3, user.getUrealname());
    pstmt.setInt(4, user.getUage());
    pstmt.setInt(5, user.getUsex());

    int count = pstmt.executeUpdate();// 完成数据添加操作,并计数
    if (count > 0)
    flag = true;// 如果添加成功,返回true,跳出方法

    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
    } finally {
    try {
    JdbcUtil.close(conn, pstmt);// 关闭连接
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
    }
    }
    return flag;
    }

    /*
    * (non-Javadoc) 根据用户名得到用户方法
    *
    * @see com.qingmang.dao.inter.IUserDao#getByName(java.lang.String)
    */
    public User getByName(String uname) {
    // 创建user的null
    User user = null;
    try {
    conn = JdbcUtil.getConnection();
    String sql = "select * from users where uname=?";
    pstmt = conn.prepareStatement(sql);
    // 设置参数
    pstmt.setString(1, uname);

    rs = pstmt.executeQuery();// 执行数据查询操作,并返回数据结果集
    if (rs.next()) {
    user = new User();// 新建User对象,以便之后将结果集中的数据封装进对象
    user.setUname(rs.getString("uname"));
    user.setUpassword(rs.getString("upassword"));
    user.setUrealname(rs.getString("urealname"));
    user.setUage(rs.getInt("uage"));
    user.setUsex(rs.getInt("usex"));

    }

    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
    } finally {
    try {
    JdbcUtil.close(conn, pstmt);
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
    }
    }

    return user;// 返回查询的对象
    }

    /*
    * (non-Javadoc) 得到所有用户信息
    *
    * @see com.qingmang.dao.inter.IUserDao#getAll()
    */
    public List<User> getAll() {

    return getByKey(null);
    }

    /**
    * 根据关键词查询用户
    *
    * @param key
    * @return
    */
    public List<User> getByKey(String key) {
    List<User> list = new ArrayList<User>();
    try {
    conn = JdbcUtil.getConnection();// 连接数据库
    String sql = "";
    sql = "select * from users where 1=1";

    /* 此处where 1=1 妙处在于在之后加条件时直接用and并列条件即可;也有一个在jsp页面多条件查询的方法,但需用到没学过的知识 */

    if (key != null && !"".equals(key)) {
    sql += " and uname like '" + key + "%'";
    } // 加key值的null和""的判断,如果为空,则全部查询,若不为空,则按条件查询

    stmt = conn.createStatement();// 创建用于向数据库发送SQL的Statement对象

    rs = stmt.executeQuery(sql);// 执行sql语句的数据查询操作
    while (rs.next()) {
    User user = new User();

    // 将数据封装进对象
    user.setUid(rs.getInt("uid"));
    user.setUname(rs.getString("uname"));
    user.setUpassword(rs.getString("upassword"));
    user.setUrealname(rs.getString("urealname"));
    user.setUage(rs.getInt("uage"));
    user.setUsex(rs.getInt("usex"));

    list.add(user);
    }
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    } finally {
    try {
    JdbcUtil.close(conn, pstmt, rs);
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    }
    return list;
    }

    /**
    * 单条用户删除 是通过超链接方式,用post方式向servlet提交一个id, 依照这个id对数据库中的记录进行删除操作。
    * */
    // 执行静态的sql(delete)
    public boolean delete(String uid) throws Exception {
    boolean flag = false;
    try {

    conn = JdbcUtil.getConnection();// 连接数据库
    stmt = conn.createStatement();// 得到Statement对象
    String sql = "delete from users where uid='" + uid + "'";// 静态的sql语句
    int count = stmt.executeUpdate(sql);// 执行sql语句
    if (count >= 1) {
    flag = true;
    }
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    } finally {
    try {
    JdbcUtil.close(conn, stmt);
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    }
    return flag;
    }

    /**
    * 根据id得到用户
    *
    * @param id
    * @return
    */
    public User findUserById(int id) {

    // 创建user的null
    User user = null;
    try {
    conn = JdbcUtil.getConnection();
    String sql = "select * from users where uid=?";
    pstmt = conn.prepareStatement(sql);
    // 设置参数
    pstmt.setInt(1, id);

    rs = pstmt.executeQuery();
    if (rs.next()) {
    user = new User();
    user.setUname(rs.getString("uname"));
    user.setUpassword(rs.getString("upassword"));
    user.setUrealname(rs.getString("urealname"));
    user.setUage(rs.getInt("uage"));
    user.setUsex(rs.getInt("usex"));

    }

    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
    } finally {
    try {
    JdbcUtil.close(conn, pstmt);
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException();
    }
    }

    return user;
    }

    /**
    * 修改用户信息
    *
    * @param user
    */
    public boolean updateUser(User user) {
    boolean falg = false;
    try {
    conn = JdbcUtil.getConnection();
    String sql = "update users set uname=?,upassword=?,urealname=?,uage=?,usex=? where uid=?";
    pstmt = conn.prepareStatement(sql);
    pstmt.setString(1, user.getUname());
    pstmt.setString(2, user.getUpassword());
    pstmt.setString(3, user.getUrealname());
    pstmt.setInt(4, user.getUage());
    pstmt.setInt(5, user.getUsex());
    pstmt.setInt(6, user.getUid());

    pstmt.executeUpdate();
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    } finally {
    try {
    JdbcUtil.close(conn, pstmt);
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }

    }
    return falg;

    }
    }

    连接数据库的工具类:

    /**
    *
    */
    package com.qingmang.utils;

    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.Properties;

    /**
    * 自定义连接数据库工具类
    * @author kh
    *
    */
    public class JdbcUtil {

    private static String url = null;
    private static String user = null;
    private static String password = null;

    static{
    InputStream is = null;
    try {
    //File f = new File(".\src\mysql.properties");
    //System.out.println(f.getAbsolutePath());
    //is = new FileInputStream(f);
    is = JdbcUtil.class.getResourceAsStream("/mysql.properties");
    Properties pro = new Properties();
    pro.load(is);

    url = pro.getProperty("url");
    user = pro.getProperty("user");
    password = pro.getProperty("password");

    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    } finally{
    if(is!=null)
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    }
    }

    /**
    * 得到数据库连接
    * @return
    * @throws Exception
    */
    public static Connection getConnection() throws Exception{
    Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动类;由于注册过程在Driver类的静态类已经实现。
    //也就是说只要类被加载,就完成了向驱动管理器的注册
    return DriverManager.getConnection(url, user, password);//得到数据库连接
    }

    /**
    * 关闭数据库连接
    * @param conn
    * @param stmt
    * @param rs
    */
    public static void close(Connection conn,Statement stmt,ResultSet rs){
    if (rs != null)
    try {
    rs.close();
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    if (stmt != null)
    try {
    stmt.close();
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    if (conn != null)
    try {
    conn.close();
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    }

    /**
    * 关闭数据库连接
    * @param conn
    * @param stmt
    * @param rs
    */
    public static void close(Connection conn,Statement stmt){
    if (stmt != null)
    try {
    stmt.close();
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    if (conn != null)
    try {
    conn.close();
    } catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    }
    }

    使用的properties:

    url = jdbc:mysql://localhost:3306/qingmang
    user = root
    password =root

    成就人
  • 相关阅读:
    show variables 详解
    用expect做自动应答脚本
    percona-toolkit工具检查MySQL复制一致性及修复
    Discuz论坛架构改造
    注解处理器
    ora-12514 tns 监听程序当前无法识别连接描述符中请求的服务
    内嵌Tomcat和SpringMVC的简单整合测试
    @Import导入ImportSelector实现类demo
    Mybatis-Spring项目编写测试类
    @Configuration注解作用和在Spring中的处理
  • 原文地址:https://www.cnblogs.com/pingzizhuanshu/p/8724490.html
Copyright © 2011-2022 走看看