通过自动回复机器人学Mybatis:MySQL脚本 + db>>dao>>service>>servlet

留着参考

makeData.sql

delimiter //
create procedure make_data()
begin
    declare i int default 1;
    while i < 1000 do
        insert into message values(i, ‘a‘, ‘b‘, ‘c‘);
        set i = i + 1;
    end while;
end;
//

call make_data();
DROP PROCEDURE IF EXISTS make_data;

Message.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Message">

  <resultMap type="com.imooc.bean.Message" id="MessageResult">
      <!-- 主键用id标签,其它的用result标签 -->
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
  </resultMap>

  <!-- Message.xml的目的:配置如下的sql语句让SqlSession读到并执行 -->
  <!-- id是为了方便sqlSession调用,相同namespace下必须唯一 -->
  <select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
    select ID, COMMAND, DESCRIPTION, CONTENT from MESSAGE where 1=1
    <!-- OGNL表达式,它不是Mybatis专有的,类似于EL表达式,#{}是Mybatis专有的 -->
    <!-- 原: <if test="command != null && !"".equals(command.trim())"></if> -->
    <if test="command != null and !&quot;&quot;.equals(command.trim())">
        and COMMAND=#{command}</if>
    <if test="description != null and !&quot;&quot;.equals(description.trim())">
        and DESCRIPTION like ‘%‘ #{description} ‘%‘</if>
  </select>

  <delete id="deleteOne" parameterType="int">
      delete from MESSAGE where ID = #{_parameter}
  </delete>    

  <delete id="deleteBatch" parameterType="java.util.List">
      delete from MESSAGE where ID in (
          <foreach collection="list" item="item" separator=",">
              #{item}
          </foreach>
      )
  </delete>

</mapper>

访问数据库类

package com.imooc.db;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 访问数据库类
 */
public class DBAccess {
    public SqlSession getSqlSession() throws IOException {
        Reader reader = Resources.getResourceAsReader("com/imooc/config/Configuration.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

dao

package com.imooc.dao;

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

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.imooc.bean.Message;
import com.imooc.db.DBAccess;

public class MessageDao {
    /**
     * 根据查询条件获取消息列表
     */
    public List<Message> queryMessageList(String command, String description) {
        List<Message> messageList = new ArrayList<>();

        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            // 通过sqlSession执行SQL语句
            Message message = new Message();
            message.setCommand(command);
            message.setDescription(description);

            messageList = sqlSession.selectList("Message.queryMessageList", message);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 如果中间发生异常sqlSession可能是null
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return messageList;
    }

    /**
     * 单条删除
     */
    public void deletOne(int id) {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            sqlSession.delete("Message.deleteOne", id);
            sqlSession.commit(); // Mybatis不默认提交
            // JDBC默认自动提交,除非setAutoCommit(false)
            // 这个时候姐需要conn.commit()提交事务
            // 可以通过conn.rollback([Savepoint savepoint])回滚
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * 删除多条消息
     */
    public void deleteBatch(List<Integer> ids) {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            sqlSession.delete("Message.deleteBatch", ids);
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    public static void main(String[] args) {
        MessageDao messageDao = new MessageDao();
        messageDao.queryMessageList("", "");
    }
}

service

MaintainService.java

package com.imooc.service;

import java.util.ArrayList;
import java.util.List;

import com.imooc.dao.MessageDao;

/**
 * 维护相关的业务功能
 */
public class MaintainService {
    /**
     * 删除单条信息
     */
    public void deleteOne(String id) {
        // servlet负责接收页面的值、向页面传值
        // service负责接收servlet穿过来的值并对这个值进行处理,做业务的操作,算法等等
        // 如果有需要调用相应的Dao
        if (id != null && !"".equals(id.trim())) { // 这个逻辑判断实际还是不够的!
            MessageDao messageDao = new MessageDao();
            messageDao.deletOne(Integer.valueOf(id));
        }
    }

    /**
     * 删除多条消息
     */
    public void deleteBatch(String[] ids) {
        MessageDao messageDao = new MessageDao();
        List<Integer> idList = new ArrayList<>();
        for (String id : ids) {
            idList.add(Integer.valueOf(id));
        }
        messageDao.deleteBatch(idList);
    }
}

QueryService.java

package com.imooc.service;

import java.util.List;

import com.imooc.bean.Message;
import com.imooc.dao.MessageDao;
import com.imooc.util.Iconst;

/**
 * 列表相关的业务功能
 */
public class QueryService {
    /**
     * 获取消息列表
     */
    public List<Message> queryMessageList(String command, String description) {
        MessageDao dao = new MessageDao();
        return dao.queryMessageList(command, description);
    }

    /**
     * 通过指令查询
     */
    public String queryByCommand(String command) {
        MessageDao dao = new MessageDao();
        List<Message> messageList;
        // 用户输入帮助
        if (Iconst.HELP_COMMAND.equals(command)) {
            messageList = dao.queryMessageList(null, null);
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < messageList.size(); ++i) {
                if (i != 0) {
                    result.append("<br />");
                }
                result.append("回复[" + messageList.get(i).getContent() + "]可以查看" + messageList.get(i).getDescription());
            }
            return result.toString();
        }
        // 用户输入具体指令
        messageList = dao.queryMessageList(command, null);
        if (messageList.size() > 0) {
            return messageList.get(0).getContent();
        }
        // 用户输入位置指令
        return Iconst.NO_MATCHING_CONTENT;
    }
}

servlet

后台方面:

package com.imooc.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.imooc.service.QueryService;

/**
 * 列表页面初始化控制
 */
@SuppressWarnings("serial")
public class ListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        // 接受页面的值
        String command = req.getParameter("command");
        String description = req.getParameter("description");
        // 向页面传值
        req.setAttribute("command", command);
        req.setAttribute("description", description);
        // 查询消息列表并传给页面
        QueryService listService = new QueryService();
        req.setAttribute("messageList", listService.queryMessageList(command, description));
        // 页面跳转
        req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
package com.imooc.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.imooc.service.MaintainService;

/**
 * 单条删除控制层
 */
@SuppressWarnings("serial")
public class DeleteOneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        // 接受页面的值
        String id = req.getParameter("id");
        MaintainService maintainService = new MaintainService();
        maintainService.deleteOne(id);
        // 页面跳转
        req.getRequestDispatcher("/List.action").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
package com.imooc.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.imooc.service.MaintainService;

@SuppressWarnings("serial")
public class DeleteBatchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        // 接受页面的值
        String[] ids = req.getParameterValues("id");
        MaintainService maintainService = new MaintainService();
        maintainService.deleteBatch(ids);
        // 页面跳转
        req.getRequestDispatcher("/List.action").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

前台方面:

package com.imooc.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * 对话页的初始化控制
 *
 */
@SuppressWarnings("serial")
public class InitTalkServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        // 页面跳转
        req.getRequestDispatcher("/WEB-INF/jsp/front/talk.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
package com.imooc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.service.QueryService;

/**
 * 自动回复功能控制层,
 * 针对AJAX的
 */
@SuppressWarnings("serial")
public class AutoReplyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        QueryService queryService = new QueryService();
        out.write(queryService.queryByCommand(req.getParameter("content")));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

时间: 2024-12-23 15:11:46

通过自动回复机器人学Mybatis:MySQL脚本 + db>>dao>>service>>servlet的相关文章

通过自动回复机器人学Mybatis(搭建核心架构)

imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154 MessageDao.java package com.imooc.dao; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.imooc.bean.Message; imp

通过自动回复机器人学Mybatis(代码重构)

imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154 ListServlet.java package com.imooc.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.servlet.ServletExceptio

通过自动回复机器人学Mybatis(OGNL参考)

imooc视频学习笔记 ----> URL:http://www.imooc.com/learn/154

Spring+Mybatis+MySql+Maven 简单的事务管理案例

利用Maven来管理项目中的JAR包,同时使用Spring在业务处理层进行事务管理.数据库使用MySq,数据处理层使用Spring和Mybatis结合. 本案例代码主要结构如图: 1.数据库脚本 -- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` (   `id` 

springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解

@[email protected] 写在最前 之前分享过下面这几篇: mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法) mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下) springmvc学习笔记(一) -- 从零搭建,基础入门 这一篇,在这些练习的基础上,将它们整合在一起! 搭建步骤如下 一.新建maven项目,配置环境,测试是否配置成

日常开发系列——Maven+Spring+Spring MVC+MyBatis+MySQL整合SSM框架

进入公司开发已经3个多月了,项目用的是Maven+Spring+Spring MVC+MyBatis+MySQL,趁这个周末有空,仔细研读一下公司项目的基本框架,学习一下这个环境是怎么搭建起来的,经过自己的研究终于是成功地试验出来.自己亲手做的才算是自己学到的,决定将其记录下来,以便日后查询,源码同时也欢迎大家拍砖. 一.数据库的准备 这次整合试验想着做个简单的,就决定做一个普通的用户登陆,就一张表吧 我新建的数据库名字是test,然后新建了一张表 DROP TABLE IF EXISTS `u

Spring+SpringMVC+Mybatis+Mysql整合实例【转】

本文要实现Spring+SpringMVC+Mybatis+Mysql的一个整合,实现了SpringMVC控制访问的页面,将得到的页面参数传递给Spring中的Mybatis的bean类,然后查找Mysql数据的功能,并通过JSP显示出来.建议可以先看笔者另一文章Mybatis与Spring整合创建Web项目 .笔者觉得整合过程中问题比较多的还是Spring+Mybatis的整合,SpringMVC的整合还是比较简单. Spring        Spring 是一个开源框架, Spring 是

eclipse下SpringMVC+Maven+Mybatis+MySQL项目搭建

这篇文章主要讲解在eclipse环境下SpringMVC+Maven+Mybatis+MySQL的项目搭建过程. 创建Maven工程. 右击-->New->Other 点击->Manven Porject 点击->勾选快速框架 输入项目名,包(Packaging,如果只是普通的项目,选jar就好了,如果是web项目就选war,这里是web项目,所以选择war) 右击项目->Properties->Java Build Path->选择Libraries->点

Spring注解处理Ajax请求-JSON格式[系统架构:Spring+SpringMVC+MyBatis+MySql]

这是自己曾写的一个系统(养老保险管理)中的一个小片段,今天突然想到把请求数据改成json,该如何处理.(Spring+SpringMVC+MyBatis+MySql)如下 1.前端jsp页面 <div class="tab_tip"> 请输入[身份证号或姓名] <input type="text" class="tab_getText" id="tab1_getText"> <input type