建立Java Web Project并进行JDBC操作

来源:互联网 发布:mac怎么连接airplay 编辑:程序博客网 时间:2024/05/18 17:03

最近正在学习Java Web,下面是练习的一个Student数据库的小项目。(因为只是刚刚做,其中有不对的,还请谅解)

实验内容:

1、首先搭建JSP的服务器运行环境,并进行测试。

2、新建一Web项目,部署程序到服务器,启动服务器程序,运行该项目的首页面文件(index.jsp),查看其转译后的.java文件。

3、JDBC操作单个表,进行表中数据的增、删、改、查功能,利用JSP页面进行数据的查询操作和增加操作。

 

实验步骤:

前期工作:

一、软件安装与配置

1、安装JDK(根据操作系统位数,决定是安装32位还是64位) ,建立安装JDK1.7之上版本;

2、安装MyEclipse(eclipse也可以);

3、安装数据库MySQL,注意记录密码,JAVA编程时使用;

4、配置Tomcat服务器,注意不使用系统自带服务器;

5、安装dreamweaver.(这里没用到)

建立工程

思路:三层架构(数据访问层、业务逻辑层、界面层)JDBC操作单表数据维护的实现:

1 创建数据库school及表student

2 创建三个层次的包:

cn.sdut.dao——放置数据访问层的类和接口

cn.sdut.biz——放置业务逻辑层的类和接口

cn.sdut.view——放置界面层的类和接口


3 创建cn.sdut.po包,里面放置Student.java类——JavaBean

4 各层次的程序代码:

(1)数据访问层:(cn.sdut.dao)

BaseDao.java——各种公共变量、数据库的连接和各种公共变量的关闭方法

StudentDao.java——学生表数据的增、删、改、查方法

(2)业务逻辑层:(cn.sdut.biz)

(3)界面层:(cn.sdut.view)

Main.java——测试

前端步骤级代码

1,建立名称为“student”web project 其下包括

a)  Cn.sdut.dao包
BaseDao java文件
StudentDao java 文件(继承BaseDao.java)

b)  Cn.sdut.biz包

c)  Cn.sdut.view包
Main.java(主函数)

d)  Co.sdut.po包

Student.java

 

2, 下面是每个类的代码:

a)Studen.java

package cn.sdut.po; public classStudent {   private int id;   private Stringname;   private Stringbirthday;   private float score;     public void setBirthday(Stringbirthday) {         this.birthday = birthday;      }   public void setId(int id) {      this.id = id;   }   public void setName(String name) {      this.name = name;   }   public void setScore(float score) {      this.score = score;   }   public String getBirthday() {      return birthday;   }   public String getName() {      return name;   }   public float getScore() {      return score;   }   public int getId() {      return id;   }   @Override   public String toString() {      return "Student [id="+ id + ", name="+ name+ ", birthday="            +birthday+ ", score=" + score+ "]";   }}


b) BaseDao.java

package cn.sdut.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 com.mysql.jdbc.Statement; public classBaseDao {   // 1 定义数据库访问公共变量   Connectioncon;   PreparedStatement pst;   ResultSetrs;   // 2 定义数据库的链接方法   public Connection getConn() {      // 1 加载jdbc驱动       try {         Class.forName("com.mysql.jdbc.Driver");      }catch(ClassNotFoundException e) {         // TODO Auto-generated catch block         e.printStackTrace();      }      // 2 得到数据库的链接      try {         Stringurl = "jdbc:mysql://localhost:3305/school";         con = DriverManager.getConnection(url,"root","mysql");      }catch(Exception e) {         // TODO Auto-generated catch block         e.printStackTrace();      }      return con;   }    // 3 关闭conn,pst,rs   public void closeAll() {      try {         if (rs !=null) {            rs.close();         }         if (pst !=null) {            pst.close();         }         if (con !=null) {            con.close();         }      }catch(SQLException e) {         // TODO Auto-generated catch block         e.printStackTrace();      }   }}


c)StudenDao.java

packagecn.sdut.dao; importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.ArrayList;importjava.util.List; importcn.sdut.po.Student; publicclass StudentDao extends BaseDao {   //建立student表   public boolean creat() {      boolean result = false;       try {         con = getConn();         String sql = "create tablestudent(id int primary key auto_increment,name varchar(20) not null,birthdaydate ,score float(1));";         pst= con.prepareStatement(sql);         result = pst.execute();      } catch (SQLException e) {         // TODO Auto-generated catch block         e.printStackTrace();      }      return result;   }   // 增   public int add(Student stu) {      int result = 0;      try {         con = getConn();         String sql = "insert intostudent(name,birthday,score,id) values(?,?,?,?)";         pst = con.prepareStatement(sql);         pst.setString(1, stu.getName());         pst.setString(2, stu.getBirthday());         pst.setFloat(3, stu.getScore());         pst.setInt(4, stu.getId());         result = pst.executeUpdate();// 可执行DML类型(insert,updata,delete),返回更新所影响的行数      } catch (SQLException e) {         // TODO Auto-generated catch block         e.printStackTrace();      } finally {         closeAll();      }      return result;   }    // 删   public int del(int id) {      int result = 0;       try {         con = getConn();         String sql = "delete from studentwhere id=?";         pst = con.prepareStatement(sql);         pst.setInt(1, id);         result = pst.executeUpdate();      } catch (SQLException e) {         // TODO Auto-generated catch block         e.printStackTrace();      }      return result;   }    // 改   public int updata(Student stu) {      int result = 0;      try {         con = getConn();         String sql = "update student setname=? ,birthday=?,score=?  whereid=?";         pst = con.prepareStatement(sql);         pst.setString(1, stu.getName());         pst.setString(2, stu.getBirthday());         pst.setFloat(3, stu.getScore());         pst.setInt(4, stu.getId());         result = pst.executeUpdate();      } catch (SQLException e) {         // TODO Auto-generated catch block         e.printStackTrace();      } finally {         closeAll();      }      return result;   }    // 查   public List<Student> queryAll() {      List<Student> students = newArrayList<Student>();       try {         con = getConn();         String sql = "select * fromstudent";          pst = con.prepareStatement(sql);         ResultSet rs = pst.executeQuery();         while (rs.next()) {            Student stu = new Student();            stu.setId(rs.getInt(1));            stu.setName(rs.getString(2));            stu.setBirthday(rs.getString(3));            stu.setScore(rs.getFloat(4));            students.add(stu);         }      } catch (SQLException e) {         // TODO Auto-generated catch block         e.printStackTrace();      } finally {         closeAll();      }      return students;
   }

}

d)Main.java

packagecn.sdut.view; //import java.util.Iterator;import java.util.List; import cn.sdut.dao.StudentDao;import cn.sdut.po.Student; public class Main {   publicstatic void main(String[] args) {      StudentDaostudentDao = new StudentDao();      Studentstudent = new Student();      studentDao.creat();      /*student.setId(2);      student.setName("xueba");      student.setBirthday("1995-1-1");      student.setScore(77);      studentDao.add(student);*/      student.setId(1);      student.setName("66");      student.setBirthday("1999-1-1");      student.setScore(88);           //studentDao.add(student);           //studentDao.del(4);           studentDao.updata(student);      List<Student>students = studentDao.queryAll();            for(Student stu:students){System.out.println(stu); }             /*for(Iterator<Student> stu = students.iterator(); stu.hasNext();) {         System.out.println(stu);      }*/   }}

3,启动TomCat服务器

4,执行Main函数得到:


说明测试成功。

前端代码及其步骤:

不要忘记将mysql-connector-java-bin.jar放到bin目录下

建立增删改的各个jsp文件及其操作jsp文件


jsp文件如下:

 1)index.jsp

<%@pageimport="cn.sdut.po.Student"%><%@pageimport="cn.sdut.dao.StudentDao"%><%@ page language="java"import="java.util.*"pageEncoding="utf-8"%><%   Stringpath = request.getContextPath();   StringbasePath = request.getScheme() + "://"         +request.getServerName() + ":" + request.getServerPort()         +path + "/";%><%   StudentDaost=newStudentDao();   List<Student>stuList = st.queryAll();    %><!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN"><html><head><basehref="<%=basePath%>"> <title>My JSP'index.jsp' starting page</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="This is my page"><!--   <linkrel="stylesheet" type="text/css"href="styles.css">   --></head> <body>   <tableborder="1">      <tr>         <thwidth="50">序号</th>         <thwidth="50">姓名</th>         <thwidth="100">出生年月</th>         <thwidth="50">成绩</th>      </tr>   <%         for (Student stu : stuList){            out.print("<tr>");            out.print("<td>");            out.print(stu.getId());            out.print("</td>");                       out.print("<td>");            out.print(stu.getName());            out.print("</td>");                       out.print("<td>");            out.print(stu.getBirthday());            out.print("</td>");            out.print("<td>");            out.print(stu.getScore());            out.print("</td>");            out.print("</tr>");         }      %>   </table>   <ul>      <li><ahref="addStudent.jsp">增加学生</a></li>      <li><ahref="delStudent.jsp">删除学生</a></li>      <li><ahref="updateStudent.jsp">更新信息</a></li></body></html>


2增加学生

    a)addStudent.jsp

<%@ page language="java"import="java.util.*"    contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPEhtmlPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"><title>增加学生</title></head><body>    <formaction="doAdd.jsp"method="post">       <table>           <caption>增加学生</caption>           <tr>              <td>姓名:</td>              <td><inputtype="text"name="name"/></td>           </tr>           <tr>              <td>出生年月:</td>              <td><inputtype="text"name="birthday"/></td>           </tr>           <tr>              <td>成绩:</td>              <td><inputtype="text"name="score"/></td>           </tr>           <tralign="center">              <tdcolspan="2"><inputtype="submit"value="确定"/><input                  type="reset"value="取消"/></td>           </tr>       </table>    </form></body></html>


 bdoStuden.jsp

<%@ page language="java"contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@pageimport="cn.sdut.dao.StudentDao"%><%@pageimport="cn.sdut.po.Student"%><!DOCTYPEhtmlPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"><title>Insert titlehere</title></head><body>    <%       //1 接受客户端传来的数据并封装成Student类的对象        request.setCharacterEncoding("utf-8");       String name = request.getParameter("name");       String birthday = request.getParameter("birthday");       String score1 = request.getParameter("score");       float score = Float.parseFloat(score1);       Student student = new Student();       student.setName(name);       student.setBirthday(birthday);       student.setScore(score);        //2 调用StudentDao的add方法,向数据库表中增加记录       StudentDao studentDao = new StudentDao();       studentDao.add(student);        //3 转向index.jsp,展示最新的表中的数据       response.sendRedirect("index.jsp");    %></body></html>


5,打开浏览器输入如下:


点击“增加学生”


点击“确认”


3删除学生

a)  delStuden.jsp代码

<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%><%   Stringpath = request.getContextPath();   StringbasePath = request.getScheme() + "://"         +request.getServerName() + ":" + request.getServerPort()         +path + "/";%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN"><html><head><basehref="<%=basePath%>"> <title>My JSP 'delStudent.jsp'starting page</title> <metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="This is my page"><!--   <linkrel="stylesheet" type="text/css"href="styles.css">   --> </head> <body>   <formaction="doDel.jsp"method="post">   <table>      <caption>删除学生</caption>      <tr>         <td>序号:</td>         <td><inputtype="text"name="id"></td>      </tr>      <tr>         <tdalign="center"colspan="2"><inputtype="submit"value="确认"><input            type="reset"value="取消"></td>      </tr>   </table>   </form></body></html> 


b)  doDel.jsp代码

<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%><%@pageimport="cn.sdut.dao.StudentDao" %><%String path =request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN"><html> <head>   <basehref="<%=basePath%>">      <title>My JSP 'doDel.jsp' starting page</title>      <metahttp-equiv="pragma"content="no-cache">   <metahttp-equiv="cache-control"content="no-cache">   <metahttp-equiv="expires"content="0">      <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">   <metahttp-equiv="description"content="This is my page">   <!--   <linkrel="stylesheet" type="text/css"href="styles.css">   -->  </head>  <body>   <%      request.setCharacterEncoding("utf-8");      String ids=request.getParameter("id");      int id = Integer.parseInt(ids);      StudentDao stuDao=new StudentDao();      stuDao.del(id);      response.sendRedirect("index.jsp");    %> </body></html>


 

点击“删除学生”


点击“确认”后


4更改信息

a) updateStudent.jsp代码

<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%><%   Stringpath = request.getContextPath();   StringbasePath = request.getScheme() + "://"         +request.getServerName() + ":" + request.getServerPort()         +path + "/";%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN"><html><head><basehref="<%=basePath%>"> <title>My JSP'updateStudent.jsp' starting page</title> <metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="This is my page"><!--   <linkrel="stylesheet" type="text/css"href="styles.css">   --> </head> <body>   <formaction="doUpdate.jsp"method="post">      <table>         <caption>更新信息</caption>         <tr>            <td>序号:</td>            <td><inputtype="text"name="id"></td>         </tr>         <tr>            <td>姓名:</td>            <td><inputtype="text"name="name"></td>         <tr>            <td>出生年月:</td>            <td><inputtype="text"name="birthday"></td>         <tr>            <td>分数:</td>            <td><inputtype="text"name="score"></td>         </tr>         <tr>            <tdalign="center"colspan="2"><inputtype="submit"value="确定"><input                type="reset"value="取消"></td>      </table>   </form></body></html>


c)  doUpdate.jsp代码

<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%><%@ page import="cn.sdut.dao.StudentDao"%><%@ page import="cn.sdut.po.Student"%><%String path =request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN"><html> <head>   <basehref="<%=basePath%>">      <title>My JSP 'doUpdate.jsp' starting page</title>      <metahttp-equiv="pragma"content="no-cache">   <metahttp-equiv="cache-control"content="no-cache">   <metahttp-equiv="expires"content="0">      <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">   <metahttp-equiv="description"content="This is my page">   <!--   <linkrel="stylesheet" type="text/css"href="styles.css">   -->  </head>  <body>   <%      request.setCharacterEncoding("utf-8");      String ids=request.getParameter("id");      String name=request.getParameter("name");      Stringbirthday=request.getParameter("birthday");      String sco=request.getParameter("score");      int id=Integer.parseInt(ids);      float score=Float.parseFloat(sco);           Student stu=new Student();      stu.setId(id);      stu.setName(name);      stu.setBirthday(birthday);      stu.setScore(score);           StudentDao stuDao =new StudentDao();      stuDao.updata(stu);           response.sendRedirect("index.jsp");    %> </body></html>


选择“更新信息”


点击“确认”


这样,一个简单的java web项目就完成了。

0 0