继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Mybatis-自动回复机器人案例

慕粉3971981
关注TA
已关注
手记 1
粉丝 0
获赞 1

1、项目概述:模仿微信公众号,用户输入指令,后台自动回复内容。要求后台对一条指令设置多条对应的内容,后台接收到用户的指令后,随机返回一条该指令对应的内容给用户。
2、项目实施
(1)数据库两张表
command指令表
图片描述
command_content指令内容表
图片描述
command_content表中的外键COMMAND_ID指向command表的主键ID,command_content表中ID为1~5的记录的COMMAND_ID都为1,都对应command表中ID为1的记录,所以ID为1的指令NAME可以对应5个内容CONTENT。
(2)创建JavaBean
父表command

package imis.black.bean;

import java.util.List;

/**
 * 对应指令表的实体类
 * 一对多关系中的一,称为主表,指令表
 * 主表应包含子表实体类的一条列表,对应的xml文件中也是(父表的xml文件要包含子表的集合)
 * @author PC
 *
 */
public class Command {
    //指令id
    private String id;
    //指令名称
    private String name;
    //对指令的描述
    private String description;
    //一条指令对应的自动回复内容列表
    private List<Command_Content> contentList;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public List<Command_Content> getContentList() {
        return contentList;
    }
    public void setContentList(List<Command_Content> contentList) {
        this.contentList = contentList;
    }

}

子表command_content

package imis.black.bean;
/**
 * 一对多关系中的多,称为子表,指令内容表
 * 对应内容表的实体类
 * @author PC
 *
 */
public class Command_Content {
    //该条内容的id
    private String id;
    //内容
    private String content;
    //内容对应的指令的id
    private String command_id;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getCommand_id() {
        return command_id;
    }
    public void setCommand_id(String command_id) {
        this.command_id = command_id;
    }

}

(3)在项目中导入Mybatis的jar包、mysql的jar包
图片描述
(4)连接数据库的配置文件Configuration.xml

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

       Copyright 2009-2016 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <!-- 
  <settings>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="useColumnLabel" value="true"/>
  </settings>

  <typeAliases>
    <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases>
     -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/response"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>

  <mappers>
    <mapper resource="imis/black/config/sql/Command.xml"/>
    <mapper resource="imis/black/config/sql/Command_Content.xml"/>
  </mappers>

</configuration>

(5)取得SqlSession对象

package imis.black.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;

/**
 * 取得SqlSession对象
 * @author PC
 *
 */
public class DBAccess {
    public SqlSession getSqlSession() throws IOException{

        Reader reader=Resources.getResourceAsReader("imis/black/config/Configuration.xml");

        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);

        SqlSession sqlSession=sqlSessionFactory.openSession();
        return sqlSession;
    }
}

(6)JavaBean和数据库表对应的xml文件
command表的

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

       Copyright 2009-2016 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

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

<mapper namespace="Command">

  <resultMap type="imis.black.bean.Command" id="Command">
    <id column="C_ID" jdbcType="INTEGER" property="id"/>
    <result column="NAME" jdbcType="VARCHAR" property="name"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <collection property="contentList" resultMap="Content.Command_Content"/>
  </resultMap>

  <!-- 要关联两张表,分别起别名a、b,方便规避一些问题 -->
  <select id="queryCommandList" parameterType="imis.black.bean.Command" resultMap="Command">
    SELECT a.ID C_ID, a.NAME, a.DESCRIPTION, b.ID, b.CONTENT, b.COMMAND_ID
    FROM command a left join command_content b
    ON a.ID=b.COMMAND_ID
    <where>
        <if test="name!=null and !"".equals(name.trim())">
            AND a.NAME=#{name}
        </if>
        <if test="description!=null and !"".equals(description.trim())">
            AND a.DESCRIPTION LIKE '%' #{description} '%'
        </if>
    </where>
  </select>

</mapper>

<br>
command_content表的

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

       Copyright 2009-2016 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

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

<mapper namespace="Content">

  <resultMap type="imis.black.bean.Command_Content" id="Command_Content">
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
    <result column="COMMAND_ID" jdbcType="VARCHAR" property="command_id"/>
  </resultMap>

</mapper>

(7)工具类

package imis.black.util;

/**
 * 共通的常量定义(当指定的指令修改时,比如“帮助”改为“Help”,就在这里修改就好,不用去业务代码修改)
 */
public interface Iconst {
    /**
     * 当指令没有匹配的自动回复内容时,用此内容代替。
     */
    public static final String NO_MATCHING_CONTENT = "客官,你没按套路出牌……我听不懂你在说什么哎!";
    public static final String HELP_COMMAND = "帮助";
}

(8)dao层

package imis.black.dao;

import imis.black.bean.Command;
import imis.black.db.DBAccess;

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

import org.apache.ibatis.session.SqlSession;

/**
 * 与指令表对应的数据库操作类
 * @author PC
 *
 */
public class CommandDAO {
    public List<Command> queryCommandList(String name,String description){
        List<Command> commandList=new ArrayList<Command>();
        DBAccess db=new DBAccess();
        SqlSession sqlSession=null;
        Command command=new Command();
        command.setName(name);
        command.setDescription(description);
        try {
            sqlSession=db.getSqlSession();
            commandList=sqlSession.selectList("Command.queryCommandList",command);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return commandList;
    }
}

(9)service层

package imis.black.service;

import imis.black.bean.Command;
import imis.black.bean.Command_Content;
import imis.black.bean.Message;
import imis.black.dao.CommandDAO;
import imis.black.dao.MessageDAO;
import imis.black.util.Iconst;

import java.util.List;
import java.util.Random;

/**
 * 查询相关的业务功能
 */
public class QueryService {

    /**
     * 根据指令名称查询,随机返回一条指令及其内容
     * @param command 指令
     * @return 自动回复的内容
     */
    public String queryByCommand(String command) {
        CommandDAO commandDAO = new CommandDAO();
        List<Command> commandList;
        if(Iconst.HELP_COMMAND.equals(command)) {
            //两个条件都为null,即为全部查询
            commandList = commandDAO.queryCommandList(null, null);
            //拼接自动回复内容
            StringBuilder result = new StringBuilder();
            for(int i = 0; i < commandList.size(); i++) {
                if(i != 0) {
                    result.append("<br/>");
                }
                result.append("回复[" + commandList.get(i).getName() + "]可以查看" + commandList.get(i).getDescription());
            }
            return result.toString();
        }
        commandList = commandDAO.queryCommandList(command, null);
        if(commandList.size() > 0) {
            //得到该指令下的多条内容
            List<Command_Content> contentList=commandList.get(0).getContentList();
            //随机返回一个大于等于0小于size的数字
            int i=new Random().nextInt(contentList.size());
            //随机返回一条内容
            return contentList.get(i).getContent();
        }
        return Iconst.NO_MATCHING_CONTENT;
    }
}

(10)Servlet控制层
AutoReplyServlet,自动回复,处理talk.jsp页面提交的请求

package imis.black.controller;

import imis.black.service.QueryService;

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;

public class AutoReplyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        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 {
        doGet(req, resp);
    }

}

InitTalkServlet,初始化talk.jsp页面

package imis.black.controller;

import java.io.IOException;

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

public class InitTalkServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/front/talk.jsp").forward(req, resp);
    }

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

}

(11)过滤器

package imis.black.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SetCharacterEncodingFilter implements Filter {

    private FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest  request;
        HttpServletResponse response;
        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException("non-HTTP request or response");
        }

        String encoding = filterConfig.getInitParameter("encoding");
        if(encoding==null){
            encoding = "UTF-8";
        }

        //POST:
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);
        chain.doFilter(request, response);
    }

    public void destroy() {

    }

}

(12)web.xml配置Servlet和过滤器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>AutoResponse</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <filter>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <filter-class>imis.black.filter.SetCharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

    <servlet>
    <servlet-name>InitTalkServlet</servlet-name>
    <servlet-class>imis.black.controller.InitTalkServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>InitTalkServlet</servlet-name>
    <url-pattern>/initTalk.action</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>AutoReplyServlet</servlet-name>
    <servlet-class>imis.black.controller.AutoReplyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AutoReplyServlet</servlet-name>
    <url-pattern>/autoReply.action</url-pattern>
  </servlet-mapping>

</web-app>

(13)导入log4j的jar包,在对页面进行操作时控制台可显示sql语句
图片描述
(14)其他的js文件、css文件就不写了,整个流程:用户通过访问initTalk.action,进入talk.jsp页面,页面提交请求给autoReply.action(可在js文件中指定),AutoReplyServlet调用service层的queryByCommand方法,service层调用dao层的queryCommandList方法,dao层取得SqlSession对象后执行command表对应的xml文件中id为queryCommandList的sql语句,将结果集一步步返回给Servlet,最后在talk.jsp页面输出

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP