java web第一次课堂测试1

---恢复内容开始---

要求如图:

java web第一次课堂测试1

 本程序包括四个文件,一个显示界面的jsp文件,一个dao层文件,一个servlet层文件 一个连接数据库的文件

下面依次附上代码:

前端界面:

<%@ 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;
    var pas= /\w/;
    if(password.length<8){f++;alert("密码长度必须大于8位!");return false;}
    if(!(pas.test(password))){
        alert("密码应由数字和字母组成!");return false;
    } 
    var xuehao = document.getElementById("xuehao").value;
    if(xuehao.length!=8){
        alert("学号必须为8位!");return false;
    }
    if(xuehao[0]==‘2‘&&xuehao[1]==‘0‘&&xuehao[2]==‘1‘&&xuehao[3]==‘8‘){f++;}
    else{
        alert("学号必须以2018开头!");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("恭喜您已入住铁大软工大家(da)庭(keng)!");
        return true;
    }
    else{
        return false;
    }
}

</script>
</head>
<STYLE TYPE="text/css">
<!--
BODY {background-image:URL(1.png);
background-position:center;
background-repeat:no-repeat;
background-atachment:fixed;
}
table{margin:auto}
-->
</STYLE>
<body >
<form action="UserServlet?method=add" method="post" onsubmit="return check()"><br/><br/><br/><br/><br/><br/><br/>
<table frame= "box">
            <tr>
            <td>登入账号:</td>
                <td><input type="text"  id="username" name="username" value="" ></td>
                <td>账号应为6到12位的英文或数字,下划线组成,且由英文开头.<td>
            </tr>
            <tr>
            <td>登入密码:</td>
               <td> <input type="password"  id="password" name="password"  value="" ></td>
               <td>密码应由大于8位的数字和英文组成.<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>
               <td>学号应为2018开头的八位数字.<td>
            <tr>
            <td>电子邮件:</td>
               <td> <input type="text" id="mail" name="mail"  value="" ></td>
               <td>电子邮件应符合其格式.<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>
               <option value ="武安市">武安市</option>
               </select>
               </td>
            </tr>
            <tr>
            <td>备注:</td>
               <td> <input type="text" id="beizhu" name="beizhu"  value="" ></td>
            </tr>
            <tr>
            <td><td>
                <td> <button type="submit" >添&nbsp;&nbsp;&nbsp;&nbsp;加</button></td>
            </tr>
        </table>
</form>
</body>
</html>

servlet层文件:

package Servlet;
import java.io.IOException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import dao.Dao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
        /**
         * @see HttpServlet#HttpServlet()
         */
        public UserServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
        Dao dao = new Dao();
        
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
               req.setCharacterEncoding("utf-8");
               String method = req.getParameter("method");
               System.out.println(method);
               if ("add".equals(method)) {
                   System.out.println("ok");
                   String user = req.getParameter("username");
                   String password = req.getParameter("password");
                   String sex = req.getParameter("sex");
                   String name = req.getParameter("name");
                   String xuehao = req.getParameter("xuehao");
                   String mail = req.getParameter("mail");
                   String school = req.getParameter("xueyuan");
                   String xi = req.getParameter("xi");
                   String banji = req.getParameter("ban");
                   String nianfen = req.getParameter("year");
                   String place = req.getParameter("address");
                   String beizhu = req.getParameter("beizhu");
                   boolean pd=Dao.add(user, password, sex, name, xuehao, mail, school, xi, banji, nianfen, place, beizhu);
                   if(pd) {
                       req.setAttribute("message", "注册成功");
                       req.getRequestDispatcher("register.jsp").forward(req,resp);
                   }else {
                       req.setAttribute("message", "注册失败,请重新注册");
                       req.getRequestDispatcher("register.jsp").forward(req,resp);
                   }
               }
               
        }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

dao层文件:

package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import database.DB;
public class Dao {
       public static boolean add(String username,String password,String sex,String name,String xuehao,String mail,String school,String xi,String banji,String nianfen,String place,String beizhu) {
            Connection conn = null;
            PreparedStatement pstmt = null;
            boolean pd = false;
            System.out.println("add run!");
            try {
                //获取连接
                conn = DB.getConn();
                //编写语句
                String sql = "insert into student values(?,?,?,?,?,?,?,?,?,?,?,?)";
                //预编译
                pstmt = conn.prepareStatement(sql);
                //设置数据
                pstmt.setString(1, username);
                pstmt.setString(2, password);
                pstmt.setString(3, sex);
                pstmt.setString(4, name);
                pstmt.setString(5, xuehao);
                pstmt.setString(6, mail);
                pstmt.setString(7, school);
                pstmt.setString(8, xi);
                pstmt.setString(9, banji);
                pstmt.setString(10, nianfen);
                pstmt.setString(11, place);
                pstmt.setString(12, beizhu);
                //执行
                int res = pstmt.executeUpdate();
                //判断
                if(res>0) {
                    pd=true;
                }else {
                    pd=false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                
                DB.close(pstmt,conn);
            }
            return pd;
        }
}

连接数据库的文件:

package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {public static String db_url = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";

public static String db_user = "root";
public static String db_pass = "abc456";

public static Connection getConn () {
    Connection conn = null;
    
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动
        conn = DriverManager.getConnection(db_url, db_user, db_pass);
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    return conn;
}

/**
 * 关闭连接
 * @param state
 * @param 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) throws SQLException {
    Connection conn = getConn();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    String sql ="select * from USER";
    pstmt = conn.prepareStatement(sql);
    rs = pstmt.executeQuery();
    if(rs.next()){
        System.out.println("空");
    }else{
        System.out.println("不空");
    }
}


}

运行结果截图:

java web第一次课堂测试1

 java web第一次课堂测试1

 java web第一次课堂测试1

 java web第一次课堂测试1

 java web第一次课堂测试1

 java web第一次课堂测试1

点击添加按钮后数据库数据界面:

 java web第一次课堂测试1

由此可见,运行已成功

设计思路:

1.设计前端界面,并用jsp文件书写判别语句。用表格存储数据。

2.将表格存储的数据发送到servlet层,

3.servlet层发送到dao层进行数据库添加。

4.dao层调用DB层进行数据库连接。

遇到的问题:

在编写这个程序时,遇到了极其多的问题

最先出现的问题是,在进行创建web项目的时候,忘记了某个选项,导致少了web.xml文件,使得servlet层无法找到。

在进行查阅资料后,重新配置了servlet,但在添加后却没有发现jar包文件。在百度后发现需要把jar包放到tomcat下的lib文件夹才能调用。

解决了这个问题后,发现又提示数据库的编码方式不对,原来是没有设置好数据库的编码方式为UTF-8,在重新设置后,终于可用了。

通过这次过程,我意识到一些事情:

首先,就是在做东西前一定要理清思路,这次的问题就在于我做东西虎头虎脑的,没有理清在编写软件中的流程和细节问题。

再其次,就是对一些细小的事情并没有在意,导致最后发生很大的错误。

总的来说,这次学到了html中表格的写法,jsp的判断方法,数据库的连接方法。

相关推荐