前言:
学习Java后端开发的过程中,很多情况下都要和数据库打交道,如何通过Java程序去访问数据库,成为每一个后端开发人员必备的技能点。本文以一个简单的
项目将数据库(这里使用Mysql)、JDBC、Servlet、JSP串联起来,将其中的逻辑流畅地走一遍,由于需要用到JSP和Servlet,所以这里建立的项目
类型是Dynamic Web Project,在此声明:仅是自己的学习总结,如有不对的地方,还请指教,互相交流学习哈^^。
第一步 数据库及模型层的准备(模型层)
首先,自己的电脑上需要安装Mysql数据库,然后再数据库中建立自己项目中需要要到的数据库,数据库名为shopping;接着在shopping数据
库中创建数据表,表名为goods;然后向其中添加几条记录;这样,数据库方面的准备就完成啦!接着,需要针对项目中建立的数据表,设计对应的
JavaBean,用来存储存储从数据库读取的记录。
这里用到的sql文件:
SET FOREIGN_KEY_CHECKS=0 ;
DROP TABLE IF EXISTS `goods` ;
CREATE TABLE `goods` (
`id` int (11 ) NOT NULL AUTO_INCREMENT,
`name` varchar (50 ) DEFAULT NULL ,
`origin` varchar (50 ) DEFAULT NULL ,
`price` int (11 ) DEFAULT NULL ,
`stock` int (11 ) DEFAULT NULL ,
PRIMARY KEY (`id` )
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
package com.model;
/**
* 与数据库shopping中的goods数据表相对应的JavaBean
*/
public class Goods {
private int id;
private String name;
private int price;
private String origin;
private int stock;
public int getId ()
{
return id;
}
public void setId (int id)
{
this .id = id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this .name = name;
}
public int getPrice ()
{
return price;
}
public void setPrice (int price)
{
this .price = price;
}
public String getOrigin ()
{
return origin;
}
public void setOrigin (String origin)
{
this .origin = origin;
}
public int getStock ()
{
return stock;
}
public void setStock (int stock)
{
this .stock = stock;
}
}`
第二步 数据库连接的准备(服务层)
首先,下载JDBC所用的jar包,将jar包拷贝到项目的lib文件夹下,然后右击jar包,选择Build Path,将jar包添加到当前项目的路径
中;接着,进行获取数据库连接的代码编写;代码如下所示。
package com.dbhelper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 专门用于提供数据库连接的类
*/
public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver" ;
private static final String url = "jdbc:mysql://localhost:3306/shopping" ;
private static final String user = "root" ;
private static final String password = "root" ;
private static Connection conn = null ;
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection (){
if (conn==null ) {
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}
}
第三步 访问数据库的业务处理(服务层)
这里,我们将访问数据库的业务逻辑只局限在从数据库中读取响应的数据,其他的业务(如向数据库中写数据(增)、删除数据(删)、更新数据
(改))并没有进行代码的编写,但是这些操作的实现所需的知识点,项目中给出的两个业务逻辑处理方法都涵盖,只需要将对应的sql语句做适当
的修改即可。
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.model.Goods;
import com.dbhelper.DBHelper;
/**
* 专门用于提供对数据库进行处理的方法的类
*/
public class DBService {
private static Connection conn = DBHelper.getConnection();
public ArrayList<Goods> query () {
ArrayList<Goods> list = null ;
String sql = "select id,name,price,origin,stock from goods where 1=1" ;
PreparedStatement statement = null ;
ResultSet rs = null ;
Goods good = null ;
try {
statement = conn.prepareStatement(sql);
rs = statement.executeQuery();
if (rs==null )
{
return null ;
}
list = new ArrayList<>();
while (rs.next())
{
good = new Goods();
good.setId(rs.getInt("id" ));
good.setName(rs.getString("name" ));
good.setPrice(rs.getInt("price" ));
good.setOrigin(rs.getString("origin" ));
good.setStock(rs.getInt("stock" ));
list.add(good);
}
good = null ;
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (rs!=null )
{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null )
{
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
public Goods queryById (int id) {
Goods good = null ;
PreparedStatement statement = null ;
ResultSet rs = null ;
String sql = "select id,name,price,origin,stock from goods where id = ?" ;
try {
statement = conn.prepareStatement(sql);
statement.setInt(1 , id);
rs = statement.executeQuery();
if (rs == null )
{
return null ;
}
while (rs.next()) {
good = new Goods();
good.setId(rs.getInt("id" ));
good.setName(rs.getString("name" ));
good.setPrice(rs.getInt("price" ));
good.setOrigin(rs.getString("origin" ));
good.setStock(rs.getInt("stock" ));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (rs!=null ) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null ) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return good;
}
}
第四步 Servlet的准备(控制层)
项目中利用Servlet读取用户请求、调用业务处理层进行处理请求以及响应客户的请求。
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.DBService;
import com.model.Goods;
@SuppressWarnings ("serial" )
public class ServiceServlet extends HttpServlet {
@Override
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
@Override
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("post请求处理中..." );
String id = request.getParameter("idnum" );
System.out.println(id);
DBService dbservice = new DBService();
Goods good = dbservice.queryById(Integer.valueOf(id));
request.setAttribute("good" , good);
request.getRequestDispatcher("/result.jsp" ).forward(request, response);
}
}
第五步 JSP的准备(视图层)
这里采用两个JSP文件作为视图层,其中,query.jsp文件负责将客户的请求传送到Servlet中,由Servlet进行请求的接收、处理和响应
,这里的响应为将处理请求的结果传送到另一个jsp文件,该文件(result.jsp)将处理的结果展示到jsp页面上。
query.jsp文件:
<%@ page language="java" contentType="text/html; charset=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 >
<form name ="demandForm" action ="com/servlet/ServiceServlet" method ="post" >
<table >
<tr >
<td > 全部查询</td >
<td > <input type ="submit" name ="all" id ="all" value ="全部查询" /> </td >
</tr >
</table >
</form >
<form name ="demandForm1" action ="com/servlet/ServiceServlet" method ="post" >
<table >
<tr >
<td > id查询</td >
<td > <input type ="text" name ="idnum" id ="idnumber" /> </td >
<td > <input type ="submit" value ="id查询" /> </td >
</tr >
</table >
</form >
</body >
</html >
result.jsp文件:
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page import="com.model.Goods" language="java" %>
<!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 >
<%
Goods good = (Goods)request .getAttribute("good" );
%>
商品id:<%=good.getId() %> <br />
商品名称:<%=good.getName() %> <br />
商品价格:<%=good.getPrice() %> <br />
商品产地:<%=good.getOrigin() %> <br />
商品库存:<%=good.getStock() %> <br />
</body >
</html >
总结
以上就是整个项目的思路和处理流程,采用从模型层开始,接着控制层,最后视图层的顺序完成整个项目的开发!整个项目框架已经搭建好,
但是细节有待完善,本文的目的是将整体的框架搭建出来,使整个处理流程在逻辑上能够畅通。