一.连接数据库
1、mysql数据库的安装和配置
在网上找到了篇关于mysql的安装详细说明,供读者自己学习
https://www.jb51.net/article/23876.htm
2、mysql的基本操作
找到了篇介绍MySQL的基本操作的文章,简单易懂,可以很快的学会
http://www.cnblogs.com/mr-wid/archive/2013/05/09/3068229.html#d22
3、创建数据库表
建议大家下载一些MySQL的可视化工具如SQLyog,navicat等相应的教程都可以在网上找到,就不在此和大家一一说明,在此以SQLyog为例。
打开SQLyog软件,打开该软件后,会弹出以下画面,点击继续。
进入链接配置界面,点击上方的New…按钮,输入链接名称创建一个链接
之后在配置界面输入链接密码。此密码就是在安装mysql时设置的密码。
输入密码后,点击连接,如果信息无误,则进入主界面。如下所示
创建数据库,在左侧现实数据库的区域,点击右键,选择“创建数据库”
输入数据库名称,字符编码选择UTF-8,然后点击创建,则在左侧现实出来了刚刚创建的数据库。
4、下载数据库对应的jar包并导入
在网上下载JDBC驱动然后导入,使用JDBC需要在工程中导入对应的jar包。数据库与JDBC包的对应关系可以参考各种数据库对应的jar包、驱动类名和URL格式。在Eclipse下的导入方法:
在工程的图标上右击,选择”Properties”,在”Java Bulid Path”中选择”Add External JARs…”,选择下载并解压后获得的jar包。
如果对MySQL进行操作,这时下面的import就不会报错了:
import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement;
import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; 以上三句导入语句可用import java.sql.*代替
二.实现增删改查
1、准备工作
1:test01文件夹(里面有所需的页面资源),我完成的是在里面添加增删改查操作
2:myeclipse(版本没什么要求) eclipse也行
3:数据库 MySQL
4:需要了解到的知识点:
servlet
EL与JSTL表达式
项目的基本框架搭建(javaweb经典三层框架)
5:在myeclipse中建立对应的包结构
2、项目的基本框架搭建
所谓三层框架分别为表述层(WEB层)、业务逻辑层()、数据访问层()。
web层(action):包含JSP和Servlet等与web相关的内容,负责与浏览器的响应和请求;
业务层(service):只关心业务逻辑;
数据层(dao):封装了对数据库的访问细节,数据操作类;
关系:web层依赖业务层 业务层依赖数据层(这个关系很重要)
ps:除了以上三层框架是我们在写一个javaweb项目必须的外,还需要一个实体类(entity)。
3、实现数据库的连接
需要在MySQL中创建所需数据库,并将表建好。
在dao下新建一个DBConn类用来处理对数据进行连接。 这是MySQL的连接方式
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { //eshop为数据库名称,db_user为数据库用户名db_password为数据库密码 public static String db_url = "jdbc:mysql://localhost:3306/eshop?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"; public static String db_user = "数据库用户名"; public static String db_password = "数据库密码"; public static Connection getConn() { Connection conn = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(db_url, db_user, db_password); System.out.println("连接成功"); } catch (Exception e) { System.out.println("连接失败"); 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(); } } } }
4、建立实体类
在entity包下创建School实体类(实体类中的对象对应数据库表中的字段数据)
package entity; public class School{ private String classname; private String classteacher; private String classplace; public String getclassname() { return classname; } public void setclassname(String classname) { this.classname=classname; } public String getclassteacher() { return classteacher; } public void setclassteacher(String classteacher) { this.classteacher=classteacher; } public String getclassplace() { return classplace; } public void setclassplace(String classplace) { this.classplace=classplace; } }
5、实现增删改查方法
创建方法类,这里有两种方法
1:在dao包中创建一个SchoolDao接口,里面写增删改查的方法,再在dao中创建SchoolDaoImpl类来实现接口,并实现之中的方法。
SchoolDao接口:
package dao; import java.util.List; import entity.School; public interface SchoolDao { public boolean add(School school) ; public List<School>select(); public boolean update(String classname,String classteacher,String classplace); public boolean delete(String classname); public List<School>selectclassname(String classname); }
SchoolDaoImpl类(包含增删改查操作):
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import entity.School; public class SchoolDaoImpl implements SchoolDao{ Connection conn=(Connection)DBUtil.getConn(); @Override public boolean add(School school) { boolean flag=false; try { String sql="insert into school values(\'"+school.getclassname()+"\',\'"+school.getclassteacher()+"\',\'"+school.getclassplace()+"\')"; PreparedStatement pstmt = conn.prepareStatement(sql); int i = pstmt.executeUpdate(); pstmt.close(); conn.close(); if(i>0) { flag = true; } }catch(SQLException e) { e.printStackTrace(); } return flag; } @Override public List<School> select(){ List<School> list = new ArrayList<School>(); try { String sql="select * from school"; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { School school=new School(); school.setclassname(rs.getString("classname")); school.setclassteacher(rs.getString("classteacher")); school.setclassplace(rs.getString("classplace")); list.add(school); } rs.close(); pstmt.close(); conn.close(); }catch(SQLException e) { e.printStackTrace(); } return list; } @Override public List<School>selectclassname(String classname){ List<School> list = new ArrayList<School>(); try { String sql="select * from school where classname=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1,classname ); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { School school=new School(); school.setclassname(rs.getString("classname")); school.setclassteacher(rs.getString("classteacher")); school.setclassplace(rs.getString("classplace")); list.add(school); } rs.close(); pstmt.close(); conn.close(); }catch(SQLException e) { e.printStackTrace(); } return list; } @Override public boolean delete(String classname) { boolean flag=false; try { String sql="delete from school where classname=\'"+classname+"\'"; PreparedStatement pstmt = conn.prepareStatement(sql); int i = pstmt.executeUpdate(); pstmt.close(); conn.close(); if(i>0) flag = true; }catch(SQLException e) { System.out.println("删除失败"); e.printStackTrace(); } return flag; } public boolean update(String classname,String classteacher,String classplace) { boolean flag=false; try { String sql="update school set classteacher=\'"+classteacher+"\',classplace=\'"+classplace+"\' where classname=\'"+classname+"\'"; PreparedStatement pstmt = conn.prepareStatement(sql); int i = pstmt.executeUpdate(); pstmt.close(); conn.close(); if(i>0)flag = true; }catch(SQLException e) { e.printStackTrace(); } return flag; } }
2:在service包中创建StudentService类,在dao包中创建StudentDao类来实现StudentService类中的方法。(具体操作以后更新)
6、实现servelet和对应jsp页面
Servlet有两种方式创建,一种手工创建。另一种程序自动生成。前者自己创建java类,实现Servlet具体内容,然后需要去WEB_INF下的web.xml去配置servlet . 而后者则直接由程序替我们配置好了Servlet
1:增
创建SchoolAddServlet
package SchoolAddServlet; import java.io.IOException; 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 dao.SchoolDao; import dao.SchoolDaoImpl; import entity.School; @WebServlet("/SchoolAddServlet") public class SchoolAddServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String classname=request.getParameter("classname"); String classteacher=request.getParameter("classteacher"); String classplace=request.getParameter("classplace"); School Subject =new School(); Subject.setclassname(classname); Subject.setclassteacher(classteacher); Subject.setclassplace(classplace); SchoolDao sd = new SchoolDaoImpl(); try{ sd.add(Subject); response.sendRedirect(request.getContextPath() + "/school.jsp"); }catch(Exception e){ System.out.println("添加失败"); e.printStackTrace(); } } }
schooladd.jsp页面部分
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="addSubjectForm" align="center">
<form action="SchoolAddServlet" method="post">
<tr>
<td>课程名称:</td>
<td><input type="text" name="classname" size="20"></td>
</tr>
<tr>
<td>任课老师:</td>
<td><input type="text" name="classteacher" size="20"></td>
</tr>
<tr>
<td>上课地点:</td>
<td><input type="text" name="classplace" size="20"></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input type="submit" value="录入">
</div>
</td>
</tr>
</form>
</div>
</body>
</html>
action=“SchoolAddServlet”为SubjectAddServlet在web.xml中的URL目录,即在Servlet中的主类名称
当在servlet中完成的操作需要获取页面表单等的数据时,需要在页面中指向对应的servlet。
2、删
创建SchoolDeleteServlet类
package SchoolDeleteServlet; import java.io.IOException; 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 dao.SchoolDao; import dao.SchoolDaoImpl; import entity.School; @WebServlet("/SchoolDelete") public class SchoolDelete extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String classname = request.getParameter("classname"); /*String classteacher=request.getParameter("classteacher"); String classplace=request.getParameter("classplace");*/ School school=new School(); school.setclassname(classname); /*school.setclassteacher(classteacher); school.setclassplace(classplace); */ SchoolDao sd = new SchoolDaoImpl(); try { sd.delete(classname); response.sendRedirect(request.getContextPath() + "/school.jsp"); }catch(Exception e) { System.out.println("删除失败"); e.printStackTrace(); } } }
schooldelete.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="addSubjectForm" align="center">
<form action="SchoolDelete" method="post">
<tr>
<td>课程名称:</td>
<td><input type="text" name="classname" size="20"></td>
</tr>
<tr>
<td>任课老师:</td>
<td><input type="text" name="classteacher" size="20"></td>
</tr>
<tr>
<td>上课地点:</td>
<td><input type="text" name="classplace" size="20"></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input type="submit" value="删除">
</div>
</td>
</tr>
</form>
</div>
</body>
</html>
3、改
创建SchoolUpdate
package SchoolUpdate; import java.io.IOException; 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 dao.SchoolDao; import dao.SchoolDaoImpl; import entity.School; @WebServlet("/SchoolUpdate") public class SchoolUpdate extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String classname=request.getParameter("classname"); String classteacher=request.getParameter("classteacher"); String classplace=request.getParameter("classplace"); SchoolDao sd = new SchoolDaoImpl(); try{ sd.update(classname,classteacher,classplace); response.sendRedirect(request.getContextPath() + "/school.jsp"); }catch(Exception e){ System.out.println("更新失败"); e.printStackTrace(); } } }
schoolupdate.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="addSubjectForm" align="center">
<form action="SchoolUpdate" method="post">
<tr>
<td>课程名称:</td>
<td><input type="text" name="classname" size="20"></td>
</tr>
<tr>
<td>任课老师:</td>
<td><input type="text" name="classteacher" size="20"></td>
</tr>
<tr>
<td>上课地点:</td>
<td><input type="text" name="classplace" size="20"></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input type="submit" value="更改">
</div>
</td>
</tr>
</form>
</div>
</body>
</html>
4、查
这里需要完成两个查询(查询返回列表;查询返回列表详细)
查询返回列表:
SchoolSelect类
package SchoolSelect; import java.io.IOException; import java.util.List; 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 dao.SchoolDao; import dao.SchoolDaoImpl; import entity.School; @WebServlet("/SchoolSelect") public class SchoolSelect extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); SchoolDao sd = new SchoolDaoImpl(); List<School> list = sd.select(); request.setAttribute("list", list); request.getRequestDispatcher("/schoolselect.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
注意:当不需要页面的参数时,页面由servlet引出
转发(request.getRequestDispatcher().forward();)和重定向(response.sendRedirect();)区别:
(1).重定向的执行过程:Web服务器向浏览器发送一个http响应--》浏览器接受此响应后再发送一个新的http请求到服务器--》服务器根据此请求寻找资源并发送给浏览器。它可以重定向到任意URL,不能共享request范围内的数据。
(2).重定向是在客户端发挥作用,通过新的地址实现页面转向。
(3).重定向是通过浏览器重新请求地址,在地址栏中可以显示转向后的地址。
(4).转发过程:Web服务器调用内部方法在容器内部完成请求和转发动作--》将目标资源发送给浏览器,它只能在同一个Web应用中使用,可以共享request范围内的数据。
(5).转发是在服务器端发挥作用,通过forward()方法将提交信息在多个页面间进行传递。
(6).转发是在服务器内部控制权的转移,客户端浏览器的地址栏不会显示出转向后的地址。
schoolselect.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<
<div id="manageSubject" align="center"><!--查看试题-->
<table width="95%" cellspacing="10">
<tr align="center">
<td>课程名称</td>
<td><input type="text" name="classname" size="20"></td>
<td>任课老师</td>
<td><input type="text" name="classname" size="20"></td>
<td>上课地点</td>
<td><input type="text" name="classname" size="20"></td>
</tr>
<c:forEach var="u" items="${list }">
<tr align="center">
<td>${u.classname}</td>
<td><a href="SchoolSelectclassname?subjectID=${u.classname }">查看</a></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
注意:
这里的顺序是,先访问的是SubjectListServlet,在转发到此页面,此页面的查看和删除又通过对应的servlet来实现对应的功能。
查询返回列表详细:
创建Schoolselectclassname
package SchoolSelect; import java.io.IOException; import java.util.List; 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 dao.SchoolDao; import dao.SchoolDaoImpl; import entity.School; /** * Servlet implementation class SchoolSelectclassname */ @WebServlet("/SchoolSelectclassname") public class SchoolSelectclassname extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); SchoolDao sd = new SchoolDaoImpl(); List<School> list = sd.selectclassname(request.getParameter("classname")); request.setAttribute("list", list); request.getRequestDispatcher("/schoolshow.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
注意:
这个查询方法需要通过限制条件classname来查询,不然显示出来的是所有的数据
schoolshow.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="schoolshow" align="center"><!--显示试题-->
<table border="0" cellspacing="10" cellpadding="0">
<c:forEach var="u" items="${list }">
<tr>
<td>课程名称:</td>
<td>${u.classname }</td>
</tr>
<tr>
<td>任课老师:</td>
<td>${u.classteacher }</td>
</tr>
<tr>
<td>上课地点:</td>
<td>${u.classplace }</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
注意:
页面同样运用的是EL和jstl表达式
school.jsp主页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="addSubjectForm" align="center">
<form action="SubjectAddServlet" method="post">
<tr>
<td>课程基本信息管理系统 </td></tr>
<ul>
<li><a href="http://localhost:8080/School/schooladd.jsp">课程信息录入 </a></li>
<li><a href="http://localhost:8080/School/schoolupdate.jsp">课程信息修改 </a></li>
<li><a href="http://localhost:8080/School/schooldelete.jsp">删除课程信息 </a></li>
<li><a href="http://localhost:8080/School/schoolselect.jsp">查询课程信息 </a></li>
</ul>
</form>
</body>
</html>