当年的java考试:Java景区预约登记管理系统(maven整合servlet)

举报
红目香薰 发表于 2022/05/27 15:31:20 2022/05/27
【摘要】 ​ maven整合servlet的过程以及使用mybatis框架进行CRUD操作需求效果:​编辑1、搭建maven整合servlet(10分)2、mybatis各种配置(创建数据库)(10分)3、完成各层编码与联系(30分)4、在DAO层进行编码测试(0分)5、在servlet层创建查询GetInfo、添加AddInfo、修改SelectById,UpdateById,删除DeleteByI...

 maven整合servlet的过程以及使用mybatis框架进行CRUD操作

需求效果:

编辑

1、搭建maven整合servlet(10分)
2、mybatis各种配置(创建数据库)(10分)
3、完成各层编码与联系(30分)
4、在DAO层进行编码测试(0分)
5、在servlet层创建查询GetInfo、添加AddInfo、修改SelectById,UpdateById,删除DeleteById(30分)
6、完成视图层编码,GetInfo.jsp,AddInfo.jsp(10分)
7、(编码规范与异常处理)(10分)
8、提交项目(提交正确计分,否则0分) 


环境:

开发工具:【IntelliJ IDEA 2020.1.3 x64】

mysql版本:【5.6.x】

mysql工具:【Navicat Premium 15】

完成步骤以及编码:

目录

maven整合servlet的过程以及使用mybatis框架进行CRUD操作

需求效果:

环境:

完成步骤以及编码:

​编辑

添加各层的包

添加【tomcat】

添加Tomcat包

创建【com.item.servlet】下【GetInfoServlet.java】测试servlet接口

刷新【maven】才会出现【Create New Servlet】

​编辑

添加mybatis对应maven包

在src/main/的resources内创建【mybatis-config.xml】文件

根据【com/item/mapper/TbTourinfoMapper.xml】在【resources】下创建包与配置文件

编码内容如下,包含【查询】【筛选查询】【添加】【删除】【修改】

在【resources】下创建【log4j.properties】文件

创建【com.item.model】内【TbTourinfo】文件

在【com.item.mapper】下创建【TbTourinfoMapper】

在【com.item.common】下创建JDBC用于获取数据库连接池链接

在【com.item.dao】下创建【TbTourinfoDAO.java】文件

在【com.item.servlet】下以此创建

【GetInfoServlet】

【SelectByNameSexTypeServlet】

【AddInfoServlet】

【DeleteByIdServlet】

【UpdateByIdServlet】

在【webapp】下创建

【GetInfo.jsp】

【AddInfo.jsp】



编辑

编辑

编辑

编辑

添加各层的包

编辑

编辑

编辑

添加【tomcat】

编辑

编辑

编辑

编辑

编辑

Tomcat添加项目成功

编辑

添加Tomcat包

编辑

编辑

编辑

编辑

编辑

创建【com.item.servlet】下【GetInfoServlet.java】测试servlet接口

刷新【maven】才会出现【Create New Servlet】

编辑

编辑

编辑
package com.item.servlet;

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;

@WebServlet("/GetInfo")
public class GetInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("访问测试");
    }

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

访问成功 

编辑

添加mybatis对应maven包

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.1</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.7.10</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.6</version>
</dependency>

编辑

编辑

在src/main/的resources内创建【mybatis-config.xml】文件

编辑

配置头部:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

添加图下配置编码:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <typeAliases>
        <package name="com.item.model"/>
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mytest?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="12345678"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/item/mapper/TbTourinfoMapper.xml"></mapper>
    </mappers>
</configuration>

编辑

根据【com/item/mapper/TbTourinfoMapper.xml】在【resources】下创建包与配置文件

编辑

编辑

编码内容如下,包含【查询】【筛选查询】【添加】【删除】【修改】

<?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="com.item.mapper.TbTourinfoMapper">
    <!-- 查询所有 -->
    <select id="GetInfo" resultType="TbTourinfo">
        select * from tb_tourinfo;
    </select>
    <!-- 各种查询-->
    <select id="SelectByNameSexType" resultType="TbTourinfo">
        select * from tb_tourinfo
        <if test="name!=null or sex!=null or type!=null">
            where 1=1
        </if>
        <if test="name!=null">
            and name like "%${name}%"
        </if>
        <if test="sex!=null">
            and sex="${sex}"
        </if>
        <if test="type!=null">
            and type="${type}"
        </if>
    </select>
    <insert id="AddInfo">
        insert into tb_tourinfo values
        (
        0,
        "${name}",
        "${sex}",
        "${id_no}",
        #{age},
        #{type},
        NOW(),
        #{visit_state},
        now()
        );
    </insert>
    <!-- 删除语句 -->
    <delete id="DeleteById" parameterType="java.lang.Integer">
        delete from tb_tourinfo where id=#{id}
    </delete>
    <!-- 修改状态在语句 -->
    <update id="UpdateById">
        update tb_tourinfo set visit_state=#{visit_state} where id=#{id}
    </update>
</mapper>

在【resources】下创建【log4j.properties】文件

#全局配置
log4j.rootLogger=debug,stdout,ERROR
#MyBatis日志配直
log4j.logger.com.item.mapper=TRACE
#控制台输出配置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

编辑

创建【com.item.model】内【TbTourinfo】文件

需要添加数据表对应的【属性】,并添加【Getter】与【Setter】以及【toString】方法。

package com.item.model;

import java.util.Date;

public class TbTourinfo {
    private int id;
    private String name;
    private String sex;
    private String id_no;
    private int age;
    private String type;
    private Date visit_date;
    private int visit_state;
    private Date register_time;

    @Override
    public String toString() {
        return "TbTourinfo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", id_no='" + id_no + '\'' +
                ", age=" + age +
                ", type='" + type + '\'' +
                ", visit_date=" + visit_date +
                ", visit_state=" + visit_state +
                ", register_time=" + register_time +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getId_no() {
        return id_no;
    }

    public void setId_no(String id_no) {
        this.id_no = id_no;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Date getVisit_date() {
        return visit_date;
    }

    public void setVisit_date(Date visit_date) {
        this.visit_date = visit_date;
    }

    public int getVisit_state() {
        return visit_state;
    }

    public void setVisit_state(int visit_state) {
        this.visit_state = visit_state;
    }

    public Date getRegister_time() {
        return register_time;
    }

    public void setRegister_time(Date register_time) {
        this.register_time = register_time;
    }
}

在【com.item.mapper】下创建【TbTourinfoMapper】

package com.item.mapper;

import com.item.model.TbTourinfo;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface TbTourinfoMapper {
    List<TbTourinfo> GetInfo();

    /**
     * 根据参数进行查询
     * @param name (姓名)
     * @param sex (性别)
     * @param type (会员类型)
     * @return
     */
    List<TbTourinfo> SelectByNameSexType(
            @Param("name") String name,
            @Param("sex") String sex,
            @Param("type") String type
    );

    int AddInfo(
            @Param("name") String name,
            @Param("sex") String sex,
            @Param("id_no") String id_no,
            @Param("age") int age,
            @Param("type") int type,
            @Param("visit_state") int visit_state
    );
    int DeleteById(@Param("id") int id);
    int UpdateById(@Param("visit_state") int visit_state,
                   @Param("id") int id);
}

在【com.item.common】下创建JDBC用于获取数据库连接池链接

package com.item.common;

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

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

public class JDBC {
    public static SqlSessionFactory GetConn(){
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
            return factory;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(GetConn());
    }
}

在【com.item.dao】下创建【TbTourinfoDAO.java】文件

package com.item.dao;

import com.item.common.JDBC;
import com.item.mapper.TbTourinfoMapper;
import com.item.model.TbTourinfo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class TbTourinfoDAO {
    /**
     * 查询所有
     * @return
     */
    public static List<TbTourinfo> GetInfo(){
        SqlSessionFactory factory = JDBC.GetConn();
        SqlSession session = factory.openSession();
        TbTourinfoMapper db = session.getMapper(TbTourinfoMapper.class);
        List<TbTourinfo> list = db.GetInfo();
        session.close();
        return list;
    }

    /**
     * 综合信息查询
     * @param name
     * @param sex
     * @param type
     * @return
     */
    public static List<TbTourinfo> SelectByNameSexType(String name,String sex,String type){
        SqlSessionFactory factory = JDBC.GetConn();
        SqlSession session = factory.openSession();
        TbTourinfoMapper db = session.getMapper(TbTourinfoMapper.class);
        List<TbTourinfo> list = db.SelectByNameSexType(name,sex,type);
        session.close();
        return list;
    }

    /**
     * 添加
     * @param name
     * @param sex
     * @param id_no
     * @param age
     * @param type
     * @param visit_state
     * @return
     */
    public static boolean AddInfo(String name,String sex,String id_no,int age,int type,int visit_state){
        SqlSessionFactory factory = JDBC.GetConn();
        SqlSession session = factory.openSession();
        TbTourinfoMapper db = session.getMapper(TbTourinfoMapper.class);
        int rows = db.AddInfo(name, sex, id_no, age, type, visit_state);
        session.commit();
        session.close();
        return rows>0;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public static boolean DeleteById(int id){
        SqlSessionFactory factory = JDBC.GetConn();
        SqlSession session = factory.openSession();
        TbTourinfoMapper db = session.getMapper(TbTourinfoMapper.class);
        int rows = db.DeleteById(id);
        session.commit();
        session.close();
        return rows>0;
    }

    /**
     * 修改
     * @param visit_state
     * @param id
     * @return
     */
    public static boolean UpdateById(int visit_state,int id){
        SqlSessionFactory factory = JDBC.GetConn();
        SqlSession session = factory.openSession();
        TbTourinfoMapper db = session.getMapper(TbTourinfoMapper.class);
        int rows = db.UpdateById(visit_state,id);
        session.commit();
        session.close();
        return rows>0;
    }

    public static void main(String[] args) {
        int oldState=1;
        System.out.println(UpdateById(oldState==0?1:0,7));
    }
}

在【com.item.servlet】下以此创建

【GetInfoServlet】

package com.item.servlet;

import com.item.dao.TbTourinfoDAO;
import com.item.model.TbTourinfo;
import sun.misc.CharacterEncoder;

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.util.List;

/**
 * 本类为GetInfo查询所有的类
 */
@WebServlet("/GetInfo")
public class GetInfoServlet extends HttpServlet {
    /**
     * 这是DOPOST访问接口
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<TbTourinfo> list = TbTourinfoDAO.GetInfo();
        request.setAttribute("lists",list);
        request.getRequestDispatcher("GetInfo.jsp").forward(request,response);
    }

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

【SelectByNameSexTypeServlet】

package com.item.servlet;

import com.item.dao.TbTourinfoDAO;
import com.item.model.TbTourinfo;

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.util.List;

@WebServlet("/SelectByNameSexType")
public class SelectByNameSexTypeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String type = request.getParameter("type");
        List<TbTourinfo> list = TbTourinfoDAO.SelectByNameSexType(name==""?null:name, sex==""?null:sex, type==""?null:type);
        request.setAttribute("lists",list);
        request.getRequestDispatcher("GetInfo.jsp").forward(request,response);
    }

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

【AddInfoServlet】

package com.item.servlet;

import com.item.dao.TbTourinfoDAO;

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;

@WebServlet("/AddInfo")
public class AddInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String id_no = request.getParameter("id_no");
        String age = request.getParameter("age");
        String type = request.getParameter("type");
        TbTourinfoDAO.AddInfo(name,sex,id_no,Integer.parseInt(age),Integer.parseInt(type),0);
        response.sendRedirect("GetInfo");
    }

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

【DeleteByIdServlet】

package com.item.servlet;

import com.item.dao.TbTourinfoDAO;

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;

@WebServlet("/DeleteById")
public class DeleteByIdServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        TbTourinfoDAO.DeleteById(Integer.parseInt(id));
        response.sendRedirect("GetInfo");
    }

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

【UpdateByIdServlet】

package com.item.servlet;

import com.item.dao.TbTourinfoDAO;

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;

@WebServlet("/UpdateById")
public class UpdateByIdServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String visit_state = request.getParameter("visit_state");
        String id = request.getParameter("id");
        TbTourinfoDAO.UpdateById(Integer.parseInt(visit_state.equals("0")?"1":"0"),Integer.parseInt(id));
        response.sendRedirect("GetInfo");
    }

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

在【webapp】下创建

【GetInfo.jsp】

<%@ page import="java.util.List" %>
<%@ page import="com.item.model.TbTourinfo" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/5/18 0018
  Time: 22:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<h1 align="center">景区预约登记管理系统</h1>
<hr/>
<% List<TbTourinfo> list = (List<TbTourinfo>) request.getAttribute("lists");%>

<form action="/SelectByNameSexType">
    游客姓名:<input type="text" name="name" placeholder="请输入搜索姓名"/>
    游客性别:<input type="text" name="sex" placeholder="请输入游客性别"/>
    游客类别:<select name="type">
    <option value="" selected>所有</option>
    <option value="0">非会员</option>
    <option value="1">普通会员</option>
    <option value="2">VIP会员</option>
    <option value="3">钻石会员</option>
    <option value="4">年卡会员</option>
</select>
    <input type="submit" value="查询" class="btn btn-primary"/>
    <a href="/AddInfo.jsp" class="btn btn-primary">添加</a>
</form>
<table class="table table-bordered table-hover">
    <tr class="info">
        <th>编号</th>
        <th>名称</th>
        <th>性别</th>
        <th>身份证</th>
        <th>年龄</th>
        <th>类型</th>
        <th>创建时间</th>
        <th>是否使用</th>
        <th>登录时间</th>
        <th>操作</th>
    </tr>
    <%
        for (TbTourinfo t : list) {
    %>
    <tr>
        <td><%=t.getId()%>
        </td>
        <td><%=t.getName()%>
        </td>
        <td><%=t.getSex()%>
        </td>
        <td><%=t.getId_no()%>
        </td>
        <td><%=t.getAge()%>
        </td>
        <td><%=t.getType()%>
        </td>
        <td><%=t.getVisit_date()%>
        </td>
        <td><%=t.getVisit_state()==0?"未使用":"已使用"%>
        </td>
        <td><%=t.getRegister_time()%>
        </td>
        <td>
            <a href="/UpdateById?visit_state=<%=t.getVisit_state()%>&id=<%=t.getId()%>" class="btn btn-primary">修改</a>
            <a href="/DeleteById?id=<%=t.getId()%>" onclick="return confirm('是否删除此行?')" class="btn btn-primary">删除</a>
        </td>
    </tr>
    <%
        }
    %>
</table>
</body>
</html>

【AddInfo.jsp】

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/5/18 0018
  Time: 22:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <form action="/AddInfo" method="post" style="width:50%;position: relative;left: 30%">
        <p>
            <input type="text" name="name" class="form-control" placeholder="请输入姓名"/>
        </p>
        <p>
            <input type="text" name="sex" class="form-control" placeholder="请输入性别"/>
        </p>
        <p>
            <input type="text" name="id_no" class="form-control" placeholder="请输入身份证"/>
        </p>
        <p>
            <input type="text" name="age" class="form-control" placeholder="请输入年龄"/>
        </p>
        <p>
            <input type="text" name="type" class="form-control" placeholder="请输入类型"/>
        </p>
        <p>
            <input type="submit" value="提交" class="btn btn-success btn-block"/>
        </p>
    </form>
</body>
</html>


【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。