2019.10.21课堂测试

一、题目要求

1登录账号:要求由6到12位字母、数字、下划线组成,只有字母可以开头;(1分)

2登录密码:要求显示“• ”或“*”表示输入位数,密码要求八位以上字母、数字组成。(1分)

3性别:要求用单选框或下拉框实现,选项只有“男”或“女”;(1分)

4学号:要求八位数字组成,前四位为“2018”开头,输入自己学号;(1分)

5姓名:输入自己的姓名;

5电子邮箱:要求正确判断格式[email protected];(1分)

6点击“添加”按钮,将学生个人信息存储到数据库中。(3分)

7可以演示连接上数据库。(2分)

二、设计思路

        首先在jsp页面进行表单数据的校验,如果校验不成功则提示错误,然后另用户重新输入数据,如果校验成功,则将表单中的数据发送到servlet层,servlet层接收到数据后开始进行数据的存放,然后调用Dao层的add函数来进行数据库的写入,这时Dao层调用DBUtil来注册驱动和获取数据库的连接,然后进行数据的写入,如果写入成功则返回true,写入失败则返回false,servlet层接收到Dao层的返回值后进行不同的处理,如果写入成功则向注册页面发送注册成功的消息,反之则发生注册失败的消息。

三、源代码

注册界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册界面</title>
<script type="text/javascript">
/*表单校验*/
function check() {
    f=0;
    var re =  /^[\w\u4e00-\u9fa5]{6,8}$/;  //判断字符串是否为数字和字母组合  
    var myPattern = new RegExp("^[a-zA-Z]"); // 以英文字母开头
    var username = document.getElementById("username").value;
    //alert(username.length);
    if(!(username.length>5&&username.length<13)){
        alert("用户名长度错误!");return false;
    }
    else if(!(re.test(username))){
        alert("用户名组成内容错误!");return false;
    }else if(!(myPattern.exec(username))){
        alert("用户名开头必须是字母!");return false;
    }
    var password = document.getElementById("password").value;
    if(password.length<8){f++;alert("密码长度错误!");}    return false;
        
    
    var xuehao = document.getElementById("xuehao").value;
    if(xuehao.length!=8){
        alert("学号长度错误!");return false;
    }
    if(xuehao[0]=='2'&&xuehao[1]=='0'&&xuehao[2]=='1'&&xuehao[3]=='8'){f++;}
    else{
        alert("学号格式错误!");return false;
    }
    
    var mail = document.getElementById("mail").value;
    if(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(mail)){f++;}
    else{
        alert("邮箱格式错误!");return false;
    }
    if(f>1){
        alert("添加成功");
        return true;
    }
    else{
        return false;
    }
    
}

</script>
</head>
<body background="1.jpg">
<form action="UserServlet?method=add" method="post" onsubmit="return check()"><br/><br/><br/><br/><br/><br/><br/>
<table align="center">
            <tr>
            <td>登入账号:</td>
                <td><input type="text"  id="username" name="username" value="" ></td>
            </tr>
            <tr>
            <td>登入密码:</td>
               <td> <input type="password"  id="password" name="password"  value="" ></td>
            </tr>
            <tr>
            <td>&nbsp;&nbsp;&nbsp;&nbsp;别:</td>
               <td>
               <select id="sex" name="sex" >
                    <option>--请选择--</option>
                        <option  value="男"></option>
                        <option  value="女"></option>
                    </select>
               </td>
            </tr>
            <tr>
            <td>&nbsp;&nbsp;&nbsp;&nbsp;名:</td>
               <td> <input type="text"  name="name"   value="" ></td>
            </tr>
            <tr>
            <td>&nbsp;&nbsp;&nbsp;&nbsp;号:</td>
               <td> <input type="text"  name="xuehao" id="xuehao"  value="" ></td>
            </tr>
            <tr>
            <td>电子邮件:</td>
               <td> <input type="text" id="mail" name="mail"  value="" ></td>
            </tr>
            <tr>
            <td>所在学院:</td>
               <td> <input type="text" id="xueyuan" name="xueyuan"  value="" ></td>
            </tr>
            <tr>
            <td>所在系:</td>
               <td> <input type="text" id="xi" name="xi"  value="" ></td>
            </tr>
            <tr>
            <td>所在班级:</td>
               <td> <input type="text" id="ban" name="ban"  value="" ></td>
            </tr>
            <tr>
            <td>入学年份(届):</td>
               <td>
               <select id="year" name="year">
                    <option>--请选择--</option>
                        
                        <option value="2018">2018</option>
                        <option value="2017">2019</option>
                        <option value="2016">2018</option>
                        <option value="2015">2019</option>
                        <option value="2014">2018</option>
                    </select>
               </td>
            </tr>
            <tr>
            <td>生源地:</td>
               <td>
               <select name="address">
               <option value ="河北省">河北省</option>
               <option value ="北京市">北京市</option>
               <option value ="天津市">天津市</option>
               </select>
               </td>
            </tr>
            <tr>
            <td>备注:</td>
               <td> <input type="text" id="beizhu" name="beizhu"  value="" ></td>
            </tr>
            <tr>
                 <td> <button type="submit" >&nbsp;&nbsp;&nbsp;&nbsp;</button></td>
            </tr>
        </table>
</form>
</body>
</html>

DBUtil.java

package zhuce;

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

//数据库资源管理工具
public class DBUtil {

    private static Connection conn;
    private static Statement stmt;
    private static PreparedStatement pstmt;

    static {
        // 加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 实例化数据库连接conn
    public static Connection getConnection() {
        try {
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/user?user=true&characterEncoding=UTF-8", "root", "123456");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    // 实例化SQL执行句柄stmt
    public static Statement getStatement() {
        Connection conn = getConnection();
        try {
            if (conn != null) {
                stmt = conn.createStatement();
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stmt;
    }

    // 实例化SQL执行句柄pstmt
    public static PreparedStatement getPreparedStatement(String sql) {
        Connection conn = getConnection();
        try {
            if (conn != null) {
                pstmt = conn.prepareStatement(sql);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return pstmt;
    }

    // 关闭数据库连接资源
    public static void closeDBResources() {
        try {
            if (pstmt != null && !pstmt.isClosed()) {
                pstmt.close();
            }
            if (stmt != null && !stmt.isClosed()) {// 如果stmt不为空,并且还未关闭
                stmt.close();
            }
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}

ZhuceDao.java

package zhuce;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import zhuce.DBUtil;

import zhuce.Zhuce;

public class ZhuceDao {
    // 保存信息
    public void saveZhuce(Zhuce zhuce) {
        String sql = "insert into zhucebiaodan(user,password,name,sex,diqu,phone,youxiang)values(?,?,?,?,?,?,?)";
        PreparedStatement pstmt = DBUtil.getPreparedStatement(sql);
        // 设置参数
        try {
            pstmt.setString(1, zhuce.getUser());
            pstmt.setString(2, zhuce.getPassword());
            pstmt.setString(3, zhuce.getName());
            pstmt.setString(4, zhuce.getSex());
            pstmt.setString(5, zhuce.getDiqu());
            pstmt.setString(6, zhuce.getPhone());
            pstmt.setString(7, zhuce.getYouxiang());
            pstmt.executeUpdate();// 更新数据
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    // 删除学生
    public void deleteZhuce(String user) {
        String sql = "delete from zhucebiaodan where user = ? ";
        PreparedStatement pstmt = DBUtil.getPreparedStatement(sql);

        try {
            pstmt.setString(1, user);
            pstmt.executeUpdate();

        } catch (SQLException e) {

            e.printStackTrace();
        } finally {
            DBUtil.closeDBResources();
        }
    }

    // 查询所有信息
    public static List<Zhuce> findAllZhuce() {
        List<Zhuce> zhucelist = new ArrayList<Zhuce>();
        String sql = "select user,password,name,sex,diqu,phone,youxiang from zhucebiaodan ";
        PreparedStatement pstmt = DBUtil.getPreparedStatement(sql);
        // 设置参数
        try {
            ResultSet rs = pstmt.executeQuery();// 执行得到结果集
            while (rs.next()) {// 每循环一次就找到一个学生

                String user = rs.getString("user");
                String password = rs.getString("password");
                String name = rs.getString("name");
                String sex = rs.getString("sex");
                String diqu = rs.getString("diqu");
                String phone = rs.getString("phone");
                String youxiang = rs.getString("youxiang");
                Zhuce zhuce = new Zhuce(user, password, name, sex, diqu, phone, youxiang);
                zhucelist.add(zhuce);// 将找到的学生对象加到集合里面
            }
            rs.close();// 关闭查询资源
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 关闭资源
            DBUtil.closeDBResources();
        }
        return zhucelist;
    }

}

ZhuceServlet.java

package zhuce;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import zhuce.ZhuceService;
import zhuce.Zhuce;

public class ZhuceServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");//设置编码
        String param=request.getParameter("param");
        
        if("add".equals(param)) {
            String user=request.getParameter("user");
            String password=request.getParameter("password");
            String name=request.getParameter("name");
            String sex=request.getParameter("sex");
            String diqu=request.getParameter("diqu");
            String phone=request.getParameter("phone");
            String youxiang=request.getParameter("youxiang");
            Zhuce zhuce=new Zhuce(user,password,name,sex,diqu,phone,youxiang);
            ZhuceService zs=new ZhuceService();
            zs.saveZhuce(zhuce);
            System.out.println("连接servlet");
            //重定向到index.jsp
            response.sendRedirect("index.jsp");
            
        }
        if("delete".equals(param)) {
            String user = request.getParameter("user");
            
            ZhuceService.deleteZhuce(user);

            // 重定向到index.jspt页面
            response.sendRedirect("index.jsp");
        }
    }
    
}

ZhuceService.java

package zhuce;

import java.util.List;

import zhuce.ZhuceDao;
import zhuce.Zhuce;


public class ZhuceService {
    private static ZhuceDao zhucedao=new ZhuceDao();
    //添加信息
        public  void saveZhuce(Zhuce zhuce) {
            zhucedao.saveZhuce(zhuce);
        }
        //查询所有信息
        public List<Zhuce> findAllZhuce(){
            return ZhuceDao.findAllZhuce();
        }
        //删除信息
        public static void deleteZhuce(String user) {
            zhucedao.deleteZhuce(user);
        }
}

四、代码分析

1、zhuce.jsp

  这是网页的主页面的代码,在画出页面后加入了表单的校验,当数据校验成功后会将表单数据发送到servlet层。

2、ZhuceServlet.java

  这个文件接收来自jsp页面的数据,然后调用Dao层的函数来进行数据库的写入。

3、ZhuceDao.java

  这个文件里存放的是用来写入数据库的代码,在该文件里调用了DBUtil类来获取和数据库的连接。

4、DBUtil.java

  这个文件里存放的类是用来注册驱动、获取和数据库的连接以及关闭相应的连接的方法,用来供TextLogin调用。

猜你喜欢

转载自www.cnblogs.com/best-hym/p/11716148.html