初学者的java项目笔记-9.添加课程接口

修改courseList.jsp

在CourseServlet中写如下代码

 

在CourseService中写addCourse方法

 在utils/CommonsUtils中添加如下代码

 

 在CourseDao中添加如下两个方法

 在CourseService中捕获异常

 

回到CourseServlet中

 

用Postman测试一下先

补全代码

courseList.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta charset="UTF-8">
    <title>课程列表</title>
    <link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/themes/default/easyui.css"/>' rel="stylesheet" type="text/css" />
    <link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/themes/icon.css"/>' rel="stylesheet" type="text/css" />
    <link href='<c:url context="${pageContext.request.contextPath}" value="/easyui/css/demo.css"/>' rel="stylesheet" type="text/css" />
    <script type="text/javascript" src='<c:url value="/easyui/jquery.min.js" context="${pageContext.request.contextPath}"/>'></script>
    <script type="text/javascript" src='<c:url value="/easyui/jquery.easyui.min.js" context="${pageContext.request.contextPath}"/>'></script>
    <script type="text/javascript" src='<c:url value="/easyui/js/validateExtends.js" context="${pageContext.request.contextPath}"/>'></script>




    <script type="text/javascript">
        $(function() {
            //datagrid初始化
            $('#dataList').datagrid({
                title:'课程列表',
                iconCls:'icon-more',//图标
                border: true,
                collapsible: false,//是否可折叠的
                fit: true,//自动大小
                method: "get",//请求表格数据的时候,请求方法
                url:"/s/course?action=data",
                idField:'cid',//表格每一行的唯一标识符
                singleSelect: true,//是否单选
                pagination: false,//分页控件
                rownumbers: true,//行号
                sortName:'cid',
                sortOrder:'asc',
                remoteSort: false,
                columns: [[
                    {field:'chk',checkbox: true,width:50},
                    {field:'cid',title:'课程编号',width:50, sortable: true},
                    {field:'courseName',title:'课程名称',width:200},
                ]],
                toolbar: "#toolbar"
            });

            //设置工具类按钮
            $("#add").click(function(){
                $("#addDialog").dialog("open");
            });
            //删除
            $("#delete").click(function(){
                var selectRow = $("#dataList").datagrid("getSelected");
                if(selectRow == null){
                    $.messager.alert("消息提醒", "请选择数据进行删除!", "warning");
                } else{
                    var courseid = selectRow.id;
                    $.messager.confirm("消息提醒", "将删除与课程相关的所有数据,确认继续?", function(r){
                        if(r){
                            $.ajax({
                                type: "post",
                                url: "CourseServlet?method=DeleteCourse",
                                data: {courseid: courseid},
                                success: function(msg){
                                    if(msg == "success"){
                                        $.messager.alert("消息提醒","删除成功!","info");
                                        //刷新表格
                                        $("#dataList").datagrid("reload");
                                    } else{
                                        $.messager.alert("消息提醒","删除失败!","warning");
                                        return;
                                    }
                                }
                            });
                        }
                    });
                }
            });

            //设置添加窗口
            $("#addDialog").dialog({
                title: "添加课程",
                width: 450,
                height: 250,
                iconCls: "icon-add",
                modal: true,
                collapsible: false,
                minimizable: false,
                maximizable: false,
                draggable: true,
                closed: true,
                buttons: [
                    {
                        text:'添加',
                        plain: true,
                        iconCls:'icon-book-add',
                        handler:function(){
                            var validate = $("#addForm").form("validate");
                            if(!validate){
                                $.messager.alert("消息提醒","请检查你输入的数据!","warning");
                                return;
                            } else{
                                $.ajax({
                                    type: "post",
                                    url: "CourseServlet?method=AddCourse",
                                    data: $("#addForm").serialize(),
                                    success: function(msg){
                                        if(msg == "success"){
                                            $.messager.alert("消息提醒","添加成功!","info");
                                            //关闭窗口
                                            $("#addDialog").dialog("close");
                                            //清空原表格数据
                                            $("#add_name").textbox('setValue', "");
                                            //刷新
                                            $('#dataList').datagrid("reload");
                                        } else{
                                            $.messager.alert("消息提醒","添加失败!","warning");
                                            return;
                                        }
                                    }
                                });
                            }
                        }
                    },
                    {
                        text:'重置',
                        plain: true,
                        iconCls:'icon-book-reset',
                        handler:function(){
                            $("#add_name").textbox('setValue', "");
                        }
                    },
                ]
            });

        });
    </script>
</head>
<body>
<!-- 数据列表,这个就是课程列表的表格 -->
<table id="dataList" cellspacing="0" cellpadding="0">

</table>
<!-- 工具栏 -->
<div id="toolbar">
    <div style="float: left;"><a id="add" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">添加</a></div>
    <div style="float: left;" class="datagrid-btn-separator"></div>
    <div><a id="delete" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-some-delete',plain:true">删除</a></div>
</div>

<!-- 添加数据窗口 -->
<div id="addDialog" style="padding: 10px">
    <form id="addForm" method="post">
        <table cellpadding="8" >
            <tr>
                <td>课程名称:</td>
                <td><input id="add_name" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="name" data-options="required:true, validType:'repeat_course', missingMessage:'不能为空'" /></td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>

CourseDao

package demo.dao;

import demo.model.Course;
import demo.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class CourseDao {
    QueryRunner queryRunner = new QueryRunner(DBUtils.getDs());

    public List<Course> getAllCourses() throws SQLException {
        return queryRunner.query("select * from course",new BeanListHandler<>(Course.class));
    }

    public Course getCourseByCourseName(String courseName) throws SQLException {
        return queryRunner.query("select * from course where courseName=?",new BeanHandler<>(Course.class),courseName);
    }

    public Integer addCourse(String courseName) throws SQLException {
        return queryRunner.update("insert into course(courseName) values(?)",courseName);
    }
}

CourseServlet

package demo.servlet.course;

import com.fasterxml.jackson.databind.ObjectMapper;
import demo.model.Course;
import demo.model.RespBean;
import demo.service.CourseService;
import demo.utils.CommonsUtils;

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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/course")
public class CourseServlet extends HttpServlet {

    CourseService courseService =new CourseService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action =req.getParameter("action");
        if ("page".equals(action)){
            //说明是来请求页面的
            req.getRequestDispatcher("/WEB-INF/jsp/course/courseList.jsp").forward(req,resp);
        }else if ("data".equals(action)){
            //说明是来请求json数据的
            //前端是一个表格,所以这里返回的是json数组,数组格式是[{xx:xx,xx:xx},{},{}]
            List<Course>list=courseService.grtAllCourses();
            ObjectMapper om=new ObjectMapper();
            String json=om.writeValueAsString(list);
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter out= resp.getWriter();
            out.write(json);
        }
    }

    /**
     * 添加课程
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String courseName = req.getParameter("courseName");
        Integer result =courseService.addCourse(courseName);
        resp.setContentType("application/json;charset=utf-8");
        RespBean respBean =null;
        if (result == CommonsUtils.REPEATABLE_VALUE){
            respBean =RespBean.error("课程名重复,添加失败");
        }else  if (result == CommonsUtils.INSERT_SUCCESS){
            respBean=RespBean.ok("添加成功");

        }else {
            respBean =RespBean.error("添加失败");
        }
        ObjectMapper om=new ObjectMapper();
        String json =om.writeValueAsString(respBean);
        resp.getWriter().write(json);
    }
}

CourseService

package demo.service;

import demo.dao.CourseDao;
import demo.model.Course;
import demo.utils.CommonsUtils;

import java.sql.SQLException;
import java.util.List;

public class CourseService {
    CourseDao courseDao = new CourseDao();

    public List<Course> grtAllCourses() {
        try {
            return courseDao.getAllCourses();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Integer addCourse(String courseName) {
        try {
            //根据课程名查询课程
            Course c = courseDao.getCourseByCourseName(courseName);
            if (c != null) {
                //课程名重复,添加失败
                return CommonsUtils.REPEATABLE_VALUE;
            }
            Integer r = courseDao.addCourse(courseName);
            return r == 1 ? CommonsUtils.INSERT_SUCCESS : CommonsUtils.OTHER_EXCEPTION;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return CommonsUtils.OTHER_EXCEPTION;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值