JAVA程序设计——第七周

实验名称:学生信息添加界面

一、实验要求:

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

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

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

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

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

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

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

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

二、实验准备

在周六上午由软工17级学长进行指导,安装并配置好“Tomcat”、“Navicat”、“MySQL”、“java ee”等软件。这个过程中遇到以下问题需要注意:

1、eclipse se里第一次使用时preferences可能没有“server和”“web”选项,需要安装插件,安装完毕后可能找不到Tomcat9.0,还要再次安装插件,或者使用java ee解决这一问题。

2、在项目中要添加jar包:“jstl-1.2.jar” (JSP标准标签库)“mysql-connector-java-5.-bin.jar”(MySQL数据库驱动)“servlet api.jar”(servlet、Tomcat驱动)

三、实验内容

一、数据库建表

在Navicat中建立和MySQL的链接,在建好的链接上右键新建数据库,在新建好的数据库的表中右键新建表,开始制表,表格如下:

(注意id一栏设置为不允许为空,并设为主键)

1、util包中建“BaseConnection.java”用于链接MySQL(可以作为模板使用时修改数据库名称和密码即可)

package util;

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

public class BaseConnection {
    
     public static Connection getConnection(){//用这个方法获取mysql的连接
         Connection conn=null;
         String driver = "com.mysql.jdbc.Driver";
         String url = "jdbc:mysql://localhost:3306/qsly?characterEncoding=utf8&useSSL=true";//修改数据库名称
         String user = "root";
         String password = "mysjz";
         try{
             Class.forName(driver);//加载驱动类
             conn=DriverManager.   
                     getConnection(url,user,password);//(url数据库的IP地址,user数据库用户名,password数据库密码)
         }catch(Exception e){
             e.printStackTrace();
         }
         return conn;
     }
     //关闭数据库链接
     public static void close (Statement state, Connection conn) {
            if (state != null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //关闭数据库连接
        public static void close (ResultSet rs, Statement state, Connection conn) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if (state != null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

public static void main(String[] args) {
    getConnection();
}
    
}

2、在bean包中构造java类 Login.java

该类中需要把所有要输入的数据设为私有成员,并构造getter、setter函数和含id的构造函数和不含id的构造函数。

package bean;
public class Login {
    
    int id;
    String user;
    String pwd;
    String name;
    String sex;
    String number;
    String email;
    String yuan;
    String xi;
    String ban;
    String year;
    String area;
    String beizhu;

    
    
    public Login(String user,String pwd,String name,String sex,String number,String email,String yuan,String xi,String ban,String year,String area,String beizhu) {
        // TODO 自动生成的构造函数存根
        this.user=user;
        this.pwd=pwd;
        this.name=name;
        this.sex=sex;
        this.number=number;
        this.email=email;
        this.yuan=yuan;
        this.xi=xi;
        this.ban=ban;
        this.year=year;
        this.area=area;
        this.beizhu=beizhu;
    }

    public Login(int id,String user,String pwd,String name,String sex,String number,String email,String yuan,String xi,String ban,String year,String area,String beizhu) {
        this.id=id;
        this.user=user;
        this.pwd=pwd;
        this.name=name;
        this.sex=sex;
        this.number=number;
        this.email=email;
        this.yuan=yuan;
        this.xi=xi;
        this.ban=ban;
        this.year=year;
        this.area=area;
        this.beizhu=beizhu;
    }

    public int getId() {
        return id;
    }

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

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getEmail() {
        return email;
    }

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

    public String getYuan() {
        return yuan;
    }

    public void setYuan(String yuan) {
        this.yuan = yuan;
    }

    public String getXi() {
        return xi;
    }

    public void setXi(String xi) {
        this.xi = xi;
    }

    public String getBan() {
        return ban;
    }

    public void setBan(String ban) {
        this.ban = ban;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getBeizhu() {
        return beizhu;
    }

    public void setBeizhu(String beizhu) {
        this.beizhu = beizhu;
    }
    
}

3、在dao包构造Add.java和check.java

在Add.java中主函数中实例化一个Login类对象用于判断是否和数据库连接成功,如果运行结果为“Yes”并且Navicat中插入成功,则链接数据库成功,否则还要查错。

package dao;

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

import bean.Login;
import util.BaseConnection;

public class Add {
    //
    public static boolean add1(Login login)
    {
        boolean f = false;
        Connection conn = BaseConnection.getConnection();
        //PreparedStatement ps=null;
        
        String sql = "insert into login(user,pwd,name,sex,number,email,yuan,xi,ban,year,area,beizhu) values('" + login.getUser() + "','" + login.getPwd() + "','" + login.getName() + "','" +login.getSex() + "','" +login.getNumber() + "','" +login.getEmail() + "','" + login.getYuan() + "','" + login.getXi() + "','" + login.getBan() + "','" + login.getYear() + "','" + login.getArea() + "','" + login.getBeizhu() + "')";
        //String sql = "insert into course1(name,teacher,classroom) values('" + cour.getName() + "','" + cour.getTeacher() + "','" + cour.getClassroom() + "')'";
        Statement state = null;
        int a = 0;
        try {
            state = conn.createStatement();
            a = state.executeUpdate(sql);
            
            
        } catch (SQLException e) {
            // TODO  Զ    ɵ  catch   
            e.printStackTrace();
        }
        
        if(a >0)
        {
            System.out.println(" Yes");
            f = true;
        }else {
            System.out.println("NO ");
        }
        return f;
    }
    public static void main(String[] args) {
        Login login = new Login("1","2","3","4","5","6","7","8","9","10","11","12");
        add1(login);
    }
}

在check.java中写入检查数据格式的代码(可以在jsp文件中检查,更简单有效,这里笔者初学,对jsp理解较差)

package dao;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class check {

    /**
      * 验证邮箱地址是否正确
      * @param email
      * @return
      */
     public static boolean checkEmail(String email){
      boolean flag = false;
      try{
       String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
       Pattern regex = Pattern.compile(check);
       Matcher matcher = regex.matcher(email);
       flag = matcher.matches();
      }catch(Exception e){
       //LOG.error("验证邮箱地址错误", e);
       flag = false;
      }
      
      return flag;
     }
     /**
      * 验证学号
      * @param mobiles
      * @return
      */
     public static boolean isMobileNO(String mobiles){
      boolean flag = false;
      try{
       Pattern p = Pattern.compile("^2018\\d{4}$");
       Matcher m = p.matcher(mobiles);
       flag = m.matches();
      }catch(Exception e){
       //LOG.error("验证手机号码错误", e);
       flag = false;
      }
      return flag;
     }
     /**
      * 验证登录名
      * 
      */
     public static boolean isUserNO(String user){
          boolean flag = false;
          try{
           Pattern p = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]*\\d{5,11}$");
           Matcher m = p.matcher(user);
           flag = m.matches();
          }catch(Exception e){
           //LOG.error("验证手机号码错误", e);
           flag = false;
          }
          return flag;
         }
     /**
      * 验证密码
      * 
      */
     public static boolean isPwdNO(String pwd){
          boolean flag = false;
          try{
           Pattern p = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$");
           Matcher m = p.matcher(pwd);
           flag = m.matches();
          }catch(Exception e){
           //LOG.error("验证手机号码错误", e);
           flag = false;
          }
          return flag;
         }
}

4、在servlet包中建立servlet.java类链接tomcat

package servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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 org.apache.taglibs.standard.tag.el.fmt.RequestEncodingTag;

import bean.Login;
import dao.Add;
import dao.check;

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

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());request.
        request.setCharacterEncoding("utf-8");
        String method=request.getParameter("method");
        if(method.equals("add"))
        {
            add(request,response);
        }
    }

    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO 自动生成的方法存根
        request.setCharacterEncoding("utf-8");
        String user=request.getParameter("user");
        String pwd=request.getParameter("pwd");
        String name=request.getParameter("name");
        String sex=request.getParameter("sex");
        String number=request.getParameter("number");
        String email=request.getParameter("email");
        String yuan=request.getParameter("yuan");
        String xi=request.getParameter("xi");
        String ban=request.getParameter("ban");
        String year=request.getParameter("year");
        String area=request.getParameter("area");
        String beizhu=request.getParameter("beizhu");
        
    
        
        Login a=new Login(user,pwd,name,sex,number,email,yuan,xi,ban,year,area,beizhu);
        
           //用户
           if (check.isUserNO(user)&&check.isPwdNO(pwd)&&check.checkEmail(email)&&check.isMobileNO(number) ){
               Login login = new Login(user,pwd,name,sex,number,email,yuan,xi,ban,year,area,beizhu);
                if (Add.add1(login)) {
                    request.setAttribute("message", "注册成功");
                    request.getRequestDispatcher("login.jsp").forward(request,response);
                }else {
                    request.setAttribute("message", "注册失败");
                    request.getRequestDispatcher("login.jsp").forward(request,response);
                }
            }
           else if(!check.isUserNO(user)){
                request.setAttribute("message", "登录名的格式不正确");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
           else if(!check.isPwdNO(pwd)){
                request.setAttribute("message", "密码格式不正确");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
           else if (!check.checkEmail(email)){
               request.setAttribute("message", "电子邮件格式不符");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
           else if(!check.isMobileNO(number)) {
               request.setAttribute("message", "学号格式不符");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }

    }
        
    
    

    /**
     * @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);
    }

}

5、制作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>Insert title here</title>
</head>
<body>
    <%
         Object message = request.getAttribute("message");
         if(message!=null && !"".equals(message)){
     
    %>
         <script type="text/javascript">
              alert("<%=request.getAttribute("message")%>");
         </script>
    <%} %>
<form action="Servlet?method=add" method="post" onsubmit="return check()">
<table align="center">
    <tr>
        <td>登录账户:</td>
        <td><input type="text" name="user" id="name" placeholder="请输入用户名"></td>
        
    </tr>
    <tr>
        <td>密码:</td>
        <td><input type="password" name="pwd" id="pwd" placeholder="请输入密码"></td>
    </tr>
    <tr>
        <td>性别:</td>
        <td><input type="radio" name="sex" value="男"><input type="radio" name="sex" value="女"></td>
    </tr>
    <tr>
        <td>姓名:</td>
        <td><input type="text" name="name" placeholder="请输入姓名"></td>
    </tr>
    <tr>
        <td>学号:</td>
        <td><input type="text" name="number" placeholder="请输入学号"></td>
    </tr>
    <tr>
        <td>电子邮件</td>
        <td><input type="text" name="email" id="email" placeholder="请输入电子邮件"></td>
    </tr>
    <tr>
        <td>所在学院:</td>
        <td><input type="text" name="yuan" placeholder="请输入所在学院"></td>
    </tr>
    <tr>
        <td>所在系:</td>
        <td><input type="text" name="xi" placeholder="请输入所在系"></td>
    </tr>
    <tr>
        <td>所在班:</td>
        <td><input type="text" name="ban" placeholder="请输入所在班"></td>
    </tr>
    <tr>
        <td>入学年份(届):</td>
        <td><select name="year">
        
            <option value="1998">1998</option>
            <option value="1999">1999</option>
            <option value="2000">2000</option>
            <option value="2001">2001</option>
            <option value="2002">2002</option>
            <option value="2003">2003</option>
            <option value="2004">2004</option>
            <option value="2005">2005</option>
            <option value="2006">2006</option>
            <option value="2007">2007</option>
            <option value="2008">2008</option>
            <option value="2009">2009</option>
            <option value="2010">2010</option>
            <option value="2011">2011</option>
            <option value="2012">2012</option>
            <option value="2013">2013</option>
            <option value="2014">2014</option>
            <option value="2015">2015</option>
            <option value="2016">2016</option>
            <option value="2017">2017</option>
            <option value="2018" selected="selected">2018</option>
            <option value="2019">2019</option>
            <option value="2020">2020</option>
        </select>
        </td>
    </tr>
    <tr>
        <td>生源地:</td>
        <td><input type="text" name="area" placeholder="请输入生源地"></td>
    </tr>
    <tr>
        <td>备注:</td>
        <td><input type="text" name="beizhu"  placeholder="请输入备注"></td>
    </tr>
    
    <tr>
    <td>    <input type="submit" value="注册"></td>
    <td>    <input type="reset" value="重置"></td>
    </tr>
</table>    
</form>
<script type="text/javascript">
        function check() {
            var name = document.getElementById("name");
            var pwd = document.getElementById("pwd");
            var user = document.getElementById("user");
            var phone = document.getElementById("phone");
            var email = document.getElementById("email");
            
            //非空 
            if(name.value == '') {
                alert('姓名不能为空');
                user.focus();
                return false;
            }else if(pwd.value == '') {
                alert('密码不能为空');
                pwd.focus();
                return false;
            }else if(user.value == '')
                {
                    alert('用户名不能为空')
                    name.focus();
                    return false;
                }else if(phone.value == '')
                {
                    alert('电话号码不能为空')
                    phone.focus();
                    return false;
                }else if(email.value == '')
                    {
                        alert('邮件地址不能为空')
                        email.focus();
                        return false;
                    }

            }
            
        </script>      
        
</body>
</html>

三、实验结果

 实验最后可以实现数据的输入和格式判断。

四、实验反思

虽然功能能够完全实现,但是界面过于简陋,而且错误提示语句笼统,检查错误还在java层,如果能够在jsp中检查效果会更好。实验中遇到的问题比这还要多,根本问题在于,过于依赖模板,对其中的函数等等还不了解。

        

猜你喜欢

转载自www.cnblogs.com/xsy948306073/p/11716615.html