新建一个Dynamic Web project项目

先导入这两个包 jstl-1.2.jre, ojdbc6.jre

我的sql是写在servlet层就没有写在Dao层了
大家可以自己修改一下就可以了
有需要的朋友就参考一下吧

下面是项目的结构目录
MVC增删改查之Oracle数据库

新建common 文件夹
新建taglib标签库
导入uri地址

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

这里使用的是Oracle自带的表
实体类 entity

package com.lizi.entity;

import java.sql.Date;

public class News {

	private int nid; //序号
	private String title;//新闻标题
	private String content1;//新闻内容
	private Date publishTime; //发表时间
	private String  author;//作者
	
	
	public News() {}//
	public News(String title, String content1, Date publishTime, String author) {
		this.title = title;
		this.content1 = content1;
		this.publishTime = publishTime;
		this.author = author;
	}
	public News(int nid, String title, Date publishTime, String author) {
		this.nid = nid;
		this.title = title;
		this.publishTime = publishTime;
		this.author = author;
	}
	public News(int nid, String title, String content1, Date publishTime, String author) {
		this.nid = nid;
		this.title = title;
		this.content1 = content1;
		this.publishTime = publishTime;
		this.author = author;
	}
	public int getNid() {
		return nid;
	}
	public void setNid(int nid) {
		this.nid = nid;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent1() {
		return content1;
	}
	public void setContent1(String content1) {
		this.content1 = content1;
	}
	public Date getPublishTime() {
		return publishTime;
	}
	public void setPublishTime(Date publishTime) {
		this.publishTime = publishTime;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	
}

Dao层

package com.lizi.Dao;

import java.util.ArrayList;

import com.lizi.entity.News;

public interface InewsDao {
     	//查询所有
       public  ArrayList<News> queryNews(String sql);
       //增删改通用
       public boolean exeUpdate(String sql,Object[] obj);
       //按Id查询
       public  ArrayList<News> queryByNews(String sql,String Id);
}

Dao层的实现类

package com.lizi.Dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import com.lizi.Dao.InewsDao;
import com.lizi.entity.News;
import com.lizi.util.DBUtil;

public class NewsDaoimpl implements InewsDao {

	//查询所有
	@Override
	public ArrayList<News> queryNews(String sql) {
		//初始化数据
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rSet=null;
		
		
		ArrayList<News> list=new ArrayList<>();
		try {
			//连接数据库
			conn=DBUtil.getConn();
			//设置预编译对象
			ps=DBUtil.getPreparedStatement(conn, sql);
			//拿到结果集
			rSet=ps.executeQuery();
			//循环
			while(rSet.next()) {
				int nid=rSet.getInt(1);
				String  title=rSet.getString(2);
				String  content1=rSet.getString(3);
				Date  publishTime=rSet.getDate(4);
				String  author =rSet.getString(5);
				
				list.add(new News(nid, title,content1, publishTime, author));
				System.out.println(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBUtil.closeAll(conn, ps, rSet);
		}
		return list;
	}

    //增删改通用
	@Override
	public boolean exeUpdate(String sql, Object[] obj) {
		boolean flag=false;
		//初始化数据
		Connection conn=null;
		PreparedStatement ps=null;
		 try {
			     //连接数据库
				conn=DBUtil.getConn();
				//设置预编译对象
				ps=DBUtil.getPreparedStatement(conn, sql);
				int index=1;
				for (Object o : obj) {
					ps.setObject(index, o);
					index++;
					System.out.println("打印"+o);
				}
				int row=ps.executeUpdate();
				if (row>0) {
					flag=true;
					System.out.println("操作成功!");
				}else {
					flag=false;
					System.out.println("操作失败!");
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	//按Id查询
	@Override
	public ArrayList<News> queryByNews(String sql,String Id) {
		//初始化数据
				Connection conn=null;
				PreparedStatement ps=null;
				ResultSet rSet=null;
				
				
				ArrayList<News> list=new ArrayList<>();
				try {
					//连接数据库
					conn=DBUtil.getConn();
					//设置预编译对象
					ps=DBUtil.getPreparedStatement(conn, sql);
					//拿到结果集
					ps.setObject(1, Id);
					rSet=ps.executeQuery();
					News news=null;
					//循环
					if(rSet.next()) {
						int nid=rSet.getInt(1);
						String  title=rSet.getString(2);
						String  content1=rSet.getString(3);
						Date  publishTime=rSet.getDate(4);
						String  author =rSet.getString(5);
						news=new News(nid, title,content1, publishTime, author);
						list.add(news);
						
						System.out.println(1);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					DBUtil.closeAll(conn, ps, rSet);
				}
				return list;
      }
}

Service层

package com.lizi.service;

import java.util.ArrayList;

import com.lizi.entity.News;

public interface newsService {
    //查询所有
	public ArrayList<News> querynews();
	//删除
	public boolean delNews(Object[] obj);
	//添加
	public boolean InsNews(Object[] obj);
	//根据Id查询
	public ArrayList<News> queryById(String Id);
	//根据Id修改
	public boolean updateNewsById(Object[] obj);
}

Service实现类

package com.lizi.service.impl;

import java.util.ArrayList;

import com.lizi.Dao.InewsDao;
import com.lizi.Dao.impl.NewsDaoimpl;
import com.lizi.entity.News;
import com.lizi.service.newsService;

public class newsServiceimpl implements newsService {
  InewsDao bean=new NewsDaoimpl();
	//查询所有
	@Override
	public ArrayList<News> querynews() {
		//写sql
		 String  sql="select * from news";
		//调用实现类的方法
		ArrayList<News> list=(ArrayList<News>)this.bean.queryNews(sql);
		return list;
	}
	
	
	//根据ID删除
	@Override
	public boolean delNews(Object[] obj) {
		//写sql
		String sql="delete news where  nid=?";
		boolean flag=bean.exeUpdate(sql, obj);
		return flag;
	}

 
	//添加
	@Override
	public boolean InsNews(Object[] obj) {
		//写sql
		String sql="insert into news values(?,?,?,to_timestamp(?,'yyyy-mm-dd hh24:mi:ss:ff'),?)";
		boolean flag=bean.exeUpdate(sql, obj);
		return flag;
	}


	//根据Id查询
	@Override
	public ArrayList<News> queryById(String Id) {
		//写sql
		String sql="select * from news where nid=?";
		//调用实体类的方法
		ArrayList<News> list=(ArrayList<News>)this.bean.queryByNews(sql, Id);
		return list ;
	}

//根据Id修改
	@Override
	public boolean updateNewsById(Object[] obj) {
		//写sql
		String sql="update news set title=?,content1=?,publishTime=to_date(?,'yyyy-mm-dd hh24:mi:ss') ,author =? where nid=?";
		boolean flag=bean.exeUpdate(sql, obj);
		return flag;
	}
}

DButil帮助类

package com.lizi.util;

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 DBUtil {

	// 驱动路径
	private static String driver = "oracle.jdbc.driver.OracleDriver";
	// 访问地址
	private static String url = "jdbc:oracle:thin:@localhost:1521:orac";
	// 数据库登录用户名
	private static String name = "scott";
	// 数据库登录密码
	private static String pwd = "tiger";

	static {
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConn() {
		Connection conn = null;

		try {
			conn = DriverManager.getConnection(url, name, pwd);
			if(conn!=null) {
				System.out.println("connection is ok");//测试连接成功或失败
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	//创建预编译对象 
		public static PreparedStatement getPreparedStatement(Connection cn,String sql) {
			PreparedStatement ps=null;
			try {
				ps=cn.prepareStatement(sql);		
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
			return ps;	
		}
		
		//关闭资源
		public static void closeAll(Connection ct,Statement st,ResultSet rs) {
			try {
				if(rs!=null) {			
					rs.close();
				}		
				if(st!=null) {
					st.close();	
				}
				if(ct!=null) {
					ct.close();	
				}			
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}		
		}
}

servlet层
在新建的那里直接新建servlet
就可以不用在麻烦的配置XML了
添加
AddNewsServlet

package com.lizi.web.servlet;

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 com.lizi.service.newsService;
import com.lizi.service.impl.newsServiceimpl;

@WebServlet("/addNewsServlet")
public class AddNewsServlet extends HttpServlet {
	// 格式化系列
	private static final long serialVersionUID = 1L;

	newsService service = new newsServiceimpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");

		String nid = request.getParameter("nid");
		String title = request.getParameter("title");
		String content1 = request.getParameter("content1");
		String publishTime = request.getParameter("publishTime");
		String author = request.getParameter("author");


		Object[] obj = new Object[] { nid, title, content1, publishTime, author };
		
		System.out.println(obj);
		boolean flag = service.InsNews(obj);
		if (flag == true) {
			response.sendRedirect("ShowNews");
		}
	}

}

删除
NewsDelete

package com.lizi.web.servlet;

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 com.lizi.service.newsService;
import com.lizi.service.impl.newsServiceimpl;

@WebServlet("/NewsDelete")
public class NewsDelete extends HttpServlet {
	// 格式化系列
	private static final long serialVersionUID = 1L;

	newsService service = new newsServiceimpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");

		String nid = request.getParameter("nid");

		Object[] obj = new Object[] { nid };

		boolean flag = service.delNews(obj);
		if (flag == true) {
			response.sendRedirect("ShowNews");
		}
	}

}

按ID查询
QueryNewsById

package com.lizi.web.servlet;

import java.io.IOException;
import java.util.ArrayList;

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 com.lizi.entity.News;
import com.lizi.service.newsService;
import com.lizi.service.impl.newsServiceimpl;

@WebServlet("/QueryNewsById")
public class QueryNewsById extends HttpServlet {
	// 格式化系列
	private static final long serialVersionUID = 1L;

	newsService service = new newsServiceimpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");

		String Id = request.getParameter("nid");
		System.out.println(Id);

		ArrayList<News> list = service.queryById(Id);

		request.setAttribute("news", list);

		request.getRequestDispatcher("updateNews.jsp").forward(request, response);
	}
}

查询全部
ShowNews

package com.lizi.web.servlet;

import java.io.IOException;
import java.util.ArrayList;

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 com.lizi.entity.News;
import com.lizi.service.newsService;
import com.lizi.service.impl.newsServiceimpl;

@WebServlet("/ShowNews")
public class ShowNews extends HttpServlet {
	// 格式化系列
	private static final long serialVersionUID = 1L;

	newsService service = new newsServiceimpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");

		ArrayList<News> list = (ArrayList<News>) this.service.querynews();
		//
		request.setAttribute("user", list);
		System.out.println(list);
		//
		request.getRequestDispatcher("ShowNews.jsp").forward(request, response);
	}
}

按ID修改
UpdateNewsServlet

package com.lizi.web.servlet;

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 com.lizi.service.newsService;
import com.lizi.service.impl.newsServiceimpl;

@WebServlet("/UpdateNewsServlet")
public class UpdateNewsServlet extends HttpServlet {
	// 格式化系列
	private static final long serialVersionUID = 1L;

	newsService service = new newsServiceimpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");

		String title = request.getParameter("title");
		String publishTime = request.getParameter("publishTime");
		String content1 = request.getParameter("content1");
		String author = request.getParameter("author");
		String nid = request.getParameter("nid");

		Object[] obj = new Object[] { title, publishTime, content1, author, nid };
		boolean flag = service.updateNewsById(obj);
		if (flag == true) {
			response.sendRedirect("ShowNews");
		}
	}
}

JSP页面
添加页面

AddNews.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>添加</title>
</head>
<body>
<form action="addNewsServlet" method="post">
     序号:<input  type="text" name="nid"/><br/>
     新闻标题:<input  type="text" name="title"/><br/>
     <div>新闻内容:</div>
     <textarea rows="8"  cols="30"  name="content1"  /></textarea><br/>
     发表时间:<input  type="text" name="publishTime"/><br/>
     作者:<input  type="text" name="author"/><br/>
          <input  type="submit" value="保存"/>
</form>
</body>
</html>

查询全部
ShowNews.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%@ include file="common/taglib.jsp" %>
<!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>新闻列表</title>
<style type="text/css">
</style>
<script type="text/javascript">
	function check(){
		var f=confirm("确定要删除这条新闻吗?");
		if(f==true){
			return true;
		}
		return false;
	}
	
</script>
</head>
<body>

<h3>新闻列表</h3>
<a  href="AddNews.jsp">添加新闻</a>
<div>
<table>
<tr>
<td>序号</td>
<td>新闻标题</td>
<td>发表时间</td>
<td>作者</td>
<td>删除</td>
<c:forEach var="news" items="${news}">
<tr>
<td><a href="QueryNewsById?nid=${news.nid}">${news.nid}</a></td>
<td>${news.title}</td>
<td>${news.publishTime}</td>
<td>${news.author}</td>
<td><a href="NewsDelete?nid=${news.nid}" onclick="return check()">删除</a></td>
</tr>
</c:forEach>
</tr>
</table>
</div>
</body>
</html>

按ID修改
UpateNews.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@include file="common/taglib.jsp" %>
<!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>111</title>
</head>
<body>
<form action="UpdateNewsServlet"  method="post">
<!-- hiddden 隐藏的 -->
<c:forEach  var="news" items="${news}">
     <input  type="hidden" name="nid"  value="${news.nid}"><br/>
新闻标题 :<input  type="text" name="title"  value="${news.title}"><br/>
新闻内容 :<input  type="text" name="publishTime"  value="${news.content1}"><br/>
发表时间 :<input  type="text" name="content1"  value="${news.publishTime}"><br/>
 作者 :<input  type="text" name="author"  value="${news.author}"><br/>
  <input  type="submit" value="保存">
 </c:forEach>
</form>
</body>
</html>

相关文章: