Java MVC 增删改查 实例

需求:增加新部门的功能,对应数据库表示Oracle的dept表

一、Java MVC 增

实现:

1、视图层(V):注册部门 deptUpdate.jsp

2、控制层(C):

3、模型层(M):

二、Java MVC 删

三、Java MVC 改

四、Java MVC 查

全部代码如下:

主页面:index.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>index page</title>
<link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<%@ include file="/view/top.jsp" %>
<ul>
    <li>员工管理
        <ul>
            <li><a href="/web01/empController">员工查询</a></li>
            <li>注册员工</li>
        </ul>
    </li>
    <li>部门管理
        <ul>
            <li><a href="/web01/deptController?callTp=deptList">部门查询</a></li>
            <li><a href="/web01/view/deptAdd.jsp">注册部门</a></li>
        </ul>
    </li>
    <li>系统管理
        <ul>
            <li><a href="/web01/requestInfoController?callTp=requestInfoPageList&now_page_num=1">访问日志查询</a></li>
        </ul>
    </li>
</ul>
</body>
</html>

部门查询:deptList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<%@ include file="top.jsp" %>
<form action="/web01/deptController" method="get">
部门名称:<input type="text" name="dnameTxt">
城市:<input type="text" name="locTxt">
<input type="submit" value="Search">
<input type="hidden" name="callTp" value="deptList">
<br/>
<table>
    <tr>
        <th>部门编号</th>
        <th>部门名称</th>
        <th>地点</th>
        <th>更新操作</th>
        <th>删除操作</th>
    </tr>
    <c:forEach items="${requestScope.deptBeanList}" var="dept">
    <tr>
        <td><c:out value="${dept.deptno }" default=" "></c:out></td>
         <td><c:out value="${dept.dname }" default=" "></c:out></td>
        <td><c:out value="${dept.loc }" default=" "></c:out></td>
        <td><a href="/web01/deptController?callTp=deptUpdate&deptno=${dept.deptno }">更改</a></td>
        <td><a href="/web01/deptController?callTp=deptDelete&deptno=${dept.deptno }">删除</a></td>
    </tr>
    </c:forEach>
</table>
<em style="color: red"><c:out value="${requestScope.updateResultMsg }"></c:out></em>
<em style="color: red"><c:out value="${requestScope.deleteResultMsg }"></c:out></em>
<em style="color: red"><c:out value="${requestScope.addResultMsg }"></c:out></em>
</form>
<%@ include file="bottom.jsp" %>
</body>
</html>

部门更新:deptUpdate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<%@ include file="top.jsp" %>
<form action="/web01/deptController" method="get">
部门编号:<input type="text" disabled="disabled" value="${requestScope.deptBean.deptno}"><br>
部门名称:<input type="text" name="dnameTxt" value="${requestScope.deptBean.dname}"><br>
城市:<input type="text" name="locTxt" value="${requestScope.deptBean.loc}"><br>
<input type="submit" value="Save">
<input type="hidden" name="callTp" value="deptSave">
<input type="hidden" name="deptno" value="${requestScope.deptBean.deptno}"">
<br/>
</form>
<%@ include file="bottom.jsp" %>
</body>
</html>

增加部门:deptAdd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<link href="/web01//css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<%@ include file="top.jsp" %>
<form action="/web01/deptController" method="get">
部门名称:<input type="text" name="dnameTxt" value="" maxlength="14"><br>
城市:<input type="text" name="locTxt" value="" maxlength="13"><br>
<input type="submit" value="Add">
<input type="hidden" name="callTp" value="deptAdd">
<br/>
</form>
<%@ include file="bottom.jsp" %>
</body>
</html>

部门控制器:DeptController.java

package com.test.biz.controller;

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.test.biz.bean.DeptBean;
import com.test.biz.service.DeptService;
import com.test.system.service.RequestInfoService;

/**
 * Servlet implementation class deptController
 */
@WebServlet("/DeptController")
public class DeptController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeptController() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestInfoService ris = new RequestInfoService();
        ris.saveRequestInfo(request);

        DeptService ds = new DeptService();
        DeptBean deptBean = new DeptBean();

        String callTp = request.getParameter("callTp");
        System.out.println("----callTp : "+callTp);
        if (callTp.equals("deptList")) {
            deptBean.setDname(request.getParameter("dnameTxt"));
            deptBean.setLoc(request.getParameter("locTxt"));
            ArrayList<DeptBean> deptBeanList = ds.deptList(deptBean);            

            request.setAttribute("deptBeanList", deptBeanList);
            request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
        } else if (callTp.equals("deptUpdate")) {
            deptBean.setDeptno(Integer.parseInt(request.getParameter("deptno")));
            deptBean = ds.deptById(deptBean.getDeptno());

            request.setAttribute("deptBean", deptBean);
            request.getRequestDispatcher("/view/deptUpdate.jsp").forward(request, response);
        } else if (callTp.equals("deptSave")) {
            deptBean.setDname(request.getParameter("dnameTxt"));
            deptBean.setLoc(request.getParameter("locTxt"));

            deptBean.setDeptno(Integer.parseInt(request.getParameter("deptno")));

            int updateInt = ds.deptSave(deptBean);
            if (updateInt == 1) {
                request.setAttribute("updateResultMsg", "更新成功!");
            } else {
                request.setAttribute("updateResultMsg", "更新失败!");
            }

            request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
        } else if (callTp.equals("deptDelete")) {
            int deleteInt = ds.deptDelete(Integer.parseInt(request.getParameter("deptno")));

            if (deleteInt == 1) {
                request.setAttribute("deleteResultMsg", "删除成功!");
            } else {
                request.setAttribute("deleteResultMsg", "删除失败!");
            }
            request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
        } else if (callTp.equals("deptAdd")) {
            String dname = request.getParameter("dnameTxt");
            String loc = request.getParameter("locTxt");

            int deptno = ds.getNextDetpno();

            DeptBean dept = new DeptBean();
            dept.setDeptno(deptno);
            dept.setDname(dname);
            dept.setLoc(loc);

            int addInt = ds.deptAdd(dept);
            if (addInt == 1) {
                request.setAttribute("addResultMsg", "添加成功!");
            } else {
                request.setAttribute("addResultMsg", "添加失败!");
            }
            request.getRequestDispatcher("/view/deptList.jsp").forward(request, response);
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}

部门服务层:DeptService.java

package com.test.biz.service;

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

import com.test.biz.bean.DeptBean;
import com.test.common.dao.BaseDao;

public class DeptService {

    private int idx = 1;

    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;

    // 获取dept list
    public ArrayList<DeptBean> deptList(DeptBean db){

        ArrayList<DeptBean> deptList = new ArrayList<DeptBean>();

        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);

        sqlBf.append("SELECT   DEPTNO                \n");
        sqlBf.append("       , DNAME                 \n");
        sqlBf.append("       , LOC                   \n");
        sqlBf.append("FROM     DEPT                  \n");
        sqlBf.append("WHERE    DNAME LIKE UPPER(?) || ‘%‘   \n");
        sqlBf.append("AND      LOC LIKE UPPER(?) || ‘%‘     \n");
        sqlBf.append("ORDER BY DEPTNO                \n");

        try {
            pstmt = conn.prepareStatement(sqlBf.toString());
            idx = 1;
            pstmt.setString(idx++, db.getDname());
            pstmt.setString(idx++, db.getLoc());

            rs = pstmt.executeQuery();
            while (rs.next()) {
                DeptBean dept = new DeptBean();

                dept.setDeptno(rs.getInt("DEPTNO"));
                dept.setDname(rs.getString("DNAME"));
                dept.setLoc(rs.getString("LOC"));

                deptList.add(dept);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            baseDao.dbDisconnection(rs, pstmt, conn);
        }

        return deptList;
    }

    // 利用deptno查询单条部门信息
    public DeptBean deptById(int deptno) {
        DeptBean dept = new DeptBean();

        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);

        sqlBf.append("SELECT   DEPTNO                \n");
        sqlBf.append("       , DNAME                 \n");
        sqlBf.append("       , LOC                   \n");
        sqlBf.append("FROM     DEPT                  \n");
        sqlBf.append("WHERE    DEPTNO = ?            \n");

        try {
            pstmt = conn.prepareStatement(sqlBf.toString());
            idx = 1;
            pstmt.setInt(idx++, deptno);

            rs = pstmt.executeQuery();
            if (rs.next()) {
                dept.setDeptno(rs.getInt("DEPTNO"));
                dept.setDname(rs.getString("DNAME"));
                dept.setLoc(rs.getString("LOC"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            baseDao.dbDisconnection(rs, pstmt, conn);
        }

        return dept;
    }

    // 更新dept信息
    public int deptSave(DeptBean deptBean) {
        int updateResulInt = 0;

        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);

        sqlBf.append("UPDATE DEPT SET DNAME = ?          \n");
        sqlBf.append("              , LOC = ?            \n");
        sqlBf.append("WHERE DEPTNO = ?                   \n");

        try {
            pstmt = conn.prepareStatement(sqlBf.toString());
            idx = 1;
            pstmt.setString(idx++, deptBean.getDname());
            pstmt.setString(idx++, deptBean.getLoc());
            pstmt.setInt(idx++, deptBean.getDeptno());

            updateResulInt = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            baseDao.dbDisconnection(null, pstmt, conn);
        }

        return updateResulInt;
    }

    // 删除部门一条记录
    public int deptDelete(int deptno) {
        int deleteResulInt = 0;

        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);

        sqlBf.append("DELETE FROM DEPT           \n");
        sqlBf.append("WHERE DEPTNO = ?           \n");

        try {
            pstmt = conn.prepareStatement(sqlBf.toString());
            idx = 1;
            pstmt.setInt(idx++, deptno);

            deleteResulInt = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            baseDao.dbDisconnection(null, pstmt, conn);
        }

        return deleteResulInt;
    }

    // 获取下一个deptno
    public int getNextDetpno() {
        int nextDeptno = 0;

        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);

        sqlBf.append("SELECT MAX(DEPTNO) + 10   AS DEPTNO  \n");
        sqlBf.append("FROM   DEPT                          \n");

        try {
            pstmt = conn.prepareStatement(sqlBf.toString());
            idx = 1;

            rs = pstmt.executeQuery();
            if (rs.next()) {
                nextDeptno = rs.getInt("DEPTNO");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            baseDao.dbDisconnection(rs, pstmt, conn);
        }

        return nextDeptno;
    }

    // 增加一条dept数据
    public int deptAdd(DeptBean dept) {
        int insertInt = 0;

        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);

        sqlBf.append("INSERT INTO DEPT(DEPTNO, DNAME, LOC)        \n");
        sqlBf.append("          VALUES(?                          \n");
        sqlBf.append("               , ?                          \n");
        sqlBf.append("               , ?)                         \n");

        try {
            pstmt = conn.prepareStatement(sqlBf.toString());
            idx = 1;
            pstmt.setInt(idx++, dept.getDeptno());
            pstmt.setString(idx++, dept.getDname());
            pstmt.setString(idx++, dept.getLoc());

            insertInt = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            baseDao.dbDisconnection(rs, pstmt, conn);
        }

        return insertInt;
    }
}
时间: 2024-10-28 22:02:59

Java MVC 增删改查 实例的相关文章

java:JSP(JSPWeb.xml的配置,动态和静态导入JSP文件,重定项和请求转发,使用JSP实现数据库的增删改查实例)

1.JSP的配置: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":&qu

Mybatis增删改查实例

Mybatis增删改查实例 编写一个简单的mybatis进行插入数据的实例 1 数据库建表  其中建表dob=Date of Birth 的意思 create table students (stud_id number primary key, name varchar2(20), email varchar2(20), dob date ); Oracle数据库中出现表已创建,则表示创建成功,如果出现名称已被使用,则可在建表之前进行删除操作:drop table students;或者进行级

yii2.0增删改查实例讲解

yii2.0增删改查实例讲解一.创建数据库文件. 创建表 CREATE TABLE `resource` ( `id` int(10) NOT NULL AUTO_INCREMENT, `texture` varchar(50) NOT NULL COMMENT '材质', `mark` varchar(50) NOT NULL COMMENT '牌号', `manufacturers` varchar(100) NOT NULL COMMENT '厂家', `price` int(11) NO

BootStrap DataTables Spring MVC简单增删改查实例

1 <!DOCTYPE html> 2 <%@ page contentType="text/html;charset=gbk" language="java" %> 3 <%@page isELIgnored="false" %> 4 <meta name="viewport" content="width=device-width, initial-scale=1&quo

ASP.NET MVC增删改查

ASP.NET MVC中的增删改查 基本都要使用C控制器中的两个action来完成操作,一个用于从主界面跳转到新页面.同时将所需操作的数据传到新界面,另一个则对应新界面的按钮,用于完成操作.将数据传回主界面以及跳转回主界面.根据不同情况使用不同的传值方法. 在M模型层中定义所需的LinQ操作,在C按需引用. 添加:View中提交元素,表单元素使用form表单提交,按钮的使用submit,在控制器C中获取元素,在模型层M的写法,在C中调用. 删除,可使用MVC中的路由功能 url="{contro

【php增删改查实例】第四节 -自己 DIY 一个数据库管理工具

本节介绍如何自己DIY一个数据库管理工具,可以在页面输入sql 进行简单的增删改查操作. 首先,找到xampp的安装目录,打开htdocs: 新建一个php文件,名称为 mysqladmin.php 1.编写php服务器代码 1.1 写上php标签 首先,还是在这个页面,要写php代码,就需要有一个php标签: 我们的php代码要写在这个标签内. 1.2 数据库连接操作 xampp安装的mysql默认没有密码,不写就行. 1.3 获取form表单传过来的sql语句 1.4 用mysql_quer

关于利用PHP访问MySql数据库的逻辑操作以及增删改查实例操作

PHP访问MySql数据库 <?php //造连接对象$db = new MySQLi("localhost","root","","0710_test"); //写SQL语句$sql = "select * from student";//检测连接数据库是否成功,失败返回"连接失败",并退出程序 if(mysqli_connect_error()){    die("连

MongoDB增删改查实例

MongoDB之Java测试代码(DAO层),mongodbdao MongoInit.java是数据库初始化及连接类 MongoUtils.java是对mongodb的各种操作方法 MongoInit.java package com.wlwcloud.datatest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.UnknownHostExce

Java数据库增删改查

数据库为MySQL数据库,Oracle数据库类似: create database db_test;--创建数据库 create user user_test@localhost identified by '123456';--创建用户 grant all privileges on db_test.* to user_test@localhost;--给用户授予权限 use db_test; create table tb_Test( pk_Test_ID char(10) primary