Mybatis+Servlet+Mysql 整合的一个小项目:对初学者非常友好,有助于初学者很快的上手Java Web

Posted 游坦之

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis+Servlet+Mysql 整合的一个小项目:对初学者非常友好,有助于初学者很快的上手Java Web相关的知识,希望对你有一定的参考价值。

文章目录

前言

为何要写?

首先声明这是一个非常简单的项目,只包含注册和登录。

有人说了,这么简单的项目,我瞧不上。确实!对于一些高手来说,这点东西不过是毛毛雨。

但是对于一个初学者来说,有一个简单易上手的项目可以吧Mybatis+Servlet+mysql 整合起来,对于自己的学习不可不算是一个良好的契机。

学以致用,本文章旨在检验前面系列文章是否写的合格,结果是:

理论性太强,而实践太散,所以借着这篇文章,把实践的方便加强

目录结构

1 依赖配置

1.1 创建一个web项目

不会的可以看这篇文章 http://t.csdn.cn/UahZN

1.2 依赖需求分析

mybatis+Servlet很显然需要用到二者的依赖,mybatis需要连接数据库,所以需要数据库的依赖,数据库则需要实体类,为了简便开发引入Lombok依赖。想要使用单元测试,则还需要引入junit依赖。

所以总共需求如下依赖

  • mybatis

  • servlet

  • mysql

  • lombok

  • junit

1.3 pom.xml

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.you</groupId>
  <artifactId>JavaWeb-Demo-06</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>JavaWeb-Demo-06 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--引入mybatis的依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
    </dependency>
    <!--引入Lombok的依赖-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.24</version>
    </dependency>
    <!--引入Servlet的依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!--引入Mysql的依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.30</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>JavaWeb-Demo-06</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

2 配置Mybatis

参考自自己的文章《Mybatis的快速入门》 http://t.csdn.cn/3SXlb 《Mybatis的代理开发》http://t.csdn.cn/Bt8Xi

2.1 mybatis-config.xml

mybatis-config配置,主要包括两个点:

  • **数据库配置:**数据库名称、JDBC、数据库用户名和密码
  • Mapper:让Mybatis找到Mapper.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">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/us80?useSSL=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="200201203332"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com/you/Mapper"/>
    </mappers>
</configuration>

2.2 UserMapper.xml

这个知识点是漏网之鱼,没有意识到即使是使用注解配置sql语句,也需要接口绑定。

<?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.you.Mapper.UserMapper">

</mapper>

2.3 UserMapper.interface

package com.you.Mapper;

import com.you.Dept.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper 
    @Select("select * from user where user_name = #user_name and user_pwd = #user_pwd")
    public User selectUserByInfo(@Param("user_name") String user_name,@Param("user_pwd") String user_pwd);
    @Select("select * from user")
    public List<User> queryAllUsers();
    @Insert("insert into user values(null,#user_name,#user_pwd,#user_emil)")
    public boolean registerUser(@Param("user_name") String user_name,@Param("user_pwd") String user_pwd,@Param("user_emil") String user_emil);


3 配置Tomcat

参考本人的文章 《idea集成Tomcat》 http://t.csdn.cn/6Uma5

4 Servlet类

4.1 loginServlet01

处理登录的功能,需要注意的点:

  1. JavaWeb_Demo_06_war是自己的虚拟目录,每个人配置的都不一样 Tomcat文章中提到了
  2. Mybatis的缺点:和数据库交互时都需要重新连接数据库
  3. request获取数据的时候,要设置编码为UTF-8,不然会乱码
package com.you.request;

import com.you.Dept.User;
import com.you.Mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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.InputStream;
import java.io.PrintWriter;
import java.util.Timer;
import java.util.TimerTask;

@WebServlet(urlPatterns = "/login")
public class loginRequset01 extends HttpServlet 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
        /* 1、获取携带的用户名和密码 */
        System.out.println("进来!!!");
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("用户名:"+username);
        System.out.println("密码:"+password);

        String resource = "mybatis-config.xml";
        InputStream inputStream = null;

        inputStream = Resources.getResourceAsStream(resource);

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

        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user1 = mapper.selectUserByInfo(username,password);
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = resp.getWriter();

        if(user1!=null)
        
            resp.sendRedirect("/JavaWeb_Demo_06_war/index.html");

        else
            resp.sendRedirect("/JavaWeb_Demo_06_war/errorPage.html");
        
    

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


4.2 registerRequest01

处理注册的功能,需要注意的点:

  1. 修改数据库(update、insert)时,需要提交(commit)才能生效
package com.you.request;

import com.you.Dept.User;
import com.you.Mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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.InputStream;
import java.io.PrintWriter;
@WebServlet("/registerRequest01")
public class registerRequest01 extends HttpServlet 
    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException 
        /* 1、获取携带的用户名、密码、邮箱 */
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String useremail = req.getParameter("useremail");


        /* 2、连接数据库 */
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        /* 3、执行SQL语句 */
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        boolean user = mapper.registerUser(username, password, useremail);

        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = resp.getWriter();

        if(user!=false)
        
            sqlSession.commit();
            resp.sendRedirect("/JavaWeb_Demo_06_war/transmitPage.html");

        else


        
    

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)以上是关于Mybatis+Servlet+Mysql 整合的一个小项目:对初学者非常友好,有助于初学者很快的上手Java Web的主要内容,如果未能解决你的问题,请参考以下文章

Spring+SpringMVC+Mybatis+Mysql整合实例

Spring+SpringMVC+Mybatis+Mysql整合实例

SpringBoot整合Mybatis

SSM框架的整合

springboot整合mybatis+mysql+druid数据源

Spring整合MyBatis(Maven+MySQL)